在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安装包在我的资源中有,大家如有需要也可以下载,语言的思想基本都差不多,只是脚本语言的写法都比较严谨,所以在编写过程中需要大伙细心。
#! /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安装包在我的资源中有,大家如有需要也可以下载,语言的思想基本都差不多,只是脚本语言的写法都比较严谨,所以在编写过程中需要大伙细心。
相关文章推荐
- [置顶] Linux下用expect实现ssh自动登录并执行脚本
- 详解如何在 Linux 启动时自动执行命令或脚本
- linux expect远程自动登录以及执行命令
- linux 普通用户登录后,执行 shell脚本切自动输入密码切换到root
- 详解在 Linux 启动时,如何自动执行命令或脚本
- 在 Linux 命令行脚本中执行 sudo 等命令时自动输入密码(使用expect)
- 如何在 Linux 启动时自动执行命令或脚本
- 通过expect自动登录到30台linux机器运行相同命令
- linux expect远程自动登录以及执行命令
- 详解如何在 Linux 启动时自动执行命令或脚本
- Linux下通过EXPECT脚本自动执行ssh远程连接
- 详解在 Linux 启动时,如何自动执行命令或脚本
- Linux下通过EXPECT脚本自动执行ssh远程连接
- 在android中如何编译连接 .c 的可执行文件 Android点滴(1) -- 执行Linux命令并且获得输出的结果
- 在linux 如何写一个自动用ssh登录重启Apache的脚本
- 简易登录,批量执行命令,批量copy文件shell脚本【Linux运维之道之脚本案例】
- linux自动登录脚本expect
- java通过代码登录远程linux服务器并执行linux命令
- centos shell编程4【分发系统】 服务器标准化 mkpasswd 生成密码的工具 expect讲解 expect传递参数 expect自动同步文件 expect指定host和要同步的文件 expect文件分发系统 expect自动发送密钥脚本 Linux脚本执行方式 第三十八节课
- linux学习第七十篇:expect脚本同步文件,expect脚本指定host和要同步的文件,构建文件分发系统,批量远程执行命令