expect講解
expect可以讓我們實作自動登入遠端機器,并且可以實作自動遠端執行指令。當然若是使用不帶密碼的密鑰驗證同樣可以實作自動登入和自動遠端執行指令。但當不能使用密鑰驗證的時候,我們就沒有辦法了。是以,這時候隻要知道對方機器的賬号和密碼就可以通過expect腳本實作登入和遠端指令。
使用expect之前,需要先安裝expect:
a、安裝expect
yum install -y expect
一、自動登陸腳本
vim 1.expect
#! /usr/bin/expect
set host "10.10.13.247" #遠端登陸主機
set passwd "abc.123" #密碼
spawn ssh root@$host #遠端登陸
expect { #判斷出現yes/no
"yes/no" { send "yes\r"; exp_continue} #發送yes
"assword:" { send "$passwd\r" } #發送密碼
}
interact
2、添加可執行權限
chmod a+x 1.expect
3、執行
./1.expect
spawn ssh [email protected]
The authenticity of host '10.10.13.247 (10.10.13.247)' can't be established.
RSA key fingerprint is 8d:5a:2e:8c:ac:a0:02:c2:46:ba:db:ec:2e:eb:ce:68.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '10.10.13.247' (RSA) to the list of known hosts.
[email protected]'s password:
Last login: Fri Jun 17 21:05:57 2016 from win10.benco.com.cn
二、登陸後執行指令再退出腳本
#!/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 "]*" #]*表示判斷登陸後的字元是]*
send "touch /tmp/12.txt\r" #表示根據上上判斷輸入指令
expect "]*"
send "echo 1212 > /tmp/12.txt\r"
send "exit\r"
三、傳遞參數腳本
set user [lindex $argv 0] #定義第一個參數,即user
set host [lindex $argv 1] #定義第二個參數,即host
set passwd "abc.123"
set cm [lindex $argv 2] #定義第三個參數,第要執行的指令,如果指令是一行需要加""
spawn ssh $user@$host
"yes/no" { send "yes\r"}
send "$cm\r"
./3.expect root 10.10.13.247 w
四、同步檔案腳本
spawn rsync -av [email protected]:/tmp/12.txt /tmp/ #執行同步指令
expect eof #執行同步指令後結束
#将10.10.13.247上/tmp目錄下的12.txt同步到本地/tmp目錄
#如果本地和遠端機器上沒有rsync指令則會報錯
五、指定host和要同步的檔案
set host [lindex $argv 0]
set file [lindex $argv 1] #檔案本地路徑和遠端路徑必須一樣
spawn rsync -av $file root@$host:$file
expect eof
#如果要同步的遠端主機不止一台可以把ip和檔案清單寫下一個檔案,使用for循環:
for ip in `cat /tmp/ip.txt`; do ./5.expect $ip $file;done
六、檔案分發系統的實作(檔案清單同步)
a. 需求背景
對于大公司而言,肯定時不時會有網站或者配置檔案更新,而且使用的機器肯定也是好多台,少則幾台,多則幾十甚至上百台。是以,自動同步檔案是至關重要的。
b. 實作思路
首先要有一台模闆機器,把要分發的檔案準備好,然後隻要使用expect腳本批量把需要同步的檔案分發到目标機器即可。
c. 核心指令
rsync -av --files-from=list.txt / root@host:/1、建立同步腳本
1、建立expect腳本
vim rsync.expect
set file [lindex $argv 1]
spawn rsync -av --files-from=$file / root@$host:/
#必須保證每台機器的賬号密碼都一樣
2、建立循環腳本
vim rsync.sh
#!/bin/bash
for ip in `cat ip.list`
do
echo $ip
./rsync.expect $ip list.txt
done
3、建立ip清單和檔案清單
vim ip.list
10.10.13.247
vim list.txt
/tmp/12.txt
4、執行
chmod a+x rsync.sh rsync.expect
#修改下/tmp/12.txt添加内容後執行
sh rsync.sh
#發現10.10.13.247内容也修改,其實是直接把本機的/tmp/12.txt同步到13.247的/tmp目錄并覆寫了
#注意兩個腳本要有執行權限要在同一個目錄
七、指令同步執行
set cm [lindex $argv 1]
spawn ssh root@$host
2、指令執行腳本
./exe.expect $ip "w;free -m;ls /tmp"