如果我使用
timeout 10 ssh -n -o BatchMode=yes 1.1.1.1 'sleep 20' > 1.1.1.1.txt 2>&1 &
Run Code Online (Sandbox Code Playgroud)
在服务器上发出远程命令,我在 10 秒后终止 SSH 连接,然后我可以看到sleep 20
服务器上仍在运行,但没有 SSH 连接。
超时后如何终止远程命令,例如 10 秒?
远程机器是 AIX 6.1(或 SLES)并且没有可用于“超时”的包。我的客户端是 Ubuntu 10.03。
假设您的远程服务器有一个符合 POSIX 的 shell,以下应该可以工作:
ssh ...options... 'command & pid=$!; sleep 20; kill $pid'
Run Code Online (Sandbox Code Playgroud)
事实上,POSIX 标准规定$!
:
扩展为从当前 shell 执行的最新后台命令(请参阅列表)的十进制进程 ID。(例如,从子shell 执行的后台命令不会影响当前shell 环境中“$!”的值。)对于管道,进程ID 是管道中最后一个命令的进程ID。
如果远程系统有作业控制,你可以这样缩短它:
ssh ...options... 'command & sleep 20; kill %1'
Run Code Online (Sandbox Code Playgroud)