Shell實戰訓練營Day11

expect 分發系統

實現遠程自動登錄

#!/usr/bin/expect
set host "192.168.200.128" #定義變量
set passwd "123456"
spawn ssh root@$host
expect{
"yes/no" {send"yes\r";exp_continue} #\r表示回車
"password:" {send "$passwd\r"}
}
interact #登錄後停留在遠程主機界面

遠程登錄後執行指定命令並退出
#!/usr/bin/expect
set user "root"
set passwd "123456"
spawn ssh [email protected]
expect {
"yes/no" {send "yes\r"}
"password:" {send "$passwd\r"}
}
expect "]" #匹配root用戶或者普通用的提示符
send "touch /tmp/exp.txt" #執行的命令
expect "]
"
send "echo test > /tmp/exp.txt\r" #執行的命令
expect "]*"
send "exit\r" #退出遠程主機

expect腳本參數傳遞

#!/usr/bin/expect
set user [lindex $argv 0] #代表第1個參數 用戶
set host [lindex $argv 1] #代表第2個參數 主機地址
set passwd "123456"
set cm [lindex $argv 2] #代表第3個參數 執行的命令
spawn ssh $user@$host
expect{
"yes/no" {send "yes\r"}
"password:" {send $"passwd\r"}
}
expect "]"
send "$cm\r"
expect "]
"
send "exit\r"
執行格式 bash shellname root 192.168.100.100 "ls-l;w"

expect 腳本自動同步文件
#!/usr/bin/expect
set passwd "123456"
spawn rsync -av [email protected]:/tmp/test.txt /tmp/ #從遠程主機192.168.100.100 同步文件至本機/tmp/
expect{
"yes/no" {send "yes\r"}
"password:" {send "$passwd\r"}
}
expect eof # 不立即退出帶同步結束後退出

指定host與需要同步的文件
#!/usr/bin/expect
set passwd "123456"
set host [lindex $avgr 0]
set file [lindex $avgr 1]
spawn rsync -avR $file root@$host:$file
expect {
"yes/no" {send "yes\r"}
"password" {send"$passwd\r" }
}
expect eof

構建文件分發系統
核心命令 rsync -avR --files-from=filelist / /root@host:/ #文件列表分發
#!/usr/bin/expect
set passwd "123456"
set host [lindex $avgr 0]
set file [lindex $avgr 1]
spawn rsync -avR --files-from=$file / root@host:/
expect{
"yes/no" {send "yes\r"}
"password" {send "$passwd\r"}
}
expect eof

文件系統分發結合的文件與腳本
自定義 iplist
192.168.200.130
192.168.200.131
192.168.200.132
自定義 filelist
/tmp/123
/awk/132
/shell/123
定義同步腳本 rsync.sh
#!/bin/bash
for ip in cat /usr/local/sbin/ip.list
do
echo $ip
./exp6.exp $ip /usr/local/sbin/file.list #exp6.exp 爲shell
done

遠程批量執行命令 注:下面的列子中批量執行需要各個主機密碼相同
#!/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"

#!/bin/bash
for ip in cat /usr/local/sbin/ip.list
do
echo $ip
./exp7.exp $ip "w;free -m;ls"
done

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章