bash - 如果连接超时、ip、端口不存在或不使用 ssh 和 sshd 配置文件进行响应,我该如何退出、停止、终止 autossh?

标签 bash ssh openssh sshd autossh

我在用于远程端口转发的脚本中运行 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 

https://linuxize.com/post/timeout-command-in-linux/

关于bash - 如果连接超时、ip、端口不存在或不使用 ssh 和 sshd 配置文件进行响应,我该如何退出、停止、终止 autossh?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73401285/

相关文章:

git push 到远程仓库 "Could not read from remote repository"

php - 如何使用 PHP 设置交互式 SSH session ?

bash - 在期望脚本中发送 INSERT 和 F12

linux - 如何在 bash 中使用 grep 删除 span 标签?

bash - 如何使用 bash 运行 `mkdir -m -p` ?

bash - 期望 ssh 无密码

ssh - 如何在 Google Compute Engine 上创建的两个实例之间进行 ssh?

windows-server-2012-r2 - Windows 上的 OpenSSH - “XXX 无法在 __PROGRAMDATA__ 中保存您的公钥

linux - 如何创建基于 key 的 ssh 用户?

regex - 如何进行多行和非贪婪的模式范围匹配?