【问题标题】:username and password checking from another file using shell script使用 shell 脚本从另一个文件检查用户名和密码
【发布时间】:2014-06-10 18:19:34
【问题描述】:

我是shell新手,我想做以下任务

一个接受用户名和密码并使用另一个文件中的一行检查 $username 和 $password 的 shell 程序(用于身份验证),我知道如何从用户那里获取用户名,但是我如何检查另一个文件中的一行.假设我有一个名为 username 的文件(其中包含用户名)和一个名为 password 的文件(其中包含密码)我如何在文件中使用该行检查 $username 和使用该行检查 $password

【问题讨论】:

  • 你能提供你的文件样本吗?
  • username.txt 文件只有一行“admin”,password.txt 文件只有一行“password” 现在如何将字符串 $username 与文件中名为 username.txt 的单词进行比较

标签: linux bash shell authentication


【解决方案1】:

这是一个示例脚本,它提示用户输入用户名和密码,然后将它们与从两个文件中获取的用户名和密码进行比较:

#!/bin/bash

# prompt the user to enter a username and password
read -p "Username: " inputUsername
read -s -p "Password: " inputPassword

# read the username and password from file
username=$(<username.txt)
password=$(<password.txt)

# compare
if [[ "$inputUsername" == "$username" && "$inputPassword" == "$password" ]]
then
    echo "valid username and password"
else
    echo "invalid username and password"
fi

【讨论】:

  • @dogbane username=$(&lt;username.txt) 是如何工作的?
  • @Jidder username=$(&lt;username.txt)username.txt 转储username 并将其保存在usename 变量中。
  • @Jidder 是命令替换。看这里它会清除你的疑惑wiki.bash-hackers.org/syntax/expansion/cmdsubst#specialities
  • 那么该命令只是将 username.txt 的全部内容转储到用户名中然后?
【解决方案2】:

直接来自 perl 食谱:(我想这不好,因为 OP 想要 bash)

#!/usr/bin/perl -w
# 

checkuser - demonstrates reading and checking a user's password

use Term::ReadKey;

print "Enter your password: ";
ReadMode 'noecho';
$password = ReadLine 0;
chomp $password;
ReadMode 'normal';

print "\n";

($username, $encrypted) = ( getpwuid $< )[0,1];

if (crypt($password, $encrypted) ne $encrypted) {
    die "You are not $username\n";
} else {
    print "Welcome, $username\n";
}

【讨论】:

    【解决方案3】:

    超级基本并且没有安全性,但这应该可以在文件中找到它们

    我认为应该怎么做(单个文件)

    echo 'Type username'
    read username
    echo 'Type Password'
    read -s Password
    awk /^$username.*$Password$/' {print "found"}' loginfile
    

    关于 OP 设置文件的方式

    echo 'Type username'
    read username
    echo 'Type Password'
    read -s Password
    UserCheck=$(awk /^$username$/' {print "1"}' Username.txt)
    PassCheck=$(awk /^$Password$/' {print "1"}' Password.txt)
    
    if [[ UserCheck -eq 1 && PassCheck -eq 1 ]]; then
         echo "Found"
    else
         echo "not found"
    fi
    

    【讨论】:

    • 您应该匹配awk 模式中行的开头和结尾。否则,如果用户输入“pass”并且文件有“password123”,它就会成功。
    • 这个问题对双方都有影响
    • 如果该行同时包含用户名和密码,它只会在第一个匹配?第二个必须找到它才能成功并说找到?我不明白你的意思?
    • @dogbane 刚刚意识到你的意思。现在修改
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-06
    • 1970-01-01
    • 2018-03-26
    • 2019-02-10
    • 2014-07-18
    • 2017-11-29
    • 2012-01-11
    相关资源
    最近更新 更多