批量分发文件、执行命令

18 阅读1分钟

在没有安装ansible等工具的情况下通过ssh免密登录在集群上批量执行命令。

前置依赖:配置从当前主机免密登录到其他主机

#!/bin/bash
command=$1
thisip=$(hostname -I | awk  '{print $1}')       # 获取当前节点的IP
for host_ip in 192.168.216.{128,129,130}
do
        if [ "$thisip" = "$host_ip" ]; then     # 在当前主机上直接执行命令,不用ssh
        echo "#########this host $host_ip##############"
        $command
        else
        echo "#########$host_ip##############"
        ssh ${host_ip} "$command"
        fi
done
 

在没有安装ansible等工具的情况下通过ssh免密 + scp(或rsync)分发文件到其他主机

前置依赖:配置从当前主机免密登录到其他主机


#!/bin/bash
# 判断参数个数
if [ $# -lt 1 ]
then
  echo Not Enough Arguement!
  exit;
fi
thisip=$(hostname -I | awk  '{print $1}')  # 获取当前节点的IP
# 遍历集群所有机器
for host in 192.168.216.{128,129,130}
do
  if [ "$thisip" = "$host" ]; then         # 不会从当前节点分发到当前节点
    echo "skip $host"
    continue
  fi
  echo ====================  $host  ====================               
  for file in $@                           # 可以发送多个文件
  do
    if [ -e $file ]
    then
      # 获取父目录
      pdir=$(cd -P $(dirname $file); pwd)
      # 获取当前文件的名称
      fname=$(basename $file)
      ssh $host "mkdir -p $pdir"
      # rsync -av $pdir/$fname $host:$pdir # FIXME 可能遇到rsync未安装或其他问题
      scp $pdir/$fname $host:$pdir         # 源和目的文件路径是一样的
    else
      echo $file does not exists!
    fi
  done
done