批量ssh并执行命令

批量ssh登录并执行命令

维护集群时,常常需要在大量服务器上执行相同的命令,虽然可以自己写循环执行脚本,但是不仅麻烦而且执行效率不高。此时我们通常会使用pssh工具来并发执行SSH指令。

  • 控制机以centos7系统为例

  • 安装 pssh和 sshpass
    yum -y install pssh
    yum -y install sshpass

  • 批量获取机器名:
    sshpass -p 'password' pssh -O StrictHostKeyChecking=no -h ip.txt -l root -A -i "hostname"

  • 批量重启:
    sshpass -p 'password' pssh -O StrictHostKeyChecking=no -h ip.txt -l root -A -i "reboot"

password 是root密码
ip.txt 内容格式如下:

172.18.0.11
172.18.0.12:2222
172.18.0.13:3333

如果SSH默认22端口可以不用加端口。如果SSH端口不同,可在ip后面加上端口号。

成功返回 SUCCESS
失败返回 FAILURE

pssh 常用参数

-h	主机名列表文件
-l	登陆用户名,例如 -l root
-A	提供统一的登陆密码
-i	交互模式,远程服务器的命令执行结果会输出
-O ssh参数

Usage: pssh [OPTIONS] command [...]
Options:
  --version             show program's version number and exit
  --help                show this help message and exit
  -h HOST_FILE, --hosts=HOST_FILE
                        hosts file (each line "[user@]host[:port]")
  -H HOST_STRING, --host=HOST_STRING
                        additional host entries ("[user@]host[:port]")
  -l USER, --user=USER  username (OPTIONAL)
  -p PAR, --par=PAR     max number of parallel threads (OPTIONAL)
  -o OUTDIR, --outdir=OUTDIR
                        output directory for stdout files (OPTIONAL)
  -e ERRDIR, --errdir=ERRDIR
                        output directory for stderr files (OPTIONAL)
  -t TIMEOUT, --timeout=TIMEOUT
                        timeout (secs) (0 = no timeout) per host (OPTIONAL)
  -O OPTION, --option=OPTION
                        SSH option (OPTIONAL)
  -v, --verbose         turn on warning and diagnostic messages (OPTIONAL)
  -A, --askpass         Ask for a password (OPTIONAL)
  -x ARGS, --extra-args=ARGS
                        Extra command-line arguments, with processing for
                        spaces, quotes, and backslashes
  -X ARG, --extra-arg=ARG
                        Extra command-line argument
  -i, --inline          inline aggregated output and error for each server
  --inline-stdout       inline standard output for each server
  -I, --send-input      read from standard input and send as input to ssh
  -P, --print           print output as we get it

Example: pssh -h hosts.txt -l irb2 -o /tmp/foo uptime
  • sshpass 常用参数
-f 指定密码文件
-p 指定密码
sshpass: invalid option -- '-'
Usage: sshpass [-f|-d|-p|-e] [-hV] command parameters
   -f filename   Take password to use from file
   -d number     Use number as file descriptor for getting password
   -p password   Provide password as argument (security unwise)
   -e            Password is passed as env-var "SSHPASS"
   With no parameters - password will be taken from stdin

   -P prompt     Which string should sshpass search for to detect a password prompt
   -v            Be verbose about what you're doing
   -h            Show help (this screen)
   -V            Print version information
At most one of -f, -d, -p or -e should be used

posted @ 2021-08-26 15:22  jzking121  阅读(1091)  评论(0编辑  收藏  举报