Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2266893
  • 博文数量: 168
  • 博客积分: 6641
  • 博客等级: 准将
  • 技术积分: 1996
  • 用 户 组: 普通用户
  • 注册时间: 2007-06-02 11:49
文章存档

2020年(4)

2019年(6)

2017年(1)

2016年(3)

2015年(3)

2014年(8)

2013年(2)

2012年(12)

2011年(19)

2010年(10)

2009年(3)

2008年(17)

2007年(80)

分类: LINUX

2014-04-24 11:22:34


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 ~]#

###########################################################

阅读(2879) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~