如何使用UNIX / LINUX在文件上保存密码?

时间:2011-03-07 15:09:24

标签: linux bash unix

我只知道如何阅读密码。但我遇到了如何设置用户输入的文件密码的问题。我只走了这么远。请帮忙:

if [ -d "$1" ]
then
    #reads password
    read -s -p "Enter Password: " password
    stty -echo
    stty echo
    echo ""
    echo ""
    #checks whether the password is valid or not
    echo $mypassword" == "$PASS" ] && echo "Password accepted" || echo "Access denied"
else
    echo "Directory not found."
fi

1 个答案:

答案 0 :(得分:1)

如果我没有弄错你,请尝试这样的事情:

#!/bin/bash

EXPECTED_PASS="FooBar"

if [ -d "$1" ]
then
    read -s -p "Enter Password: " password
    stty -echo
    stty echo
    echo ""
    echo ""

    #Save password to a temporary file
    echo "${password}" > /tmp/password.txt

    #Load password from file
    password=`cat /tmp/password.txt`

    if [ "${password}" == "${EXPECTED_PASS}" ]
    then
        echo "Access granted"
    else
        echo "Access denied"
    fi


else
    echo "Directory not found."
fi

通常将密码存储为纯文本不是一个好主意。最好加密它们或者至少对它们执行散列操作:

EXPECTED_PASS=`echo "FooBar" | md5sum | cut -f1 -d" "`
...
#Save password to a temporary file
echo "${password}"  | md5sum | cut -f1 -d" " > /tmp/password.txt

#Load password from file
password=`cat /tmp/password.txt`

希望它有所帮助。

问候。