ssh连接:
cat ssh.exp#!/usr/bin/expect -fset HOST [lindex $argv 0]set PASS "your-password"spawn ssh $HOSTset timeout 10expect {"*(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 -fset CMD0 [lindex $argv 0]set CMD1 [lindex $argv 1]set PASS "your-password"spawn scp -r $CMD0 $CMD1set timeout 10expect {"*(yes/no)*" { send "yes\r" }"*password*" { send "${PASS}\r" }}interact
使用:
expect scp.exp root@your-ip:/tmp/test /tmpexpect scp.exp /tmp/test root@your-ip:/tmp/
附加:
使用scp.exp的时候,提示输入密码,无法自动读取密码,修改如下即可:
#!/usr/bin/expect -fset CMD0 [lindex $argv 0]set CMD1 [lindex $argv 1]set PASS "your-password"spawn scp -r $CMD0 $CMD1set timeout 10expect {"*(yes/no)*" { send "yes\r" }"*password*" { send "${PASS}\r" }}#interactset timeout 3600expect eofexit
ssh.exp 修改端口
#!/usr/bin/expect -fset HOST [lindex $argv 0]set PORT [lindex $argv 1]set PASS "your-password"spawn ssh $HOST -p$PORT #spawn ssh -l$user -p$port $ipset timeout 10expect {"*(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