简体   繁体   English

如何将用户给定的输入(字符串)与Ubuntu中的/ etc / passwd文件进行比较

[英]how to compare user given input(string) to /etc/passwd file in ubuntu in c

I want to compare user given input ie a username to the already stored usernames in /etc/passwd file in ubuntu. 我想将用户给定的输入(即用户名)与ubuntu中的/ etc / passwd文件中已存储的用户名进行比较。 I am trying it in C. any help please 我正在C中尝试

#include <pwd.h>
...

struct passwd *e = getpwnam(userName);
if(e == NULL) {
   //user not found
} else {
  //found the user
}

See docs here and here 在此处此处查看文档

(If you actually want to authenticate the user as well, there's more work needed though ) (如果您实际上也想对用户进行身份验证,那么还需要做更多的工作)

This code prints all the usernames from /etc/passwd. 此代码从/ etc / passwd打印所有用户名。

#include <stdio.h>

int main()
{  
        char buffer[128];
        char* username;
        FILE* passwdFile;

        passwdFile = fopen("/etc/passwd", "r");
        while (fgets(buffer, 128, passwdFile) != NULL)
        {
                username = strtok(buffer, ":");
                printf("username: %s\n", username);
        }
        fclose(passwdFile);
        return 0;
}

Modify to compare username to your input. 进行修改以将username与您的输入进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM