自动切换 root 用户
安装expect:
apt-get install tcl tk expect # 仅安装 expect 即可
脚本内容和含义:
#! /usr/bin/expect # 表示使用expect的shell交互模式
set timeout 10
set password "whldpx20150928" # 对变量password赋值
spawn su root # spawn在expect下执行shell脚本
expect "Password:" # expect对通过spawn执行的shell脚本的返回进行判断,是否包""中的字段
send "$password\n" # 如果expect监测到了包含的字符串,将输入send中的内容,\n相当于回车
expect "#"
send "cd /root/sdb\r"
interact # 退出expect返回终端到root用户,否则将一直在expect不能退出到终端
set timeout 10:设置超时时间为10秒,如果要执行的shell命令很长可以设置超时时间长一些。expect超过超时时间没有监测到要找的字符串,则不执行,默认timeout为10秒
Q.E.D.