使用expect脚本登录到root账号并执行命令


通过expect脚本登录root账号,方法比较简单,只要先写一个如下格式的脚本即可:

#!/usr/bin/expect

set timeout=30                       #设置30秒超时

spwan su root

expect "Password*"

send    "123456\r"                   #发送密码,别忘了以\r结尾

expect "*#*"                           #等待#提示符的出现

send    "ls -l>/tmp/1\r"             #执行ls命令,并重定向到/tmp/1

expect "*#*"                           #等待#出现,说明上一个命令执行完毕了

send     "uname -a>/tmp/2\r"  #再执行下一条命令

#interact                                 #使用interact后,脚本将退出到root账号下,可以手动执行root权限的命令

expect  eof           

exit

相关内容