本文演示通过expect工具实现su命令自动输入密码验证的方法。
Expect软件安装步骤,请参考:
http://blog.csdn.net/hanlizhong85/article/details/71038532
1、 su.sh脚本实现
脚本实现功能:用户切换,执行完成之后进入新用户界面。
############################################################
#!/bin/bash
USERNAME=$1
PASSWD=$2
expect -c "
set timeout 1000
spawn su - ${USERNAME}
expect "*assword:" { send "${PASSWD}\\r" }
interact
"
############################################################
执行结果:
-bash-4.1$ whoami
hanlzh
-bash-4.1$ ./su.sh root root --入参1为用户名,入参2为密码
spawn su - root
Password:
[root@HLZ ~]# whoami
root
2、 su_cmd.sh脚本实现
脚本实现功能:切换到其他用户并执行命令,执行完成之后回到原用户界面。
############################################################
#!/bin/bash
#Created by hanlizhong on 2013.08.26
#Notice: ${CMD} must be a system commond or a script has absolute path.
USERNAME=$1
if [ $(whoami) == root ]; then
CMD=$2
su - ${USERNAME} -c "${CMD}"
elif [ $(whoami) == ${USERNAME} ]; then
CMD=$2
sh -x ${CMD}
else
PASSWD=$2
CMD=$3
test -z "${CMD}" && (echo "Input error!" && exit 1)
expect -c "
spawn su - ${USERNAME} -c \"${CMD}\"
expect "*assword:" { send "${PASSWD}\\r" }
expect eof
"
fi
############################################################
执行结果:
-bash-4.1$ rm -rf /home/hanlzh/log.txt
rm: cannot remove `/home/hanlzh/log.txt': Permission denied
-bash-4.1$ ./su_cmd.sh root root "rm -rf /home/hanlzh/log.txt"
spawn su - root -c rm -rf /home/hanlzh/log.txt
Password:
-bash-4.1$