使用Bash(shell)脚本批量传输文件到Linux服务器并远程执行传输的文件

在日常运维工作中,我们经常需要批量管理多台服务器,包括文件传输和命令执行。本文将介绍如何使用Bash脚本实现这一目标。

脚本说明

以下是一个Bash脚本示例,它会从ip.txt文件中读取IP地址列表,将本地文件传输到远程服务器,并在远程服务器上执行安装命令。

脚本内容

#!/bin/bash

# 读取ip.txt文件中的IP地址
hosts=()
while IFS= read -r line; do
    hosts+=("$line")
done < ip.txt

username="your_username"
password="your_password"
local_file="/path/to/local_file"
remote_file="/path/to/remote_file"
installation_command="chmod +x $remote_file && $remote_file"
ssh_port=22

for host in "${hosts[@]}"
do
    echo "Transferring file to $host on port $ssh_port..."
    sshpass -p "$password" scp -P $ssh_port -o StrictHostKeyChecking=no "$local_file" "$username@$host:$remote_file"
    
    echo "Logging in to $host on port $ssh_port and executing installation command..."
    sshpass -p "$password" ssh -p $ssh_port -o StrictHostKeyChecking=no "$username@$host" "$installation_command"
done

脚本解释

  1. 读取IP地址

    • 使用while IFS= read -r line; do ... done < ip.txt循环读取ip.txt文件中的每一行,并将其添加到hosts数组中。
  2. 变量定义

    • hosts:包含多个主机IP地址的数组,从ip.txt文件中读取。
    • username:用于登录远程主机的用户名。
    • password:用于登录远程主机的密码。
    • local_file:本地文件的路径。
    • remote_file:远程主机上文件的路径。
    • installation_command:在远程主机上执行的安装命令。
    • ssh_port:SSH连接使用的端口号,默认设置为22。
  3. 循环遍历每个主机

    • 对于每个主机,使用sshpassscp命令将本地文件传输到远程主机。
    • 然后使用sshpassssh命令登录到远程主机,并执行安装命令。

注意事项

  • 安全性:在实际使用中,建议使用SSH密钥认证而不是明文密码,以提高安全性。
  • 文件路径:请确保local_fileremote_file路径正确,并且具有相应的权限。
  • IP地址文件ip.txt文件应包含每行一个IP地址。

运行脚本

将上述脚本保存为deploy.sh,并确保其具有可执行权限:

chmod +x deploy.sh

然后运行脚本:

./deploy.sh

结论

通过这个简单的Bash脚本,我们可以轻松地批量传输文件并在远程服务器上执行该文件。这在大规模运维管理中非常实用。希望本文对大家有所帮助!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

longerxin2020

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值