歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> 關於Linux >> linux下的expect的簡單用法及舉例

linux下的expect的簡單用法及舉例

日期:2017/3/1 17:15:47   编辑:關於Linux

linux下的expect的簡單用法及舉例 1、使用expect前,需要先安裝兩個rpm包,下載:http://download.csdn.net/detail/wang7dao/4416172 # rpm -ihv expect-5.43.0-8.el5.i386.rpm # rpm -ihv expect-devel-5.43.0-8.el5.i386.rpm 2、使用腳本文件的例子--實現自動輸密碼 #!/usr/bin/expect -f set password 123456 #download spawn scp [email protected]:/root/a.wmv /home/yangyz/ set timeout 300 expect "[email protected]'s password:" set timeout 300 send "$password\r" set timeout 300 send "exit\r" expect eof www.2cto.com 3、在sh腳本中嵌入expect的例子--通過連上一個公網的服務器再轉跳到一個內網的服務器上,用腳本實現不用輸密碼,直接使用./goto.sh servername #!/bin/bash passmsmallq10="a" passzhsh="a" passfcwr="b" passwapfx="c" passadfx="d" ip1="200.100.10.10" ip2="10.100.100.70" ip3="10.100.100.60" ip4="10.100.100.10" ip5="10.100.100.20" case $1 in "zhsh") passstr=$passzhsh ipstr=$ip2 ;; "fcwr") passstr=$passfcwr ipstr=$ip3 ;; "wapfx") passstr=$passwapfx ipstr=$ip4 ;; "adfx") passstr=$passadfx ipstr=$ip5 ;; *) echo "The parameter $1 isn't exist" exit 0 ;; www.2cto.com esac command1="ssh -l m_smallq -p 36000 $ip1" command2="ssh -l mqq -p 36000 $ipstr" expect -c " set timeout 60; spawn $command1; expect { \"221.130.15.10's password:\" {send \"$passmsmallq10\r\"; exp_continue} \"m_smallq\" {send \"$command2\r\"; exp_continue} \"mqq's password:\" {send \"$passstr\r\";interact} } " 對上面例子的expect的解說 expect -c "..." --裡面輸入命令 expect {...} --裡面的多行記錄,從上向下掃描匹配,誰先匹配誰先處理。 www.2cto.com 4、ssh到另一台機子執行df -h後退出,要點是send後面可以跟多個命令,通過\r來分行成多個命令 #!/bin/bash ip1="183.62.178.191" command1="ssh -l root -p 14322 $ip1" expect -c " spawn $command1; expect { \"183.62.178.191's password:\" {send \"aa\r\"; exp_continue} \"root@\" {send \"df -h\r exit\r\"; exp_continue} } " 作者 wang7dao
Copyright © Linux教程網 All Rights Reserved