shell逐行读取文件 & 远程操作服务器

代码示例

while read ip; 
    do
        echo "uninstalling test programs in $line"        
        ssh root@$ip 'bash -s' < remote_remove_tool.sh
    done < installed_ips

总结

✅ 作用:

  • 逐行读取 installed_ips 文件中的 IP 地址
  • 通过 SSH 连接到远程服务器,执行 remote_remove_tool.sh 脚本
  • 用于批量卸载多个服务器上的测试程序

✅ 优化建议:

  • 使用 & 并行执行,提高速度
  • 检查 installed_ips 是否存在,避免脚本报错
  • 增加 SSH 连接超时判断,防止连接卡住

1. 并行执行,提高效率

while read line; do
    echo "uninstalling test programs in $line"
    ssh root@$line 'bash -s' < remote_remove_tool.sh &
done < installed_ips
wait
  • & 让 ssh 命令在后台运行,多个 SSH 任务可以并行执行。
  • wait 让脚本等待所有后台任务完成。

2. 检查 installed_ips 是否存在,避免报错

if [ ! -f installed_ips ]; then
    echo "Error: installed_ips 文件不存在"
    exit 1
fi

3. 检查 SSH 连接是否成功

while read line; do
    echo "uninstalling test programs in $line"
    ssh -o ConnectTimeout=5 root@$line 'bash -s' < remote_remove_tool.sh || echo "Failed to connect: $line"
done < installed_ips
  • -o ConnectTimeout=5 限制 SSH 连接超时为 5 秒,避免卡死。
  • || echo “Failed to connect: $line” 如果 SSH 失败,则输出失败日志。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值