检查远程进程是否正在运行(Linux)

3

我有以下代码,用于检查脚本是否在运行(脚本名为my_script.sh):

ps cax | grep my_script.sh > /dev/null
if [ $? -eq 0 ]
then
    echo "Process is running."
else
    echo "Process is not running."
fi

然而,我想修改这个功能,检查进程是否在另一台机器上运行,而不需要直接ssh连接,因为如果我正在循环中运行该脚本,则会使我退出当前脚本。

实际上,我想做到这一点:

ssh otherMachine
ps cax | grep my_script.sh > /dev/null
if [ $? -eq 0 ]
then
    echo "Process is running."
else
    echo "Process is not running."
fi
ssh originalMachine

任何帮助都将不胜感激。谢谢!


将脚本复制到 otherMachine 并作为 ssh otherMachine check_script.sh 运行。 - Jakuje
@Jakuje 我想把脚本保留在 originalMachine 上,因为最终的计划是在 originalMachine 上执行其他脚本,如果进程没有在 otherMachine 上运行。 - CdSdw
你所说的“如果我在循环中运行它,这会打破当前脚本”,具体是什么意思?你是指远程SSH连接没有结束吗? - nephtes
2个回答

8
我不确定这是否符合您的要求,但您可以在ssh调用中直接执行远程机器上的检查命令。返回值应该对应于在远程机器上调用的命令的返回值。
当然,您需要启用无密码身份验证方法(例如ssh密钥)。
ssh otherMachine "ps cax | grep my_script.sh > /dev/null"
if [ $? -eq 0 ]
then
    echo "Process is running."
else
    echo "Process is not running."
fi

1
这是一个简单的解决方案,用于检查程序是否在远程位置运行。

ssh root@192.168.22.12 -p 22 -t "pgrep -fl while.sh"

(注:该命令为检查名为while.sh的程序是否在IP地址为192.168.22.12的远程服务器上运行)
if [ $? -eq 0 ]; then echo "Process is running."; else   echo "Process is not running."; fi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接