Background process for ssh port forwarding

John Hazen john at hazen.net
Tue Oct 4 15:40:27 EDT 2005


Hi Jesse-

> 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 = f.read().split(' ')
>     f.close()
>     #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)
>     connection.expect('.*assword:')
>     connection.sendline(forwardpass)
> 
> 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
> command.

I think what's happening is that when you return from 'hostforward', the
connection is being closed because of garbage collection.  Python uses
(among other stuff) reference counting to tell it when to delete
objects.  After hostforward returns from execution, there are no longer
any references to 'connection', so it gets deleted, which cleans up the
connection.

You probably want to add:

    return connection

at the end of hostforward, and call it like:

connection = hostforward()
my_rsync_function()
connection.close()   # or whatever the approved pexpect cleanup is


Hope that helps-

John



More information about the Python-list mailing list