是否可以从 Bash exec 通过 SSH 连接到所有网络客户端?
Is it possible to SSH to all network clients from a Bash exec?
我正在编写一个 shell 脚本,我希望能够 运行 一些命令,例如 arp -a
,以获取网络上每个人的 IP,然后尝试依次通过 SSH 连接到它们中的每一个。问题是,我不知道如何在不手动输入 IP 的情况下将 IP 从 arp -a
发送到 SSH 命令(不会工作,因为我正在编写可执行文件。)这甚至可能吗?
简短回答:您可以编写一个小脚本从 arp
中提取 IP 并处理每个。您可以使用bash
循环,或其他工具(xargs
)来处理多个IP。
Bash解决方案
#! /bin/bash
# Read arp line like: '_gateway (192.168.215.3) at 00:52:58:e7:cf:5f [ether] on ens33`
while read tag ip x ; do
# Strip leading and trailing characters from the IP
ip=${ip:1:-1}
# Execute ssh
ssh ... "$ip"
done <<< "$(arp -a)"
更新 bash 4.2 之前的版本:
基于@cyrus 的评论输入。
在 bash 4.2 中添加了在子字符串上使用负长度。对于较旧的旧版本,使用以下而不是 ip=${ip:1:-1}
来删除前导 '(' 和尾随 ')'
ip=${ip#(} ; ip=${ip%)}
我正在编写一个 shell 脚本,我希望能够 运行 一些命令,例如 arp -a
,以获取网络上每个人的 IP,然后尝试依次通过 SSH 连接到它们中的每一个。问题是,我不知道如何在不手动输入 IP 的情况下将 IP 从 arp -a
发送到 SSH 命令(不会工作,因为我正在编写可执行文件。)这甚至可能吗?
简短回答:您可以编写一个小脚本从 arp
中提取 IP 并处理每个。您可以使用bash
循环,或其他工具(xargs
)来处理多个IP。
Bash解决方案
#! /bin/bash
# Read arp line like: '_gateway (192.168.215.3) at 00:52:58:e7:cf:5f [ether] on ens33`
while read tag ip x ; do
# Strip leading and trailing characters from the IP
ip=${ip:1:-1}
# Execute ssh
ssh ... "$ip"
done <<< "$(arp -a)"
更新 bash 4.2 之前的版本:
基于@cyrus 的评论输入。
在 bash 4.2 中添加了在子字符串上使用负长度。对于较旧的旧版本,使用以下而不是 ip=${ip:1:-1}
来删除前导 '(' 和尾随 ')'
ip=${ip#(} ; ip=${ip%)}