37 分發系統

expect分發
yum install -y expect
1.自動遠程登錄

#! /usr/bin/expect
set host "192.168.133.132"  //定義變量host
set passwd "123456"
spawn ssh root@$host  //spawn後面跟系統shell命令,遠程登錄
expect {
"yes/no" { send "yes\r"; exp_continue}  //初次登錄機器會提示yes/no,再次登錄不會是因爲/root/.ssh/known_hosts有記錄。表示有yes/no時,做括號中動作,exp_continue表示繼續
"password:" { send "$passwd\r" }
}
interact  //保持登錄在機器上,若用expect eof,則停留一會兒退出

需要給文件執行權限

2.自動遠程登錄後,執行命令並退出

#!/usr/bin/expect
set user "root"
set passwd "123456"
spawn ssh [email protected]

expect {
"yes/no" { send "yes\r"; exp_continue}
"password:" { send "$passwd\r" }
}
expect "]\*"  //表示命令行前的部分,PS1的最後部分root用戶是]#,普通用戶是]$,因此需要通配
send "touch /tmp/12.txt\r"
expect "]\*"
send "echo 1212 > /tmp/12.txt\r"
expect "]\*"
send "exit\r"  //退出

3.傳遞參數

#!/usr/bin/expect

set user [lindex $argv 0]  //定義變量user值爲參數1
set host [lindex $argv 1]  //參數2
set passwd "123456"
set cm [lindex $argv 2]  //參數3,發送的多條命令用分號隔開,命令執行時間不能太長,expect會有超時時間,默認10s。也可以自行設置:set timeout [number] 單位s,設定-1表示不限時間
spawn ssh $user@$host

expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect "]\*"
send "$cm\r"
expect "]\*"
send "exit\r"

4.自動同步文件

#!/usr/bin/expect
set passwd "123456"
spawn rsync -av [email protected]:/tmp/12.txt /tmp/  //同步遠端文件到本機
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof  //不加這個會登錄後立即退出導致根本沒同步

5.指定host和要同步的文件

#!/usr/bin/expect
set passwd "123456"
set host [lindex $argv 0]
set file [lindex $argv 1]
spawn rsync -av $file root@$host:$file
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof

6.構建文件分發系統
需求背景:對於大公司而言,肯定時不時會有網站或者配置文件更新,而且使用的機器肯定也是好多臺,少則幾臺,多則幾十甚至上百臺。所以,自動同步文件是至關重要的。
實現思路:首先要有一臺模板機器,把要分發的文件準備好,然後只要使用expect腳本批量把需要同步的文件分發到目標機器即可。
核心命令:
rsync -av --files-from=list.txt  /  root@host:/

rsync.expect 內容

#!/usr/bin/expect
set passwd "123456"
set host [lindex $argv 0]
set file [lindex $argv 1]
spawn rsync -av --files-from=$file / root@$host:/  //list.txt裏有文件的絕對路徑列表
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof

 ip.list內容
192.168.133.132
192.168.133.133
......

rsync.sh 內容
#!/bin/bash
for ip in `cat ip.list`
do
    echo $ip
    ./rsync.expect $ip list.txt
done

7.命令批量執行
exe.expect 內容

#!/usr/bin/expect
set host [lindex $argv 0]
set passwd "123456"
set cm [lindex $argv 1]
spawn ssh root@$host
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect "]\*"
send "$cm\r"
expect "]\*"
send "exit\r"

exe.sh 內容
#!/bin/bash
for ip in `cat ip.list`
do
    echo $ip
    ./exe.expect $ip "w;free -m;ls /tmp"
done
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章