我有一个在嵌入式 Linux 上运行的用 C 编写的程序,有时它想检查系统用户的密码。
- 如果我能得到/etc/passwd的crypt salt,我就可以使用crypt()来检查用户密码是否正确。
- 有没有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/