python调用命令行获取pid,Bash:通过ssh启动远程python应用程序并获取其PID

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.

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!"

The important lines are:

ssh root@myserver 'python /root/python/run_dev_server.py > /dev/null 2>&1 &'

SERV_PID=$(ssh root@myserver 'echo $!')

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 $!')

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 $!'

i get a PID printed to the terminal.

Any advice on this would be really appreciated.

解决方案

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"'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值