ssh连接:

cat ssh.exp
#!/usr/bin/expect -f
set HOST [lindex $argv 0]
set PASS "your-password"
spawn ssh $HOST
set timeout 10
expect {
"*(yes/no)*" { send "yes\r" }
"*password*" { send "${PASS}\r" }
}
expect "*$"
send "mkdir /tmp/test\r"
send "exit\r"
interact

使用: 

expect ssh.exp your-ip 或者 ./ssh.exp your-ip

作用:

登录 your-ip 后执行 mkdir /tmp/test 退出


2.scp  

cat scp.exp
#!/usr/bin/expect -f
set CMD0 [lindex $argv 0]
set CMD1 [lindex $argv 1]
set PASS "your-password"
spawn scp -r $CMD0 $CMD1
set timeout 10
expect {
"*(yes/no)*" { send "yes\r" }
"*password*" { send "${PASS}\r" }
}
interact

使用:

expect scp.exp root@your-ip:/tmp/test /tmp
expect scp.exp /tmp/test root@your-ip:/tmp/

附加:

使用scp.exp的时候,提示输入密码,无法自动读取密码,修改如下即可:

#!/usr/bin/expect -f
set CMD0 [lindex $argv 0]
set CMD1 [lindex $argv 1]
set PASS "your-password"
spawn scp -r $CMD0 $CMD1
set timeout 10
expect {
"*(yes/no)*" { send "yes\r" }
"*password*" { send "${PASS}\r" }
}
#interact
set timeout 3600
expect eof
exit

ssh.exp 修改端口

#!/usr/bin/expect -f
set HOST [lindex $argv 0]
set PORT [lindex $argv 1]
set PASS "your-password"
spawn ssh $HOST -p$PORT 
#spawn ssh -l$user -p$port $ip
set timeout 10
expect {
"*(yes/no)*" { send "yes\r" }
"*password*" { send "${PASS}\r" }
}
expect "*$"
send "cd /data/plat_bak/\r"
send "tar zxvf upload_bak.tgz\r"
send "exit\r"
interact