使用檔案中的主機位址產生 shellscript 選單,並在每個選項下方顯示帶有「ping 狀態」的選項?

使用檔案中的主機位址產生 shellscript 選單,並在每個選項下方顯示帶有「ping 狀態」的選項?

問題:使用檔案中的主機位址產生 shellscript 選單,並在每個選項下方顯示帶有「ping 狀態」的選項?有什麼想法可以幫忙嗎?

檔案名稱:bssh.sh

#!/bin/bash
# Display Servers
echo "Servers List"
echo ""
SERVERS="servers_list.txt"
while IFS= read -r SERVERS_LINE || [[ -n "$SERVERS_LINE" ]]; do
    serveraddress=$(echo $SERVERS_LINE | cut -d"@" -f 2)
    servername=$(echo $SERVERS_LINE | cut -d"@" -f 1)
    if ping -c 1 -W 1 $serveraddress >/dev/null 2>&1; then
        echo -e "$servername [\033[0;32mOnline\033[0m]"
        echo ""
    else
        echo -e "$servername [\033[0;31mOffline\033[0m]"
        echo ""
    fi
done <"$SERVERS"
readarray -t Servers < servers_list.txt
PS3=$'\n'"Enter your choice or 0 to exit: "
select selection in "${Servers[@]}"; do
    if [[ $REPLY == "0" ]]; then
        echo -e "\033[0;90mPeace Out!\033[0m" >&2
        exit
    else
        # Modify the way the program is called
        if [[ -e /usr/bin/ssh ]]; then
            echo ""
            ssh "$selection"
            #echo ""
        else
            echo ""
            ssh "$selection"
            #echo ""
        fi
        break
    fi
done

檔案名稱:servers_list.txt

[email protected]  
[email protected]  
[email protected]
   

答案1

首先,您可以readarray透過讀取一次檔案來填入數組。無論哪種方式,一旦填充了數組,您就可以簡單地重複使用該數組並在使用它從每個條目中提取所需的位元時解析它:

$ cat se.sh
#!/bin/bash
readarray ssh_users < input
printf "SSH connections list:\n"
for connection in ${ssh_users[@]}; do
   printf "%s\n" "${connection}"
done
printf "Users list:\n"
for user in ${ssh_users[@]}; do
   printf "%s\n" "${user%%@*}"
done
printf "Servers list:\n"
for server in ${ssh_users[@]}; do
   printf "%s\n" "${server##*@}"
done
$ ./se.sh
SSH connections list:
[email protected]
[email protected]
[email protected]
Users list:
root
validusername
ufo
Servers list:
127.0.0.1
127.0.0.1

相關內容