【问题标题】:Loop until connected to SSH循环直到连接到 SSH
【发布时间】:2012-03-14 19:29:28
【问题描述】:

有时在连接到远程 SSH 服务器时,我会收到 Connection Closed By *IP*; Couldn't read packet: Connection reset by peer.,但在尝试一两次后,它可以正常连接。

这给我用来自动将存档备份上传到 SSH 服务器的一些 bash 脚本带来了问题,就像这样;

export SSHPASS=$sshpassword
sshpass -e sftp -oBatchMode=no -b - root@$sshaddress << !
   cd $remotefolder
   put $backupfolder/Qt_$date.sql.gz
   bye
!

在真正正确连接之前,我怎样才能让这部分循环?

更新:(解决方案)

RETVAL=1
while [ $RETVAL -ne 0 ]
do
export SSHPASS=$sshpassword
sshpass -e sftp -oBatchMode=no -b - root@$sshaddress << !
   cd $remotefolder
   put $backupfolder/Qt_$date.tgz
   bye
!
RETVAL=$?
[ $RETVAL -eq 0 ] && echo Success
[ $RETVAL -ne 0 ] && echo Failure
done

【问题讨论】:

  • 解决真正的问题,“coudln't read packet: connection reset by peer”。
  • 即使我这样做了,我仍然想要一种方法来验证它是否已连接,如果未连接则循环...据我所知,服务器正在重新启动或出现网络问题在备份脚本从 cron 运行时。
  • @natli,您是否尝试在循环内连接?例如:i=0; until ssh $user@$ip || [ $i -eq 10 ]; do sleep 1; (( i++ )); done

标签: linux bash ssh


【解决方案1】:

试试这样的:

export SSHPASS=$sshpassword

sshpassFunc() {
    sshpass -e sftp -oBatchMode=no -b - root@$sshaddress << !
    cd $remotefolder
    put $backupfolder/Qt_$date.sql.gz
    bye
!
}

until sshpassFunc; do
    sleep 1
done

(未测试)

【讨论】:

  • 现在由此产生的每个进程都清楚地知道您的密码,因为您通过环境变量导出了密码。请在这些情况下使用无密码公钥交换。
【解决方案2】:

我不是shell脚本专家,但我会在sshpass退出时检查它的返回值。

来自man ssh

ssh exits with the exit status of the remote command or
with 255 if an error occurred.

来自man sshpath

返回值

与任何其他程序一样,sshpass 在成功时返回 0。的情况下 失败,使用以下返回码:

  1. 命令行参数无效
  2. 给出的参数冲突
  3. 一般运行时错误
  4. 来自 ssh 的无法识别响应(解析错误)
  5. 密码无效/不正确
  6. 主机公钥未知。 sshpass 退出而不确认新密钥。

另外,ssh可能在抱怨中间有男人 攻击。此投诉不会发送到 tty。换句话说,即使 使用 sshpass,来自 ssh 的错误消息会打印到标准错误中。 在这种情况下,ssh 的返回码会被报告回来。这通常是 对于所有错误情况,都是一个缺乏想象力(且不提供信息)的“255”。

因此尝试运行该命令,并检查其返回值。如果返回值不是0(对于SUCCESS),那么再试一次。重复使用 while 循环,直到成功。

旁注:您为什么使用sshpass 而不是public-key (passwordless) authentication? 它更安全(您不必写下您的密码)并且通过常规ssh 登录就像ssh username@host 一样简单。

even an easy tool to set it up: ssh-copy-id.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 2015-08-28
    • 2019-09-25
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多