37 分發系統

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

#! /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,則停留一下子退出

須要給文件執行權限bash

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

#!/usr/bin/expect
set user "root"
set passwd "123456"
spawn ssh $user@192.168.133.132

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.傳遞參數ide

#!/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 root@192.168.133.132:/tmp/12.txt /tmp/  //同步遠端文件到本機
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof  //不加這個會登陸後當即退出致使根本沒同步

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

#!/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 內容code

#!/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 內容ip

#!/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
相關文章
相關標籤/搜索