expect自动登录SSH
2014.04.21 TsengYia@126.com http://tsengyia.blog.chinaunix.net
##########################################################
系统环境:
RHEL5.9[2.6.18-348.el5]
软件环境:
expect-5.43.0-8.el5
openssh-server-4.3p2-82.el5
openssh-clients-4.3p2-82.el5
##########################################################
1. 自动SSH登录,并停留在远程Shell环境
—— 实验脚本:
[root@localhost ~]# vim ex1.sh
#!/usr/bin/expect
spawn ssh mike@192.168.4.5
#expect "(yes/no)?" { send "yes\r" }
expect "password:" { send "123456\r" }
interact //允许进入交互模式
—— 运行结果:
[root@localhost ~]# ./ex1.sh
spawn ssh mike@192.168.4.5
mike@192.168.4.5's password:
Last login: Thu Apr 24 10:06:46 2014 from 192.168.4.5
[mike@svr5 ~]$
2. 自动SSH登录,执行一条命令后退出
—— 实验脚本:
[root@localhost ~]# vim ex2.sh
#!/usr/bin/expect
spawn ssh mike@192.168.4.5 "uname -r"
expect "password:" { send "123456\r" }
sleep 5
—— 运行结果:
[root@localhost ~]# ./ex2.sh
spawn ssh mike@192.168.4.5 uname -r
mike@192.168.4.5's password:
2.6.18-348.el5 //命令输出结果
[root@localhost ~]#
3. 自动SSH登录,执行多条命令后退出
—— 实验脚本:
[root@localhost ~]# vim ex3.sh
#!/usr/bin/expect
spawn ssh mike@192.168.4.5
expect "password:" { send "123456\r" }
expect "\[mike\@" { send "head -2 /etc/passwd > mike.txt\r" }
expect "\[mike\@" { send "ls -lh mike.txt\r" }
expect "\[mike\@" { send "sleep 5 ; exit\r" }
interact
—— 运行结果:
[root@localhost ~]# ./ex3.sh
spawn ssh mike@192.168.4.5
mike@192.168.4.5's password:
Last login: Thu Apr 24 10:41:47 2014 from 192.168.4.5
head -2 /etc/passwd > mike.txt
ls -lh mike.txt
sleep 5
exit
[mike@svr5 ~]$ head -2 /etc/passwd > mike.txt
[mike@svr5 ~]$ ls -lh mike.txt
-rw-rw-r-- 1 mike mike 65 04-24 10:42 mike.txt
[mike@svr5 ~]$ sleep 5
[mike@svr5 ~]$ exit
[root@localhost ~]#
###########################################################
阅读(2928) | 评论(0) | 转发(0) |