Search code examples
pythonpexpect

Pxssh reconnect Python (pexpect)


I need to do more then one connection in one script using pxssh. Trying to do like this:

import pxssh
ip = 'ip'
username = 'username'
password = 'password'
s = pxssh.pxssh()
s.login (ip, username, password)
s.sendline('command')
s.prompt()
print s.before
s.logout()
s.login(ip2, username, password)
etc

But getting error on the second connection: AssertionError: The pid member must be None. Only one connection per time is passing. How to get it work?


Solution

  • You just need to create a new pxssh object. The constructor for the pxssh object creates a process and spawns ssh. Logout disconnects from the remote system, which makes the connection useless but doesn't reset the object. Something like this:

    ...
    s.logout()
    s.close()
    s = pxssh.pxssh()
    s.login(ip2, ...)
    

    The s.close() is not strictly necessary but it's a good idea as otherwise, the underlying file descriptor will not be closed until the original object is garbage-collected.