我想编写一个 bash 脚本,通过 ssh 在远程服务器上执行一些命令。然后我需要重新启动远程服务器,通过 ssh 再次连接并执行更多命令。
我正在使用这段代码:
ssh $theip 'sudo reboot'
echo "starting sleep---1"
sleep 30
echo " finished sleeping1"
while ! ping -c 1 $theip &>/dev/null; do echo "waiting..."; done
echo "starting sleep---2"
sleep 45
echo " finished sleeping2"
echo "finished rebooting"
ssh $theip 'commands....'
问题是,有时服务器在我可以 ssh 到它之前返回 ping,然后脚本失败。我的一些服务器需要超过 45 秒的睡眠时间。还有其他方法可以做到这一点吗?例如,尝试在 while 循环中使用 ssh 而不是 ping?
谢谢,
答案1
尝试使用以下命令来获取“粘性 ssh”:
while true; do command ssh "$@"; [ $? -eq 0 ] && break || sleep 0.5; done
答案2
ls -l
根据您的运行级别进行操作/etc/rc3.d
或/etc/rc5.d
根据您的运行级别进行操作。这里需要注意的是网络守护进程在 ssh 守护进程之前启动。因此ping
之前可用ssh
。在远程计算机上执行之前,您可能应该wait
多做一些操作。ssh
就我而言,大约有 19 个服务在网络之后、ssh 之前启动。
lrwxrwxrwx 1 root root 17 Sep 9 2011 S10network -> ../init.d/network
lrwxrwxrwx 1 root root 16 Sep 9 2011 S11auditd -> ../init.d/auditd
lrwxrwxrwx 1 root root 21 Sep 9 2011 S12restorecond -> ../init.d/restorecond
lrwxrwxrwx 1 root root 16 Sep 9 2011 S12syslog -> ../init.d/syslog
lrwxrwxrwx 1 root root 20 Sep 9 2011 S13irqbalance -> ../init.d/irqbalance
lrwxrwxrwx 1 root root 19 Sep 9 2011 S15mdmonitor -> ../init.d/mdmonitor
lrwxrwxrwx 1 root root 19 Sep 9 2011 S18rpcidmapd -> ../init.d/rpcidmapd
lrwxrwxrwx 1 root root 17 Sep 9 2011 S19rpcgssd -> ../init.d/rpcgssd
lrwxrwxrwx 1 root root 15 Sep 9 2011 S20kdump -> ../init.d/kdump
lrwxrwxrwx 1 root root 20 Sep 9 2011 S22messagebus -> ../init.d/messagebus
lrwxrwxrwx 1 root root 24 Sep 9 2011 S23setroubleshoot -> ../init.d/setroubleshoot
lrwxrwxrwx 1 root root 15 Sep 9 2011 S25netfs -> ../init.d/netfs
lrwxrwxrwx 1 root root 15 Sep 9 2011 S25pcscd -> ../init.d/pcscd
lrwxrwxrwx 1 root root 15 Sep 9 2011 S26acpid -> ../init.d/acpid
lrwxrwxrwx 1 root root 19 Sep 9 2011 S26haldaemon -> ../init.d/haldaemon
lrwxrwxrwx 1 root root 14 Sep 9 2011 S26hidd -> ../init.d/hidd
lrwxrwxrwx 1 root root 20 Sep 9 2011 S26lm_sensors -> ../init.d/lm_sensors
lrwxrwxrwx 1 root root 16 Sep 9 2011 S28autofs -> ../init.d/autofs
lrwxrwxrwx 1 root root 15 Sep 9 2011 S50hplip -> ../init.d/hplip
lrwxrwxrwx 1 root root 15 Sep 13 2011 S50snmpd -> ../init.d/snmpd
lrwxrwxrwx 1 root root 14 Sep 9 2011 S55sshd -> ../init.d/sshd