- #!/usr/bin/expect
- set timeout 5
- set server [lindex $argv 0]
- set user [lindex $argv 1]
- set passwd [lindex $argv 2]
- spawn ssh -l $user $server
- expect {
- "(yes/no)" { send "yes\r"; exp_continue }
- "password:" { send "$passwd\r" }
- }
- expect "*Last login*" interact
- 演示
- [root@localhost ~]# expect test.sh 192.168.1.248 root 123
- spawn ssh -l root 192.168.1.248
- root@192.168.1.248's password:
- Last login: Sun Mar 11 12:11:46 2012 from 192.168.1.7
- [root@web-musicxx ~]#
- 如果要做自动登录
- 建立一个ip地址用户名passwd脚本
- [root@localhost ~]# cat file
- 192.168.1.248:root:123
- 建立一个sh脚本写一段循环
- [root@localhost ~]# cat 1.sh
- #!/bin/bash
- for i in `cat file`
- do
- host=`echo $i | awk -F':' '{print $1}'`
- user=`echo $i | awk -F':' '{print $2}'`
- passwd=`echo $i | awk -F':' '{print $3}'`
- expect test.sh $host $user $passwd
- done
- 演示
- [root@localhost ~]# bash 1.sh
- spawn ssh -l root 192.168.1.248
- root@192.168.1.248's password:
- Last login: Sun Mar 11 14:59:04 2012 from 192.168.1.7
- [root@web-musicxx ~]#
- 如果要在脚本中嵌套命令远程执行
- 如:
- #!/usr/bin/expect -f
- set timeout 5
- set server [lindex $argv 0]
- set user [lindex $argv 1]
- set passwd [lindex $argv 2]
- spawn ssh -l $user $server
- expect {
- "(yes/no)" { send "yes\r"; exp_continue }
- "password:" { send "$passwd\r" }
- }
- expect "*#"
- send "touch /testexpect \r"
- send "ls -l / \r"
- expect "*#"
- expect "*Last login*" interact