Bash:通过ssh启动远程python应用程序并获取其PID [英] Bash: start remote python application through ssh and get its PID
问题描述
我正在创建一个bash脚本,将新文件从Windows机器复制到远程linux centos服务器(我使用git-shell运行此脚本),然后我想重新启动服务器上运行的python应用程序,使用这些新文件.
I'm creating a little bash script to copy new files from a windows machine to a remote linux centos server (i run this script using the git-shell) then i want to restart the python application thats running in the server to use those new files.
问题在于,每次我运行此脚本时,我都想在再次启动之前结束实际的运行过程,因此我想获取启动过程的pid并将其保存到远程主机中的文件中,因此我可以从那里下一次我运行该程序读它并杀死它.
The problem is that everytime i run this script i want to end the actual running process before i start it again, so i want to get the pid of the process i start and save it to a file in the remote host so i can read it from there the next time i run the program and kill it.
到目前为止,我的代码与此类似:
My code by now looks similar to this:
echo "Copying code files to server..."
# The destination folder has to exist in the server
scp -r ./python/ root@myserver:/root/
echo "Checking for running processes..."
if ssh root@myserver 'ls dmr.pid >/dev/null'; then
echo "PID file exists, reading file..."
PID=$(ssh root@myserver 'cat dmr.pid')
# Terminate the actual process
echo "Terminating the process with PID '$PID'..."
ssh root@myserver 'kill $PID'
else
echo "PID file doesn't exist, not known processes running"
fi
# Restart the server and get the PID
echo "Restarting the server..."
ssh root@myserver 'python /root/python/run_dev_server.py > /dev/null 2>&1 &'
SERV_PID=$(ssh root@myserver 'echo $!')
echo "Saving PID to file dmr.pid"
ssh root@myserver "echo '$SERV_PID' > \"dmr.pid\""
echo "Sucesfully finished!"
重要的几行是:
ssh root@myserver 'python /root/python/run_dev_server.py > /dev/null 2>&1 &'
SERV_PID=$(ssh root@myserver 'echo $!')
这个问题是脚本完成了,但是文件和$ SERV_PID变量一样都是空的.
the problem with this is that the script finishes but the file ends up empty as well as the $SERV_PID variable.
如果我不重定向输出,只是做这样的事情:
And if i dont redirect the outputs and just do something like this:
SERV_PID=$(ssh root@myserver 'python /root/python/run_dev_server.py & echo $!')
在重新启动服务器"之后,我陷入了困境,从不获取PID或包含该PID的文件,甚至脚本的末尾.
i get stuck after "Restarting the server" and never get the PID or the file that will contain it or even the end of the script.
但是,如果我在控制台中运行此命令:
But if i run this right in the console:
ssh root@myserver 'python /root/python/run_dev_server.py & echo $!'
我在终端上打印了一个PID.
i get a PID printed to the terminal.
任何对此的建议,将不胜感激.
Any advice on this would be really appreciated.
推荐答案
感谢Kingslndian,我通过执行一个执行我所需的三个步骤的命令来解决了该问题,从而避免了在不同的shell中运行的问题:>
Thanks to Kingslndian i solved it by making one single command that did the three steps i required, so with that avoided the problem of running in different shells:
ssh root@myserver 'python /root/python/run_dev_server.py > /dev/null 2>&1 & echo $! > "dmr.pid"'
这篇关于Bash:通过ssh启动远程python应用程序并获取其PID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!