Getting pid of a remote process

Miles semanticist at gmail.com
Tue Aug 19 09:25:06 EDT 2008


On Mon, Aug 18, 2008 at 9:34 AM, srinivasan srinivas wrote:
> Could you please suggest me a way to find pid of a process started on a remote machine by the current process??

If ps + grep (or the more robust tool pgrep) won't work because you're
running more than one instance at once, try this: instead of running
the process via SSH directly, write a small wrapper script which runs
the process locally and saves the PID to a file on the machine (or
prints it to stdout if the program itself has no output), and then run
that wrapper remotely.

For example:

import subprocess, sys
f = open(sys.argv[1], 'w')
p = subprocess.Popen(sys.argv[2:])
print >>f, p.pid
f.close()

You may have to be careful with the quoting of the arguments, since
OpenSSH uses a shell to execute the command.  You could then obtain
the pid with something along the lines of:

int(subprocess.Popen(['ssh', <hostname>, 'cat', <pidfile>],
stdout=subprocess.PIPE).stdout.read())

-Miles



More information about the Python-list mailing list