根据用户名区验证用户名密码是否正确
函数说明
The getpwnam() and getpwuid() functions return a pointer to a passwd structure, or NULL if the matching entry is not found or an error occurs. If an error occurs, errno is set appropriately. If one wantsto check errno after the call, it should be set to zero before call.
getpass() --get a password
,用于获取用户输入的密码,取消了输入的回显功能
struct passwd
*getpwnam(const char *name
);
struct passwd
*getpwuid(uid_t uid
);
passwd结构体
The passwd structure is defined in
<pwd
.h
> as follows
:
struct passwd
{
char *pw_name
;
char *pw_passwd
;
uid_t pw_uid
;
gid_t pw_gid
;
char *pw_gecos
;
char *pw_dir
;
char *pw_shell
;
};
验证用户密码代码
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<shadow.h>
#include<string.h>
#include<crypt.h>
#define _XOPEN_SOURCE
int main(int argc
, char *argv
[])
{
struct spwd
*shadowline
;
char *crypted_pass
;
char *input_pass
;
if(argc
<2)
{
fprintf(stderr,"Usage...\n");
exit(1);
}
input_pass
=getpass("PassWord:");
shadowline
=getspnam(argv
[1]);
crypted_pass
=crypt(input_pass
,shadowline
->sp_pwdp
);
if(strcmp(shadowline
->sp_pwdp
,crypted_pass
)==0)
puts("OK!");
else
puts("failer!");
exit(0);
}
## 根据ID显示用户名代码
```c
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<pwd.h>
int main(int argc,char *argv[])
{
struct passwd *pwdline;
if(argc<2)
{
fprintf(stderr,"Usage...\n");
exit(1);
}
pwdline=getpwuid(atoi(argv[1]));
puts(pwdline->pw_name);
exit(0);
}
调用示例