我在用于远程端口转发的脚本中运行 autossh,如果连接超时、ip、端口不存在或响应,我需要退出、终止、停止脚本,而不使用 ssh、sshd 配置文件,是这样吗可能的? 没有答案,在堆栈站点或 autossh 的联机帮助页上找到。
示例 1:
myautossh 脚本
#!/bin/bash
/usr/bin/autossh -NT -o "ExitOnForwardFailure=yes" -R 5555:localhost:443 -l user 1.1.1.1
if [ $? -eq 0 ]; then
echo "SUCCESS" >> errorlog
else
echo "FAIL" >> errorlog
fi
示例 2:
myautossh 脚本
#!/bin/bash
/usr/bin/autossh -f -NT -M 0 -o "ServerAliveInterval=5" -o "ServerAliveCountMax=1" -o "ExitOnForwardFailure=yes" -R 5555:localhost:443 -l user 1.1.1.1 2>> errorlog
if [ $? -eq 0 ]; then
echo "SUCCESS" >> errorlog
else
echo "FAIL" >> errorlog
kill $(ps aux | grep [m]yautossh | awk '{print $2}')
fi
IP 1.1.1.1 在我的网络中不存在,因此连接超时,但脚本和 autossh 仍在运行,已检查:
ps aux | grep [m]yautossh
或
ps x | grep [a]utossh
只能用ctrl+c终止脚本
我想在脚本中运行 autossh,尝试连接到一个不存在的 ip 或端口并终止、退出、终止 autossh 进程以继续我的脚本,没有配置 ssh 和 sshd 配置文件,只有选项/autossh 命令和使用 -f
作为背景,这可能吗?
最佳答案
将超时与 --preserve-status 一起使用是您所需要的
timeout allows you to run a cmmand with a time limit
Preserving the Exit Status, timeout with --preserve-status returns 124 when the time limit is reached. Otherwise, it returns the exit status of the managed command
这将在 2 秒后终止命令并返回命令的退出状态,如果不等于 0,则命令不成功,您无法建立成功的连接
#!/bin/bash
timeout --preserve-status 2 /usr/bin/autossh -NT -o "ExitOnForwardFailure=yes" -R 33333:localhost:443 -l user 1.1.1.1
if [ $? -eq 0 ]; then
echo "Connection success"
else
echo "Connection fail"
fi
关于bash - 如果连接超时、ip、端口不存在或不使用 ssh 和 sshd 配置文件进行响应,我该如何退出、停止、终止 autossh?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73401285/