使用文件中的主机地址生成 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

相关内容