[linux服务器]使用expect自动登录

lovelily 2010-11-18

使用expect自动登录

一,什么是expect?

在做系统管理时,我们很多时候需要输入密码,例如:连接ssh,连接ftp,

那么如何能做到不输入密码吗?

我们需要有一个工具,能代替我们实现与终端的交互,

那么,就是它:expect,管理员的最好的朋友之一

它能够代替我们实现与终端的交互,我们不必再守候在电脑旁边输入密码,

或是根据系统的输出再运行相应的命令,

这些都可以由expect代替我们来完成

说明:expect到底是什么?

expect是一种脚本语言,使用起来非常简单,我们看后面的例子即可以了解到了

三,安装expect

备注:因为expect是基于tcl的,所以需要你的系统中安装有tcl

如何检查?

[root@dev~]#whereistcl

tcl:/usr/lib/tcl8.4/usr/share/tcl8.4

如果看不到结果,请先安装tcl

安装,

[root@dev~]#yuminstallexpect

也可以从http://rpm.pbone.net下载for相应发行版的rpm包

四,使用expect自动登录的例子

1,程序例子的内容:

先做功能上的说明

此程序ssh登录到作为参数传递过来的ip地址上

然后执行:df-h

free-m

uptime

来检查系统的情况

[root@dev~]#catmonitor_auto

#!/usr/bin/expect-f

#--------------------------------------------------aboutus

#product:monitorone

#Author:liuhongdi<hongdi.liu@chinafotopress.com>

#LastModified:2008-05-13

#version:0.3.2

#user:thisscriptwillhelpyoutomonitormanylinux(unix)machine

#license:thisscriptisbasedGPL

#--------------------------------------------------setthevariable,youcanmodifythevalue

setloginuser"root"

setloginpass{passwordonthishost}

setipaddr[lrange$argv00]

settimeout300

setcmd_prompt"]#|~]?"

#--------------------------------------------------loginbyssh

spawnssh$loginuser@$ipaddr

settimeout300

expect{

-re"Areyousureyouwanttocontinueconnecting(yes/no)?"{

send"yes\r"

}-re"assword:"{

send"$loginpass\r"

}-re"Permissiondenied,pleasetryagain."{

exit

}-re"Connectionrefused"{

exit

}timeout{

exit

}eof{

exit

}

}

expect{

-re"assword:"{

send"$loginpass\r"

}

-re$cmd_prompt{

send"\r"

}

}

#----------------------------------------------------now,wedosomecommands

execsleep1

expect{

-re$cmd_prompt{

send"df-h\r"

}

}

execsleep1

expect{

-re$cmd_prompt{

send"free-m\r"

}

}

execsleep1

expect{

-re$cmd_prompt{

send"uptime\r"

}

}

execsleep1

#--------------------------------------------------

expect{

-re$cmd_prompt{

send"exit\r"

}

}

exit

#interact

2,程序运行的显示结果

[root@dev~]#./monitor_auto209.209.94.107

spawnsshroot@209.209.94.107

root@209.209.94.107'spassword:

Lastlogin:SunFeb1501:42:392009from201.103.105.49

[root@ws~]#

[root@ws~]#df-h

FilesystemÈÝÒÑÓÿÉÓÃÒÑÓÃ%¹ÒÔصã

/dev/mapper/VolGroup00-LogVol00

133G72G55G57%/

/dev/sda199M13M82M14%/boot

none1014M01014M0%/dev/shm

209.209.94.109:/www/pics

5.9T5.6T138G98%/bank/bank1

[root@ws~]#free-m

totalusedfreesharedbufferscached

Mem:20261955710721621

-/+buffers/cache:2611764

Swap:1983681915

[root@ws~]#uptime

01:48:00up561days,8:53,2users,loadaverage:0.13,0.09,0.07

[root@ws~]#[root@dev~]#

四,对此程序的详细说明:

1,setloginuser"root"

set用来定义变量,定义之后的代码中可以使用所定义的变量

使用时注意需添加$符号

使用时的例子:spawnssh$loginuser@$ipaddr

相关推荐