expect腳本同步文件、expect腳本指定host和同步的文件、構建文件分發系統、批量遠程執行命
阿新 • • 發佈:2018-09-25
shadow ces 使用 term shu 自動創建 ofo 內容 oot
expect腳本當中去把一臺機器的文件同步到另外一臺機器上去,自動同步文件
[root@100xuni1 sbin]# vim 4.expect ##編輯腳本
寫入一下內容:
#!/usr/bin/expect
set passwd "hanshuo"
spawn rsync -av [email protected]:/tmp/12.txt /tmp/
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof
加個執行權限
[root@100xuni1 sbin]# chmod a+x 4.expect
測試這個腳本
[root@100xuni1 sbin]# ./4.expect
expect腳本指定host和要同步的文件
指定host和要同步的文件
[root@100xuni1 sbin]# vim 5.expect ##編輯腳本 寫入一下內容: #!/usr/bin/expect set passwd "hanshuo" 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
加個執行權限
[root@100xuni1 sbin]# chmod a+x 5.expect
測試這個腳本
[root@100xuni1 sbin]# ./5.expect 192.168.63.101 "/tmp/12.txt" ##把本地的12.txt同步到了遠程
構建文件分發系統
掌握了expect的基礎知識,用所學的東西構建個文件分發系統,以上是同步一個文件,我的需求同步一堆,這些文件需要寫到一個文件列表裏邊去,我們使用rsync的files-from這個參數就能夠實現把列表裏邊的文件給同步到遠程去,那麽在列表的路徑必須要絕對路徑
文件分發系統的實現
首先定義rsync.expect
[root@100xuni1 sbin]# vim rsync.expect ##編輯rsync.expect
寫入一下內容:
#!/usr/bin/expect
set passwd "hanshuo"
set host [lindex $argv 0]
set file [lindex $argv 1]
spawn rsync -avR --files-from=$file / root@$host:/ ##大寫R是如果同步機器路徑不相同自動創建
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect eof
定義file.list,這個file你可以寫到tmp下名字叫file.list
[root@100xuni1 sbin]# vim /tmp/file.list ##編輯文件列表file.list,這個文件裏邊是你要同步到另一臺的文件
寫入一下內容:
/tmp/12.txt
/root/shell/1.sh
/root/111.txt
定義ip.list
[root@100xuni1 sbin]# vim /tmp/ip.list ##編輯一個ip.list裏邊寫入你要同步文件的ip
寫入以下內容:
192.168.63.101
192.168.63.104
創建rsync.sh編輯它
[root@100xuni1 sbin]# vim rsync.sh ##編輯rsync.sh
寫入以下內容:
#!/bin/bash
for ip in `cat /tmp/ip.list`
do
./rsync.expect $ip /tmp/file.list
done
給rsync.expect執行權限
[root@100xuni1 sbin]# chmod a+x rsync.expect
執行rsync.expect
[root@100xuni1 sbin]# sh -x rsync.sh
批量遠程執行命令
構建命令批量執行
編輯exe.expect
[root@100xuni1 sbin]# vim exe.expect
寫入下列內容:
#!/usr/bin/expect
set host [lindex $argv 0]
set passwd "hanshuo"
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.expect執行權限
[root@100xuni1 sbin]# chmod a+x exe.expect
定義一個exe.sh的shell腳本
[root@100xuni1 sbin]# vim exe.sh
寫入下列內容:
#!/bin/bash
for ip in `cat /tmp/ip.list`
do
./exe.expect $ip "hostname"
done
執行exe.sh
[root@100xuni1 sbin]# sh exe.sh
擴展
shell多線程 http://blog.lishiming.net/?p=448
expect腳本同步文件、expect腳本指定host和同步的文件、構建文件分發系統、批量遠程執行命