expect腳本同步文件
自動同步文件
#!/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
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
構建文件分發系統
需求背景
對於大公司而言,肯定時不時會有網站或者配置文件更新,而且使用的機器肯定也是好多臺,少則幾臺,多則幾十甚至上百臺。所以,自動同步文件是至關重要的。
實現思路首先要有一臺模板機器,把要分發的文件準備好,然後只要使用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:/
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof
ip.list內容,爲需要同步的遠程機器IP
192.168.133.132
192.168.133.133
list.txt內容,爲同步的文件路徑
/tmp/12.txt
/root/1.sh
/root/111/222/lll.txt
rsync.sh 內容
#!/bin/bash
for ip in `cat /tmp/ip.list` #要輸入文檔的絕對路徑
do
echo $ip
./rsync.expect $ip /tmp/list.txt
done
批量遠程執行命令
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 /tmp/ip.list`
do
echo $ip
./exe.expect $ip ;w;free -m;ls /tmp
done
擴展:
shell多線程 http://blog.lishiming.net/?p=448