【问题标题】:Is it possible to SSH to all network clients from a Bash exec?是否可以从 Bash exec SSH 到所有网络客户端?
【发布时间】:2019-11-16 05:37:51
【问题描述】:

我正在编写一个 shell 脚本,我希望能够运行一些命令,例如 arp -a,以获取网络上每个人的 IP,然后依次尝试通过 SSH 连接到每个人。问题是,我不知道如何在不手动输入 IP 的情况下将 IP 从arp -a 发送到 SSH 命令(不起作用,因为我正在编写一个可执行文件。)这甚至可能吗?

【问题讨论】:

    标签: bash ssh ip arp


    【解决方案1】:

    简短回答:您可以编写一个小脚本从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)"
    

    在 4.2 之前更新 bash 版本:

    基于@cyrus 的评论输入。

    在 bash 4.2 中添加了对子字符串使用负长度。对于较旧的旧版本,请使用以下内容而不是 ip=${ip:1:-1} 删除前导 '(' 和尾随 ')'

     ip=${ip#(} ; ip=${ip%)}
    

    【讨论】:

    • 我认为这会起作用,除非 bash 在到达 ip=${ip:1:-1} 时抛出错误,特别是关于 -1。有什么想法吗?
    • 你能发布错误吗?我正在使用 bash 4.0 没有问题。你能发布你使用的 bash 版本吗(bash --version
    • 我使用的版本是3.2.57 (MacOS)
    • ${var:start:-len} 是在 4.2 版中添加的。
    猜你喜欢
    • 1970-01-01
    • 2020-01-24
    • 2015-09-29
    • 1970-01-01
    • 2014-05-14
    • 2012-06-07
    • 2010-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多