Shell指令碼:人機互動指令碼-su
本文演示通過expect工具實現su命令自動輸入密碼驗證的方法。
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
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$