使用 expect 自动登录

今天在玩Linux,在root与普通用户之间切换,老是要输入密码,然后突然有个想法,自己写个shell脚本执行自动切换此不是更方便,瞎搞了一下不行,然后google上搜一下,原来纯shell做不了这个事,要用expect,以下安装步骤:

1:下载需要用到的包,因为安装expect要用到tcl,tcl下载地址:http://www.tcl.tk/software/tcltk/downloadnow84.tml,expect下载地址:http://download.chinaunix.net/download/0003000/2845.shtml,下载完用 tar -zxf解压。

2:安装tcl:进入tcl目录(cd tcl),你会看到有一个unix目录与一个win目录,把unix里的文件拷贝到generic目录(要不然之后编译expect就会出错,出错原因可以查看 tclPort.h文件,里面有个 include "tclUnixPort.h",不拷贝的话会找不到这个文件),执行:
cd generic
cp ../unix/* .
然后开始配置与编译了,
./configure --prefix=/usr/local/tcl --enable-shared
make && make install

3:搞定tcl之后,开始搞expect了,进入expect目录,执行:
./configure --prefix=/usr/local/expect --with-tcl=/usr/local/tcl/lib --with-tclinclude=/root/upload/expect/generic (注:这个是刚才解压tcl源码的目录)
make && make install

4:因为要写脚步,创建一个/usr/local/expect/bin/expect的软链接到/usr/bin/expect更方便点, ln /usr/local/expect/bin/expect /usr/bin/expect

5:都配置好了,开始写脚步啦^-^,切换到普通用户,su dylan ,vi root.sh
代码如下:
#!/usr/bin/expect
spawn su root #执行切换root用户命令
expect "Password" #匹配要输入密码的提示符
send "yourPassword\r" #发送root用户的密码
interact #结束

posted @ 2015-06-04 22:34  菜B  阅读(448)  评论(0编辑  收藏  举报