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 失败,则输出失败日志。

你可能感兴趣的:(#,Shell编程,服务器,运维)