How to fix error with expect to ssh to device using python on windows?

65 Views Asked by At

On windows 10 I want to use pexpect to ssh to a device and execute some commands. I am using the following script:

ssh_command = '"C:\Program Files\PuTTY\plink.exe" -ssh [email protected]'
ssh_session = pexpect.popen_spawn.PopenSpawn(ssh_command)
ssh_session.expect('Using username "service".')
ssh_session.expect("[email protected]'s password:")
time.sleep(1)
ssh_session.sendline(pw1 + "\r")
time.sleep(1)
ssh_session.sendline("login root\r")
time.sleep(1)
ssh_session.expect("Password:")  # **
time.sleep(1)
ssh_session.sendline(pw2 + "\r")
time.sleep(1)

But I seem to get a timeout in the line marked with **. When I use

"C:\Program Files\PuTTY\plink.exe" -ssh [email protected]'

on the command line directly I can log in and all works (manually) as expected. How can I even investigate this problem?

1

There are 1 best solutions below

0
Alex On

I figured it out, the fix is just to remove the "\r" from sending the commands, as sendline send that EOL itself.

So just

ssh_session.sendline(pw1)