在shellscript中检查unix用户名和密码

问题描述:

如果本地 unix 用户传递的用户名和密码正确,我想检查一个 shell 脚本.最简单的方法是什么?

I want to check in a shell script if a local unix-user's passed username and password are correct. What is the easiest way to do this?

我在谷歌搜索时唯一发现的是使用expect"和su",然后以某种方式检查su"是否成功.

Only thing that I found while googling was using 'expect' and 'su' and then checking somehow if the 'su' was successful or not.

好的,现在这是我用来解决问题的脚本.我首先尝试编写一个由 Aaron Digulla 提出的小型 c 程序,但事实证明这太难了.

Ok, now this is the script that I used to solve my problem. I first tried to write a small c-programm as susgested by Aaron Digulla, but that proved much too difficult.

也许这个脚本对其他人有用.

Perhaps this Script is useful to someone else.

#!/bin/bash
#
# login.sh $USERNAME $PASSWORD

#this script doesn't work if it is run as root, since then we don't have to specify a pw for 'su'
if [ $(id -u) -eq 0 ]; then
        echo "This script can't be run as root." 1>&2
        exit 1
fi

if [ ! $# -eq 2 ]; then
        echo "Wrong Number of Arguments (expected 2, got $#)" 1>&2
        exit 1
fi

USERNAME=$1
PASSWORD=$2

# Setting the language to English for the expected "Password:" string, see http://askubuntu.com/a/264709/18014
export LC_ALL=C

#since we use expect inside a bash-script, we have to escape tcl-$.
expect << EOF
spawn su $USERNAME -c "exit" 
expect "Password:"
send "$PASSWORD\r"
#expect eof

set wait_result  [wait]

# check if it is an OS error or a return code from our command
#   index 2 should be -1 for OS erro, 0 for command return code
if {[lindex \$wait_result 2] == 0} {
        exit [lindex \$wait_result 3]
} 
else {
        exit 1 
}
EOF