20.31 expect腳本同步文件
自動同步文件
#!/usr/bin/expect
set passwd "123456"
spawn rsync -av root@192.168.192.135:/tmp/12.txt /tmp/
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
expect eof
}
//expect eof 不加這句 還沒來得及傳輸就退出了
20.32 expect腳本指定host和要同步的文件
指定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
}
./5.expect 192.168.192.135 "/tmp/99.txt" //只能寫絕對路徑
20.33 構建文件分發系統
需求背景
對於大公司而言,確定時不時會有網站或者配置文件更新,並且使用的機器確定也是好多臺,少則幾臺,多則幾十甚至上百臺。因此,自動同步文件是相當重要的。
實現思路
首先要有一臺模板機器,把要分發的文件準備好,而後只要使用expect腳本批量把須要同步的文件分發到目標機器便可。
核心命令
rsync -avR --files-from=list.txt / root@host:/
// R 若是目標目錄不存在, 能夠建立目標主機的級聯路徑
文件分發系統的實現
cd /usr/local/sbin
rsync.expect 內容
chmod a+x rsync.expect
#!/usr/bin/expect
set passwd "123456"
set host [lindex $argv 0]
set file [lindex $argv 1]
spawn rsync -avP --files-from=$file / root@$host:/
expect {
"yes/no" { send "yes\r";exp_continue}
"password:" { send "$passwd\r" }
}
expect eof
vim /tmp/list.txt 內容
/tmp/12.txt
/root/shell/01.sh
/root/shell/03.sh
....
vim /tmp/ip.txt 內容
192.168.192.135
192.168.192.136
......
vim rsync.sh 內容
chmod a+x rsync.sh
for ip in `cat /tmp/ip.txt`
do
echo $ip
./rsync.expect $ip /tmp/list.txt
done
測試
20.34 批量遠程執行命令
exe.expect 內容
chmod a+x 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";exp_continue}
"password:" { send "$passwd\r" }
}
expect "]*"
send "$cm\r"
expect "]*"
send "exit\r"
exe.sh 內容
#!/bin/bash
for ip in `cat /tmp/ip.txt`
do
echo $ip
./exe.expect $ip "w;free -m;ls /tmp"
done
測試
sh -x exe.sh