批量小程序expect的简单使用

物理环境:

suse 11 x86_64 sp2


~/test> rpm -qa | grep tcl

tcl-32bit-8.5.5-2.81

tcl-8.5.5-2.81


安装expect

~ # rpm -ivh ftp://192.168.1.206/release/suse/x86_64/expect-5.44.1.11-1.241.1.x86_64.rpm

Retrieving ftp://192.168.1.206/release/suse/x86_64/expect-5.44.1.11-1.241.1.x86_64.rpm

Preparing...                ########################################### [100%]

        package expect-5.44.1.11-1.241.1.x86_64 is already installed


~/test> ssh [email protected]

Password: 

Last login: Wed Dec 28 15:34:01 2016 from 192.168.1.214


~> du -sh

3.5G    .


编写脚本

~/test> vi ssh.sh 

#!/usr/bin/expect

ip="192.168.1.213"

pd=\0okm\(IJN\

expect <<EOF

set timeout 30

spawn ssh testuser@$ip "du -sh;"

expect {

"*yes/no" {send "yes\r";exp_continue}

"*Password:" {send "$pd\r"}

}

expect eof

EOF


说明:

ip和pd是设置的变量,分别是执行命令的远程机器的IP地址和需要输入的密码,密码因为有特殊字符所以加了三个转意字符,真实的密码是0okm(IJN


spawn这一行是ssh到192.168.1.213这台机器上,之后查看目录的占用空间大小


expect { }内容是判断上面输出的内容是否出现"yes/no"的字段,如果有则代替手动输入send字段"yes\r",接下来判断是否存在"Password"的字段,有的话就输入变量pd的内容


expect eof表示退出登录


执行结果:

~/test> sh ssh.sh 

spawn ssh [email protected] du -sh;

Password: 

3.5G    .


参考:

http://blog.csdn.net/zhuying_linux/article/details/6902135

猜你喜欢

转载自blog.csdn.net/duanbiren123/article/details/80190393