linux - 获取使用 sshpass 启动的远程进程的 PID

标签 linux pid nohup sshpass

我有一个 bash 脚本需要在远程机器上启动一些进程。 我已经使用 sshpass 做到了这一点命令。

我需要存储那个远程进程的 PID。

我用脚本尝试了以下操作:

sshpass -p password ssh user@ipaddr /bin/bash << EOF nohup process > /dev/null 2>&1 & echo $! > pid_file cat pid_file EOF

当我检查远程机器时,进程启动并且 pid_file 中也写入了一个数字。但是进程id和pid_file的编号不匹配。

在没有脚本的情况下直接在终端上执行上述命令集,不会在 pid_file 中写入任何内容。

有人可以帮助存储远程进程的正确 pid。

最佳答案

sshpass -p password ssh user@ipaddr /bin/bash << EOF
nohup process > /dev/null 2>&1 & echo $! > pid_file
cat pid_file
EOF

问题是 $! 不是在远程计算机上而是在您的计算机上展开的。使用 Here document 时, 变量名被它们的值替换。因此它会扩展到您在计算机后台运行的任何进程。您需要在远程计算机上执行 echo $!。这就是为什么最好使用 -c 并始终正确地包含参数。

sshpass -p password ssh user@ipaddr /bin/bash -c 'nohup process >/dev/null 2>&1 & echo $! > pid_file'

或者你可以转义 $!:

sshpass -p password ssh user@ipaddr /bin/bash <<EOF
nohup process > /dev/null 2>&1 & echo \$! > pid_file
cat pid_file
EOF

或者最好是在此处使用引号字符串定界符:

sshpass -p password ssh user@ipaddr /bin/bash <<'EOF'
nohup process > /dev/null 2>&1 & echo $! > pid_file
cat pid_file
EOF

关于linux - 获取使用 sshpass 启动的远程进程的 PID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50851668/

相关文章:

linux - 使用 playframework 执行 nohup 命令得到错误的文件描述符错误

bash - 如何将已经运行的进程置于 nohup 下?

background-process - Linux top 不以批处理模式将完整命令名作为 nohup 进程打印到文件

linux - 创建一个名为 hello.txt 的文件,其中包含单词 "hello world"?

bash - 如何终止后台/分离的 ssh session ?

linux - scp作为后台工作?

C++ 使用带任务列表的命令提示符扫描进程 ID

javascript - Grunt pid 文件和 Grunt-kill

python - 什么是 os.fdopen() 语义?

linux - 在一台机器上模拟telnet通信