从文件中读取用户名和密码

时间:2012-09-13 06:05:49

标签: linux bash scripting fedora

我正在寻找一个读取文件的用户名和密码并输入这些文件以添加用户或删除用户的信息。

EG:我有一个名为'userlist'的文件,其中包含以下格式的内容:

user1 pass1
user2 pass2
user3 pass3

我完全不明白的是如何使用BASH脚本添加这些帐户。

到目前为止我所拥有的是:

if [[ whoami -ne "root" ]]
then
exit
else
echo "wish to add or delete? a/d"
read uArg
echo "enter file name"
read uFile
if [ $uArg = "a" -o $uArg = "A" ]
then
    IDK WHAT TO DO HERE.
elif [ $uArg = "d" -o $uArg = "D" ]
then
   IDK WHAT TO DO HERE.
fi
fi

好吧,我不明白的是如何逐行阅读每个单词并输入用户名和密码来添加新用户或删除现有用户。

该程序用于读取整个文件并为每个用户添加相应的密码。如果选择删除,则会删除文件中的每个用户。

我是BASH的新手,所以任何帮助都会受到赞赏。

3 个答案:

答案 0 :(得分:3)

awk完全符合您的需求。

见这个例子:

$ awk '{print "Hi! my name is " $1 ", and my pass is " $2}' ./userpass.txt 
Hi! my name is user1, and my pass is pass1
Hi! my name is user2, and my pass is pass2
Hi! my name is user3, and my pass is pass3

Awk以1美元存储用户名,以2美元(第一列和第二列)存储密码。

您可以使用管道执行从awk获得的字符串作为命令:

$ awk '{print "echo " $1}' ./userpass.txt | /bin/bash
user1
user2
user3

答案 1 :(得分:0)

某些事情......

if [[ whoami -ne "root" ]]
    then
    exit
else
    echo "wish to add or delete? a/d"
    read uArg
    echo "enter file name"
    read uFile
    if [ $uArg = "a" -o $uArg = "A" ]
    then
        while read user passwd rest
        do
            if [ ! -z $rest ]; then
                echo "Bad data"
            else
                useradd -m $user
                passwd $user <<EOP
$passwd
$passwd
EOP
            fi
        done < $uFile
    elif [ $uArg = "d" -o $uArg = "D" ]
    then
        while read user passwd rest
        do
            if [ ! -z $rest ]; then
                echo "Bad data"
            else
                userdel $user
            fi
        done < $uFile
    fi
fi

答案 2 :(得分:0)

第一条评论:

  • 学习并习惯基本命令,如grep,sed,echo,以及一般的文件操作,如果你想知道bash基础知识,awk也是一个不错的选择,你会遇到很多关于文件操作的内容。
  • 代码可以使用更多的错误测试,它只是一个基本的骨架
  • 小心字符串和变量,尽可能引用它们,字符串中的空格可以做很多坏事

可能是这些方面的事情:

echo "wish to add or delete? a/d"
read uArg
echo "enter username"
read uName
grep "^$uName " password-file
RET=$?

if [ "$uArg" == "a" -o "$uArg" == "A" ]
then
    [ $RET -eq 0 ] && echo "User is already in file"

    if [ $RET -ne 0 ]
    then
        echo "enter password"
        read uPass
        echo "$uName $uPass" >> password-file
    fi

elif [ "$uArg" == "d" -o "$uArg" == "D" ]
then
    [ $RET -ne 0 ] && echo "User is not file"

    if [ $RET -eq 0 ]
    then
        sed -i "/^$uName /d" password-file
        echo "User deleted"

    fi
fi