ping/ssh一个网段内的所有ip

44 篇文章 0 订阅
1 篇文章 0 订阅

今天遇到一个问题,树莓派接上电源,但没有显示器,只能通过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的作用是在退出连接后不再继续执行脚本
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值