如何在Bash中通过用户输入控制循环次数并优化IP批量管理
实现方案
1. 先实现IP从配置文件读取
首先创建IP映射配置文件,比如命名为tart_ip_map.conf,和脚本放在同一目录下,格式如下(支持空行和#开头的注释):
# Tart序号与IP映射配置 1 10.171.0.10 2 10.171.0.11 3 10.171.0.12 4 10.171.0.13 5 10.171.0.14 6 10.171.0.15 7 10.171.0.16 8 10.171.0.17 9 10.171.0.18 10 10.171.0.19 11 10.171.0.20 12 10.171.0.21 13 10.171.0.100 14 10.171.0.101 15 10.171.0.102 16 10.171.0.103 17 10.171.0.104 18 10.171.0.105 19 10.171.0.106 20 10.171.0.107
2. 修改脚本逻辑支持两个需求
修改后的完整脚本如下:
#!/bin/bash ips=() tarts=() launch_tarts () { local tart=$1 local ip=${ip[tart]} echo " ---- Launching Tart $1 ---- " sshpass -p "tart123" ssh -Y -X -L 5900:$ip:5901 tarts@$ip <<EOF1 export DISPLAY=:1 gnome-terminal -e "bash -c \"pwd; cd /home/tarts; pwd; ./launch_tarts.sh exec bash\"" exit EOF1 } kill_tarts () { local tart=$1 local ip=${ip[tart]} echo " ---- Killing Tart $1 ---- " sshpass -p "tart123" ssh -tt -o StrictHostKeyChecking=no tarts@$ip <<EOF1 . ./tartsenvironfile.8.1.1.0 nohup yes | kill_tarts mcgdrv & nohup yes | kill_tarts server & pkill -f traf pkill -f terminal-server exit EOF1 } tarts_setup () { local tart=$1 local ip=${ip[tart]} echo " ---- Setting-Up Tart $1 ---- " sshpass -p "root12" ssh -tt -o StrictHostKeyChecking=no root@$ip <<EOF1 pwd nohup yes | /etc/rc.d/init.d/lifconfig su tarts nohup yes | vncserver sleep 10 exit exit EOF1 } # ---------- 新增部分:读取IP映射文件 ---------- MAP_FILE="./tart_ip_map.conf" if [ ! -f "$MAP_FILE" ]; then echo "错误:IP映射文件 $MAP_FILE 不存在,请检查路径" exit 1 fi declare -A ip while read -r tart_num ip_addr; do [[ -z "$tart_num" || "$tart_num" =~ ^#.* ]] && continue ip[$tart_num]="$ip_addr" done < "$MAP_FILE" # ---------- 新增部分结束 ---------- case $1 in kill) function=kill_tarts;; launch) function=launch_tarts;; setup) function=tarts_setup;; *) echo "错误:仅支持kill/launch/setup三个操作" && exit 1;; esac shift # ---------- 新增部分:支持单数字批量生成序号 ---------- if [ $# -eq 1 ] && [[ $1 =~ ^[1-9][0-9]*$ ]]; then max_tart=$1 tart_list=$(seq 1 $max_tart) else tart_list="$@" fi # ---------- 新增部分结束 ---------- for tart in $tart_list; do # 新增合法性判断,避免无效序号 if [ -z "${ip[$tart]}" ]; then echo "警告:序号 $tart 无对应IP配置,已跳过" continue fi ($function $tart) & ips+=(${ip[$tart]}) tarts+=(${tart[@]}) done wait
使用说明
- 操作前8个IP的命令简化为:
./testing.sh launch 8,和原来的./testing.sh launch 1 2 3 4 5 6 7 8效果完全一致 - 新增IP只需修改
tart_ip_map.conf,无需改动脚本本身,支持加注释标注IP用途,方便批量维护 - 脚本自动跳过无效序号,避免异常报错
内容的提问来源于stack exchange,提问作者Asad Javed
相关产品推荐
相关产品推荐

