如何从 bash

问题描述

我有一个包含任意数量主机名的文本文件。请注意,每个主机名未按以下编号编号。这只是一个经过消毒的版本,每个主机名都是唯一的。

hostname1
hostname2
hostname3
hostname4
hostname5
...

我的用例要求我遍历主机名的文本文件登录到这些框。目前,跳转盒的 ssh 连接限制为 6。我正在努力解决这个问题。我在这里有限,请耐心等待。

我目前的目标是:

  1. ssh 到前 6 台主机(主机名列表可以小于或大于 6 台主机)
  2. 然后在每个主机上运行 'ls -l'
  3. 关闭连接
  4. 重复直到文件结束。

我正在使用 tmux 来实现这一点,并为我为每个主机拆分窗格。

COUNTER="$(< "$1" wc -l)"                                         #This counts the number of hostnames in the file. I wrote this because i believe i need a counter somewhere to keep track of what iteration im in.


    while IFS= read -r ip || [[ -n "$ip" ]]; do                   #Read the hostname file
        tmux select-layout tiled;                                 #split the panes evenly ~roughly
        echo "$ip" | xclip -i -sel clipboard                      #copy the hostnames from the file to system clipboard
        tmux split-window -v; 
        tmux send-keys "ssh myjumpBox" ;                          #this is specific to my ssh config
        tmux send-keys "KPEnter" \ "$(xclip -o -sel clipboard)" ; #Press enter and paste IP to jumpBox
        tmux send-keys "KPEnter" ; 
        tmux send-keys "sudo su -" ;                              #become root on target host
        tmux send-keys "KPEnter" ; 
        tmux send-keys "$2" ;                                     #run [COMMAND]
        tmux send-keys "KPEnter";                                 #Press enter again
    done < "$1"
    sleep 60                                                      #Wait 60s until all the commands have fully executed
    tmux kill-pane -a -t 0                                             #Close all current ssh connections/panes besides pane 0 in order to establish new connetions for the rest of the host file
}

目前,上面的代码可以根据现有 tmux shell 中文件中的主机名数量来拆分窗格。问题是,一旦达到 6 个连接的限制。它将打开其余的窗格,但由于服务器 ssh 限制而出现“会话打开被对等方拒绝”的错误提示

#usage
./script [FILE] [COMMAND]
./script hostFile "ls -l"

我正在苦苦挣扎的是,继续主机名迭代,直到文件完成。希望用更清晰的术语

我认为是我的边缘情况(假设)

if the hostname file is less than 6 hosts,proceed as normal
if the hostname file is lets say 7. run the first 6,close the connection. iterate to the 7th hostname.
if the hostname file is 18,run the above code for the first 6 hosts,close,run the next 6. close. run the final 6. close.

我知道我在做的事情很笨拙。但是,我正在以最少的访问权限工作。如果有人可以在代码方面为我指出正确的方向,我将如何实现这种迭代逻辑,我将不胜感激。我相信我需要一个 continue 语句,只是不确定或调整我的 while-conditional。问题与 tmux 无关。因为我已经把它记下来了。我只是想我发布它以供参考。这更像是一个与迭代相关的问题。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)