簡單模式:
#!/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
講解: