Fabric远程后台执行脚本

199 阅读1分钟

问题

  • 工作中遇到项目启动,分为5个jar,项目有启动和关闭都有顺序要求,在使用fabric直接执行nohup stop.sh &的时候,发现并没有执行成功过了,只会在远程机器上短时间看到该命令进程存在,然后退出,没有执行成功。

解决办法

  1. 使用已经存在daemon技术,如init、supervisord、upstart、systemd等
  2. 使用screen、tmux、dtach等工具来从当前shell中detach进程,注意关闭pty
  3. 使用nohup
nohup方式(比较麻烦,不推荐)
(nohup sh stop.sh >& /dev/null < /dev/null &) && sleep 1

# 下面这个没有尝试
nohup sh -c "( ( sh stop.sh &>/dev/null ) & )

如果脚本中含有nohup启动,记得也要按上述方式

dtach方式
# 安装
# yum install dtach -y

from fabric import Connection, Config
config = Config(overrides={'load_ssh_configs':False,"run.pty": False
cmd='cd /root/server && sh start.sh'
re = Connection(host=host, connect_timeout=2, config=config).run('dtach -n `mktemp -u /tmp/%s.XXXX` %s'  % ('startGs',cmd))

screen(推荐)
# 安装
# yum install screen -y

from fabric import Connection, Config
config = Config(overrides={'load_ssh_configs':False,"run.pty": False})

Connection(host=host, connect_timeout=2, config=config).run("screen -dmS test1 bash -c 'source /etc/profile && cd /root/server && sh start.sh && sleep 360'")