Linux - expect自動化遠程登錄腳本


簡單模式:

#!/usr/bin/expect -f   
set timeout 5   
spawn ssh root@192.168.0.1
expect "*assword*"   
send "root\r"   
expect "#"   
send "ifconfig \r"   
expect eof

講解:

send:用於向進程發送字符串
expect:從進程接收字符串 比如:expect "*assword*"
spawn:啟動新的進程 interact:允許用戶交互

怎么使用變量:
#!/usr/bin/expect -f
set port 22
set user root
set host 192.168.0.12
set password root
set timeout -1
spawn ssh -D $port $user@$host "ifconfig"
expect {  
"*yes/no" { send "yes\r"; exp_continue}  
"*assword:" { send "$password\r" }  
}  
expect "*#*"  
send "ifconfig > /home/cfg \r"
send "exit\r"
}

講解:

expect {  
"*yes/no" { send "yes\r"; exp_continue} "*assword:" { send "$password\r" } } 
選擇模式,exp_continue表示繼續。

通過讀取配置文件獲取變量:
配置文件
192.168.0.1 root
192.168.0.2 root

   自動化登錄腳本

#!/usr/bin/expect -f
set f [open ./ip r]  
while { [gets $f line ]>=0 } {       
set ip [lindex $line 0]     
set pwd [lindex $line 1]
spawn ssh $ip
expect  "*password:" { send "$pwd\r" }
expect "#"
send "ifconfig \r"
send "exit\r"
interact
}

講解:

可以多台服務器循環執行,是個非常使用的方式!

自動化遠程拷貝文件:

#!/usr/bin/expect -f
set port 22
set user root
set host 192.168.28.30
set password root
set timeout -1
spawn scp $host:/home/cfg ./
expect {
"*yes/no" { send "yes\r"; exp_continue}
"*assword:" { send "$password\r" }
}
expect eof

講解:

原理和ssh一樣

遠程執行命令后寫入文件,再通過scp到本機服務器:

#!/usr/bin/expect -f

set port 22
set user root
set host 192.168.28.30
set password root
set timeout -1
spawn ssh -D $port $user@$host "ifconfig"
expect {
"*yes/no" { send "yes\r"; exp_continue}
"*assword:" { send "$password\r" }
}
expect "*#*"
send "ifconfig > /home/cfg \r"
send "exit\r"
interact
spawn scp $host:/home/cfg ./
expect {
"*yes/no" { send "yes\r"; exp_continue}
"*assword:" { send "$password\r" }
}
expect eof

講解:

自動化運維,遠程交互從服務器A上ssh到服務器B上,然后執行服務器B上的命令。

http://www.cnblogs.com/Javame/p/4272440.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM