如何使用 ssh 在后台运行命令并分离会话 [英] how to run a command in background using ssh and detach the session

查看:31
本文介绍了如何使用 ssh 在后台运行命令并分离会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试通过 ssh 连接到远程机器并运行脚本,然后让节点运行脚本.下面是我的脚本.但是,当它运行时,脚本在机器上成功运行但 ssh 会话挂起.有什么问题?

I'm currently trying to ssh into a remote machine and run a script, then leave the node with the script running. Below is my script. However, when it runs, the script is successfully run on the machine but ssh session hangs. What's the problem?

ssh -x $username@$node 'rm -rf statuslist
                        mkdir statuslist
                        chmod u+x ~/monitor/concat.sh
                        chmod u+x ~/monitor/script.sh
                        nohup ./monitor/concat.sh &
                        exit;'

推荐答案

有些情况下,您想在远程机器/服务器(会自动终止)上执行/启动某些脚本并断开与服务器的连接.

There are some situations when you want to execute/start some scripts on a remote machine/server (which will terminate automatically) and disconnect from the server.

>

例如:运行在盒子上的脚本,当执行时

eg: A script running on a box which when executed

  1. 获取模型并将其复制到远程服务器
  2. 创建一个脚本来运行模型的模拟并将其推送到服务器
  3. 在服务器上启动脚本并断开连接
  4. 由此启动的脚本的职责是在服务器中运行模拟,并在完成后(需要数天才能完成)将结果复制回客户端.

我会使用以下命令:

ssh remoteserver 'nohup /path/to/script `</dev/null` >nohup.out 2>&1 &'

@CKeven,您可以将所有这些命令放在一个脚本中,将其推送到远程服务器并按如下方式启动它:

@CKeven, you may put all those commands on one script, push it to the remote server and initiate it as follows:

echo '#!/bin/bash  
rm -rf statuslist  
mkdir statuslist  
chmod u+x ~/monitor/concat.sh  
chmod u+x ~/monitor/script.sh  
nohup ./monitor/concat.sh &  
' > script.sh

chmod u+x script.sh

rsync -azvp script.sh remotehost:/tmp

ssh remotehost '/tmp/script.sh `</dev/null` >nohup.out 2>&1 &'

希望这有效;-)

你也可以使用ssh user@host 'screen -S SessionName -d -m "/path/to/executable"'

You can also use ssh user@host 'screen -S SessionName -d -m "/path/to/executable"'

创建一个分离的屏幕会话并在其中运行目标命令

Which creates a detached screen session and runs target command within it

这篇关于如何使用 ssh 在后台运行命令并分离会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆