您的位置:首页 > 运维架构 > Linux

在linux下如何通过expect正确执行自动切换登录,并且执行命令和脚本

2011-10-11 23:17 941 查看
最近项目在搞可维护性这块功能,如:修改网卡IP、机器重启/关闭,数据库备份与恢复;这些功能点与linux中的shell脚本执行息息相关,但shell脚本却不支持自动化,目前我所知道的支持自动化的脚本也就expect、perl、python可支持自动化处理的脚本,虽然linux安装安后会自带perl命令库,但还是需要通过安装expect第三方动态语言。好了,废话不多说,直接上代码:

#! /usr/bin/expect

set command [lindex $argv 0]

set username [lindex $argv 1]

set passwd [lindex $argv 2]

spawn su - $username -c $command

expect "password:"

send $passwd\r

expect eof

exit

#! /usr/bin/expect 如果各位不知道这句是什么意思,可以通过执行witch epxect命令查询expect命令库地址,我这里就是/usr/bin/expect

脚本中首先定义了command、username、passwd三个参数,在调用时可通过./shell.sh reboot root root 来进行传参,切记不可用sh shell.sh的方式来执行脚本,因为expect脚本本身是不能用shell的形式来启动的,不然会报spawn、expect、send命令不到的错误。

如果是想切换用户后调用脚本,可以这样写:

#! /usr/bin/expect

set username [lindex $argv 0]

set passwd [lindex $argv 1]

spawn su - $username

expect "password:"

send $passwd\r

expext {

"su:密码错误" { send "echo 密码错误\r" }

"*#*" { send "sh test.sh\r" }

}

expect eof

exit

expect安装包在我的资源中有,大家如有需要也可以下载,语言的思想基本都差不多,只是脚本语言的写法都比较严谨,所以在编写过程中需要大伙细心。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐