简体   繁体   中英

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.

Something like this?

$ remote_pid=$(ssh mauro@planck 'sleep 20 > /dev/null 2>&1 & echo $!')
$ echo $remote_pid
13878

or...

$ remote_pid=$(ssh mauro@planck 'echo secret | sudo -S sleep 20 > /tmp/log 2>&1  & echo $!')

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM