1. 程式人生 > >Shell實戰訓練營Day11

Shell實戰訓練營Day11

expect 分發系統

實現遠端自動登入

#!/usr/bin/expect
set host "192.168.200.128" #定義變數
set passwd "123456"
spawn ssh [email protected]$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

[email protected]$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 [email protected]$host:$file
expect {
"yes/no" {send "yes\r"}
"password" {send"$passwd\r" }
}
expect eof

構建檔案分發系統
核心命令 rsync -avR --files-from=filelist / /[email protected]:/ #檔案列表分發
#!/usr/bin/expect
set passwd "123456"
set host [lindex $avgr 0]
set file [lindex $avgr 1]
spawn rsync -avR --files-from=$file / [email protected]:/
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 [email protected]$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