Bash - 通过 ARP table 循环并将 IP 存储在变量中
Bash - Cycling trough ARP table and storing IPs in a variable
因此,如果我想通过 SSH 连接到网络上的所有设备,使用 ARP table 确切知道连接到哪里,我该怎么做?
代码应该是这样的:
#!/bin/bash
for a in $([ARP Table here?])
do
ssh user@$a true
echo "Connected to $a"
done
我不确定如何将动态 IP 存储在 a 变量中。此外,我不确定我之后是否可以使用该变量通过 ssh 进行连接,因为 IP 不会是一个 int,而更可能是一个字符串。
编辑:在安德鲁让我注意到并非我网络上的所有设备都可以在我的 ARP table 中之后,我想知道:
是从0开始到当前网络掩码的最大值还是在ARP中搜索更好table?
以下是两种情况:
#!/bin/bash
for a in $(seq 255)
do
ssh user@172.18.10.$a true
echo "Connected to 172.18.10.$a"
done
或
#!/bin/bash
for a in $([ARP Table here?])
do
ssh user@$a true
echo "Connected to $a"
done
我将回答您的第一个问题(标题介绍的那个)。
要读取 arp table 并遍历其中的每个 IP 地址,您可以执行以下操作
#!/bin/bash
for a in $(arp -n | tail -n+2 | cut -d' ' -f1)
do
ssh user@$a true
echo "Connected to $a"
done
arp
命令输出 arp 缓存以及一些信息
关于每个条目。
tail
用于去掉第一行,即
包含 header 输出的不同列
arp
.
cut
删除所有附加信息,只留下
IP 地址,每行一个。
比开发自己的扫描工具更好的解决方案可能是使用已经存在的东西。
要查看可访问的 IP 地址(副作用会填充您的 ARP 缓存),您可以使用 fping
。它可能适用于您的 OS 或发行版。来自我本地网络的示例:
$ fping -g 10.1.1.0/29
10.1.1.1 is alive
10.1.1.2 is alive
10.1.1.5 is alive
10.1.1.3 is unreachable
10.1.1.4 is unreachable
10.1.1.6 is unreachable
fping
命令仅用于 ICMP -- 它发送 ping。如果您的目标不仅是确定存在哪些设备,而且还确定它们是否在 SSH 端口 (22) 上应答,您可以使用 tcping
或类似的东西。
for ip in $(seq -f "10.1.1.%g" 1 9); do
if tcping -u 200 -q $ip 22; then
echo "yes: $ip"
fi
done
编写脚本可能有点棘手的另一个选项是使用实际的扫描工具,例如 nmap
(as seen in The Matrix)。
如果您使用的是网络监控系统,请检查它是否内置了网络扫描工具。Cacti, for example, has a discovery plugin. Nagios has quite a few of them。
因此,如果我想通过 SSH 连接到网络上的所有设备,使用 ARP table 确切知道连接到哪里,我该怎么做?
代码应该是这样的:
#!/bin/bash
for a in $([ARP Table here?])
do
ssh user@$a true
echo "Connected to $a"
done
我不确定如何将动态 IP 存储在 a 变量中。此外,我不确定我之后是否可以使用该变量通过 ssh 进行连接,因为 IP 不会是一个 int,而更可能是一个字符串。
编辑:在安德鲁让我注意到并非我网络上的所有设备都可以在我的 ARP table 中之后,我想知道:
是从0开始到当前网络掩码的最大值还是在ARP中搜索更好table?
以下是两种情况:
#!/bin/bash
for a in $(seq 255)
do
ssh user@172.18.10.$a true
echo "Connected to 172.18.10.$a"
done
或
#!/bin/bash
for a in $([ARP Table here?])
do
ssh user@$a true
echo "Connected to $a"
done
我将回答您的第一个问题(标题介绍的那个)。
要读取 arp table 并遍历其中的每个 IP 地址,您可以执行以下操作
#!/bin/bash
for a in $(arp -n | tail -n+2 | cut -d' ' -f1)
do
ssh user@$a true
echo "Connected to $a"
done
arp
命令输出 arp 缓存以及一些信息 关于每个条目。tail
用于去掉第一行,即 包含 header 输出的不同列arp
.cut
删除所有附加信息,只留下 IP 地址,每行一个。
比开发自己的扫描工具更好的解决方案可能是使用已经存在的东西。
要查看可访问的 IP 地址(副作用会填充您的 ARP 缓存),您可以使用 fping
。它可能适用于您的 OS 或发行版。来自我本地网络的示例:
$ fping -g 10.1.1.0/29
10.1.1.1 is alive
10.1.1.2 is alive
10.1.1.5 is alive
10.1.1.3 is unreachable
10.1.1.4 is unreachable
10.1.1.6 is unreachable
fping
命令仅用于 ICMP -- 它发送 ping。如果您的目标不仅是确定存在哪些设备,而且还确定它们是否在 SSH 端口 (22) 上应答,您可以使用 tcping
或类似的东西。
for ip in $(seq -f "10.1.1.%g" 1 9); do
if tcping -u 200 -q $ip 22; then
echo "yes: $ip"
fi
done
编写脚本可能有点棘手的另一个选项是使用实际的扫描工具,例如 nmap
(as seen in The Matrix)。
如果您使用的是网络监控系统,请检查它是否内置了网络扫描工具。Cacti, for example, has a discovery plugin. Nagios has quite a few of them。