今天遇到一个问题,树莓派接上电源,但没有显示器,只能通过ssh连接,而使用之前的ip无法连接,估计是分配的ip变化了。所以目前已知的信息只有10.8.81.x网段,如果一个一个试太麻烦了,我们可以通过shell脚本自动帮我们一个一个ip尝试。
ping
一行代码
for i in {1..254}; do ping -c 2 -W 1 10.8.81.$i; if [ $? -eq 0 ]; then continue >> pingall.log; else echo 'down'; fi; done
或者脚本文件
#!/bin/sh
for i in {1..254}; do
ping -c 2 -W 1 10.8.81.$i
if [ $? -eq 0 ]; then continue >>pingall.log; else echo 'down'; fi
done
上面的脚本实现逐个ping从10.8.81.1到10.8.81.254之间的ip,将ping通的ip写入pingall.log文件中,-c参数表示ping两次,-W参数表示超时时间
能ping通就表示有可能是目标ip,再从这些ip中寻找就好了
参考:https://www.huaweicloud.com/articles/f4994d1fb22beaf7c440b02704d90d74.html
ssh
当然我们也可以不ping,直接ssh
但ssh不允许我们在命令中指定密码,所以我们需要借助sshpass
安装sshpass
在debian系操作系统上可通过命令
>>> sudo apt install sshpass
centos可通过命令
>>> sudo yum install sshpass
mac可通过命令
>>> curl -L https://raw.githubusercontent.com/kadwanev/bigboybrew/master/Library/Formula/sshpass.rb > sshpass.rb && brew install sshpass.rb && rm sshpass.rb
参考:https://stackoverflow.com/a/32258393/7151777
逐个ssh
一行代码
>>> for i in {1..254}; do sshpass -p xxxxxx ssh -o ConnectTimeout=1 -o StrictHostKeyChecking=no pi@10.8.81.$i; if [ $? -eq 0 ]; then break; else continue; fi; done
或者脚本文件
#!/bin/sh
for i in {1..254}; do
sshpass -p xxxxxx ssh -o ConnectTimeout=1 -o StrictHostKeyChecking=no pi@10.8.81.$i
if [ $? -eq 0 ]; then break; else continue; fi
done
- -p xxxxx 指定密码
- -o ConnectTimeout=1表示连接超时时间为1秒
- -o StrictHostKeyChecking=no 表示禁用strict host key checking,加上这个就不会在连接新IP时出现下面的内容了
The authenticity of host '10.8.81.141 (10.8.81.141)' can't be established.
ECDSA key fingerprint is SHA256:f4VMVf7zI6Nz/nebgZLtCcDFpivcG17zE47SDw0v0sk.
Are you sure you want to continue connecting (yes/no/[fingerprint])?
参考:https://askubuntu.com/a/167753/685786
- break的作用是在退出连接后不再继续执行脚本