如何在Linux中使用C或Shell检查密码? [英] How to check password in Linux by using C or shell?

查看:157
本文介绍了如何在Linux中使用C或Shell检查密码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a program written in C running on a embedded Linux, sometimes it want to check the password of a system user.


  1. 如果我可以得到 / etc / passwd 的地穴盐,则可以使用crypt()进行检查

  2. 是否有任何shell脚本可以帮助我检查密码?如check_passwd用户名密码,那么它返回的值是正确还是不正确?
    谢谢!

  1. If I can get the crypt salt of /etc/passwd, I can use crypt() to check the correction of user password.
  2. Is there any script of shell can help me check the password? Such as check_passwd username password, then it return a value for correct or incorrect? Thanks!


推荐答案

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

I had been solving the same task recently. Here is an example of C function (link with -lcrypt). Note that you need to have read permissions for files /etc/passwd and /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检查密码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆