check unix username and password in a shellscript

2019-03-29 21:48发布

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?

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

标签: unix shell
4条回答
干净又极端
2楼-- · 2019-03-29 21:56

the username and passwords are written in the /etc/shadow file. just get the user and the password hash from there (sed would help), hash your own password and check.

use mkpasswd to generate the hash. you hve to look which salt your version is using. the newest shadow is using sha-512 so :

mkpasswd -m sha-512 password salt

manpages can help you there a lot.

Easier would be to use php and the pam-aut module. there you can check vie php on group access pwd user.

查看更多
欢心
3楼-- · 2019-03-29 22:04

Partial answere would be to check user name, is it defined in the passwd/shadow file in /etc then calculate the passwords MD5 with salt. If you have your user password sended over SSL (or at least some server terminal service).

Its just a hint because I dont know what do You need actually. Because "su" is mainly for authentication purposes.

Other topics which You might look at are kerberos/LDAP services, but those are hard topics.

查看更多
闹够了就滚
4楼-- · 2019-03-29 22:06

On Linux, you will need to write a small C program which calls pam_authenticate(). If the call returns PAM_SUCCESS, then the login and password are correct.

查看更多
Melony?
5楼-- · 2019-03-29 22:08

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
查看更多
登录 后发表回答