Shell 之批量執行命令


利用Expect來實現自動交互

注意:需提前安裝 expect

  • CentOS
# 安裝 expect
[root@ansible ~]# yum -y install expect
# 查看安裝包
[root@ansible ~]# rpm -qa expect
expect-5.45-14.el7_1.x86_64
  • Ubuntu
# apt-get install expect -y

run_cmd.exp 腳本解決ssh交互問題

#!/usr/bin/expect

if { $argc !=2 } {
    puts "Usages: expect $argv0 ip command"
    exit
}

# 接收腳本參數
set ip [lindex $argv 0]
set cmd [lindex $argv 1]

# 配置 SSH 密碼,每台服務器的SSH密碼必須一致
set password "test"


spawn ssh root@$ip $cmd

# 匹配交互內容
expect {
    "yes/no" {send "yes\r";exp_continue}
    "*password" {send "$password\r"}
}

expect eof

run_cmd.sh 利用 shell 循環執行 Expect 腳本命令

#!/bin/bash
#Author:mcsiberiawolf
#Time:2019-02-13 09:42:25
#Name:run_cmd.sh
#Version:V1.0
#Description: This is a test script.


if [ $# -ne 1 ]; then
    echo $"Usage: $0 cmd"
    exit 1
fi

cmd=$1

# 192.168.7.2和192.168.7.3 批量執行命令
for n in 2 3
do
    /usr/bin/expect /server/scripts/expect/run_cmd.exp 192.168.7.$n "$cmd"
done

批量查看及其負載

[root@ansible expect]# sh run_cmd.sh uptime
spawn ssh root@192.168.7.2 uptime
root@192.168.7.2's password: 
 10:01:31 up 13 days, 16:15,  1 user,  load average: 0.04, 0.17, 0.21
spawn ssh root@192.168.7.3 uptime
root@192.168.7.3's password: 
 10:01:49 up 13 days, 16:14,  0 users,  load average: 0.22, 0.28, 0.23

批量查看內存

[root@ansible expect]# sh run_cmd.sh "free -m"
spawn ssh root@192.168.7.2 free -m
root@192.168.7.2's password: 
              total        used        free      shared  buff/cache   available
Mem:         112517         992      111031          17         493      110893
Swap:         15259           0       15259
spawn ssh root@192.168.7.3 free -m
root@192.168.7.3's password: 
              total        used        free      shared  buff/cache   available
Mem:         128644        1057      127094          17         493      126954
Swap:         15259           0       15259

批量查看 /etc/passwd 文件

[root@ansible expect]# sh run_cmd.sh "ls -al /etc/passwd"
spawn ssh root@192.168.7.2 ls -al /etc/passwd
root@192.168.7.2's password: 
-rw-r--r--. 1 root root 874 Jan 30 17:12 /etc/passwd
spawn ssh root@192.168.7.3 ls -al /etc/passwd
root@192.168.7.3's password: 
-rw-r--r--. 1 root root 874 Jan 30 17:12 /etc/passwd

參考文章

跟老男孩學Linux運維 Shell編程實戰


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM