Simple mode:
#!/usr/bin/expect-FSetTimeout5spawn ssh [email protected]192.168.0.1expect"*assword*"Send"root\r"expect"#"Send"ifconfig \ r"expect EOF
Explain:
send:用于向进程发送字符串expect:从进程接收字符串 比如:expect "*assword*"
spawn:启动新的进程interact:允许用户交互
How to use variables:
#!/usr/bin/expect-FSetPort ASetUser RootSetHost192.168.0.12SetPassword RootSetTimeout-1Spawn ssh-D $port [email protected] $host"ifconfig"Expect {"*yes/no"{Send"yes\r"; Exp_continue}"*assword:"{Send"$password \ r"}} expect"*#*"Send"ifconfig >/home/cfg \ r"Send"exit\r"}
Explain:
Expect { "*yes/no" {send "yes\r"; exp_continue} "*assword:" {send "$password \ r " } }
Select mode, exp_continue means continue.
To get a variable by reading a configuration file:
Configuration file
192.168. 0.1 Root 192.168. 0.2 Root
Automated logon scripts
#!/usr/bin/expect-FSetf [Open./IP R] while{[Gets $f line]>=0 } { SetIP [lindex $line0] SetPWD [Lindex $line1]spawn ssh $ipexpect"*password:"{Send"$pwd \ r"}expect"#"Send"ifconfig \ r"Send"exit\r"Interact}
Explain:
Can be more than one server loop execution, is a very use of the way!
Automating Remote Copy files:
#!/usr/bin/expect-FSetPort ASetUser RootSetHost192.168.28.30SetPassword RootSetTimeout-1Spawn SCP $host:/home/cfg./Expect {"*yes/no"{Send"yes\r"; Exp_continue}"*assword:"{Send"$password \ r"}}expect EOF
Explain:
The same principle as SSH
Write the file after the command is executed remotely, and then through the SCP to the native server:
#!/usr/bin/expect-FSetPort ASetUser RootSetHost192.168.28.30SetPassword RootSetTimeout-1Spawn ssh-D $port [email protected] $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
Explain:
Automation operations, remote interaction from Server a SSH to Server B, and then execute the commands on Server B.
Http://www.cnblogs.com/Javame/p/4272440.html
Linux-expect Automated Telnet scripts