簡(jiǎn)單模式:
#!/usr/bin/expect -f set timeout 5 spawn ssh root@192.168.0.1expect "*assWord*" send "root/r" expect "#" send "ifconfig /r" expect eof
講解:
send:用于向進(jìn)程發(fā)送字符串expect:從進(jìn)程接收字符串 比如:expect "*assword*"
spawn:?jiǎn)?dòng)新的進(jìn)程interact:允許用戶交互怎么使用變量:#!/usr/bin/expect -fset port 22set user rootset host 192.168.0.12set password rootset timeout -1spawn 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表示繼續(xù)。通過(guò)讀取配置文件獲取變量:配置文件192.168.0.1 root192.168.0.2 root
自動(dòng)化登錄腳本
#!/usr/bin/expect -fset f [open ./ip r] while { [gets $f line ]>=0 } { set ip [lindex $line 0] set pwd [lindex $line 1]spawn ssh $ipexpect "*password:" { send "$pwd/r" }expect "#"send "ifconfig /r"send "exit/r"interact}講解:
可以多臺(tái)服務(wù)器循環(huán)執(zhí)行,是個(gè)非常使用的方式!
自動(dòng)化遠(yuǎn)程拷貝文件:
#!/usr/bin/expect -fset port 22set user rootset host 192.168.28.30set password rootset timeout -1spawn scp $host:/home/cfg ./expect {"*yes/no" { send "yes/r"; exp_continue}"*assword:" { send "$password/r" }}expect eof講解:
原理和ssh一樣
遠(yuǎn)程執(zhí)行命令后寫(xiě)入文件,再通過(guò)scp到本機(jī)服務(wù)器:
#!/usr/bin/expect -fset port 22set user rootset host 192.168.28.30set password rootset timeout -1spawn 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"interactspawn scp $host:/home/cfg ./expect {"*yes/no" { send "yes/r"; exp_continue}"*assword:" { send "$password/r" }}expect eof講解:
自動(dòng)化運(yùn)維,遠(yuǎn)程交互從服務(wù)器A上ssh到服務(wù)器B上,然后執(zhí)行服務(wù)器B上的命令。http://www.CUOXin.com/javame/p/4272440.html
新聞熱點(diǎn)
疑難解答
圖片精選