get the pid of a process with pexpect

Karim Bernardet bernardet at cppm.in2p3.fr
Tue May 6 08:43:37 EDT 2008


Many thanks !
This is what I did

for mytunnel.py :
I use pexpect like this
tunnel_command = '''bash -c "ssh -N -R 60011:localhost:60002 
username at xxxxx.fr "'''
....
com="echo \""+str(ssh_tunnel.pid)+"\" >> pids"
...
time.sleep(172800)

in the bash script which calls mytunnel.py :
./mytunnel.py ${USERN} ${HMM} ${P2USE} ${p2use2}  &
echo $! >>pids

this way I have all the pids

Cheers !


Noah wrote:
> On May 5, 7:18 am, Karim Bernardet <bernar... at cppm.in2p3.fr> wrote:
>> ssh_tunnel = pexpect.spawn (tunnel_command % globals())
>> ...
>> print ssh_tunnel.pid
>>
>> but ssh_tunnel is not the pid of the ssh tunnel
>>
>> Is there a way to get it using pexpect ?
> 
> You will notice that you can't get this information even from the
> shell. This does not work of course:
> 
>     ssh -f -N -L 81:localhost:80 noah at www.example.com
>     echo $!
> 
> However, this seems to work, but I don't trust it. Certainly it isn't
> a real daemon, but this work OK for you if you only need to manage the
> tunnel for the duration of your script. Notice that now Bash had the
> PID in $! variable:
> 
>     ssh -N -L 81:localhost:80 noah at www.example.com &
>     TUNNEL_PID=$!
>     echo $TUNNEL_PID
> 
> What command-line are you using for 'tunnel_command'? This is hard
> because SSH does not provide a way to get the PID of the tunnel if you
> request ssh to go to the background (see the -f option). I always
> considered this a bug because it makes scripting hard. Even if you
> start the tunnel from a shell you can't use $! to get the PID because
> the daemonizing is initiated by ssh. This is not the same use using
> the shell to put a command into the background, so the shell won't
> know anything about the PID.
> 
> I'm not sure if you can put ssh into the background using the shell
> and still have the tunnel work. So you might start a tunnel something
> like this:
> 
>     ssh -f -N -L 80:localhost:80 username at www.example.com
> 
> But can you also do something like this?
> 
>     ssh -N -L 80:localhost:80 username at www.example.com &
>     echo $!
> 
> And for that to even work you will have to use Pexpect to start bash.
> Remember, Python doesn't start your command in a subshell, so you have
> to specify it if you want. So your tunnel command would have to be
> something like this:
> 
>     tunnel_command = '''bash -c "ssh -N -L ...foo... &"'''
>     ssh_tunnel = pexpect.spawn (tunnel_command % globals())
> 
> --
> Noah




More information about the Python-list mailing list