linux - 如何使用 C 或 shell 在 Linux 中检查密码?

标签 linux embedded-linux

我有一个在嵌入式 Linux 上运行的用 C 编写的程序,有时它想检查系统用户的密码。

  1. 如果我能得到/etc/passwd的crypt salt,我就可以使用crypt()来检查用户密码是否正确。
  2. 有没有shell脚本可以帮我查密码?比如check_passwd 用户名密码,那么它返回的值是正确的还是不正确的? 谢谢!

最佳答案

我最近一直在解决同样的任务。下面是 C 函数的示例(与 -lcrypt 链接)。请注意,您需要对文件/etc/passwd 和/etc/shadow 具有读取权限。

#include <sys/types.h>
#include <pwd.h>
#include <shadow.h>
#include <crypt.h>
#include <string.h>
#include <stdio.h>

/// @return 0 - password is correct, otherwise no
int CheckPassword( const char* user, const char* password )
{
    struct passwd* passwdEntry = getpwnam( user );
    if ( !passwdEntry )
    {
        printf( "User '%s' doesn't exist\n", user );
        return 1;
    }

    if ( 0 != strcmp( passwdEntry->pw_passwd, "x" ) )
    {
        return strcmp( passwdEntry->pw_passwd, crypt( password, passwdEntry->pw_passwd ) );
    }
    else
    {
        // password is in shadow file
        struct spwd* shadowEntry = getspnam( user );
        if ( !shadowEntry )
        {
            printf( "Failed to read shadow entry for user '%s'\n", user );
            return 1;
        }

        return strcmp( shadowEntry->sp_pwdp, crypt( password, shadowEntry->sp_pwdp ) );
    }
}

关于linux - 如何使用 C 或 shell 在 Linux 中检查密码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17499163/

相关文章:

python - 在 Raspbian 上自动启动程序 - Raspberry Pi 3

c - 使用ftok()创建 key 以及如何使用 key ?

c - 使用 gstreramer 播放歌曲的顺序是什么?

c - 如何使用 C 中的原始套接字发送接收到的数据包?

linux - 验证 bash 中的一些参数

linux - JMeter-服务器在开始测试后卡住

linux - "-sh: executable_path:not found"是什么意思

linux - 使用 bash shell 脚本挂载图像和编辑配置文件(在文件系统内)

c - 如何确保UDP套接字关闭?

linux - 保持 OE/Yocto 图像更新的过程