Background process for ssh port forwarding

Jesse Rosenthal jr2075 at
Sun Oct 2 01:17:39 CEST 2005

Hello all,

I'm writing a script which will backup data from my machine to a server
using rsync. It checks to see if I am on the local network. If I am, it
runs rsync over ssh to using the pexpect module to log in.
That's the easy part.

Now, when I'm not on the local network, I first want to open up an ssh
connection to do port forwarding, so something like this:

def hostforward():
    #This is based on the assumption that the passfile is the gnus
    #authinfo file, or has a similar format...
    f = open(PASS_FILE, "r")
    f_list =' ')
    #Now, we get the entry after "password" (be slicker to make it a
    #dictionary, but maybe wouldn't work as well).
    pass_index = f_list.index('password') + 1
    forwardpass = f_list[pass_index]
    #now we connect
    command = 'ssh -l %s -L 2022:%s:22 %s' % \
              (login, my_server, forwarding_server)
    connection = pexpect.spawn(command)

If I end this with 'connection.interact()', I will end up logged in to the
forwarding server. But what I really want is to go on and run rsync to
localhost port 2022, which will forward to my_server port 22. So, how can
I put the ssh connection I set up in hostforward() in the background?
I need to make sure that connection is made before I can run the rsync

I've looked at threading, but that seems excessive. There must be an
easier way. Whatever I do, though, I'll need to use pexpect to spawn the
processes, since I'll need to log in to ssh servers with a password.

Thanks for any help.


More information about the Python-list mailing list