Skip to content
Advertisement

Get the PID of a process started with sudo via ssh

I need the process id of a process (here sleep 20) started remotely via SSH and sudo.

date is inserted to illustrate the duration of the SSH connection. Without connection there is also no process on my remote machine, of course.

$ date; ssh pc1 "sleep 20 & echo $!"; date                            # works
Mi 20. Jan 16:18:29 CET 2016
11540
Mi 20. Jan 16:18:50 CET 2016
$ date; ssh pc1 "echo password | sudo -S sleep 20"; date               # works
Mi 20. Jan 16:20:44 CET 2016
[sudo] password for lab: Mi 20. Jan 16:21:04 CET 2016
$ date; ssh pc1 "echo password | sudo -S sleep 20 & echo $!"; date    # does not
Mi 20. Jan 16:21:55 CET 2016
11916
Mi 20. Jan 16:21:56 CET 2016

On a second machine the last, complete command works fine:

$ date; ssh pc2 "echo password | sudo -S sleep 20 & echo $!"; date
Mi 20. Jan 16:23:40 CET 2016
6035
[sudo] password for lab: Mi 20. Jan 16:24:01 CET 2016

Any suggestion why there is this different behaviour of the two machines?

Info: I know the risk of clear passwords but it’s a shared account in an isolated test network.

Advertisement

Answer

It looks like an issue with incomplete process dependencies. With some additional milliseconds the connection (and process) keeps established the whole time.

$ date; ssh pc1 "echo password | sudo -S sleep 20 & echo $! && sleep 0.01"; date
Do 21. Jan 14:50:39 CET 2016
[sudo] password for lab: 6841
Do 21. Jan 14:51:00 CET 2016
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement