C language programming from the password file to obtain data function summary

  • 2020-04-02 03:19:26
  • OfStack

C getpw() function: gets the password file data for the specified user
The header file:


#include <pwd.h>  #include <sys/types.h>

Definition function:


int getpw(uid_t uid, char *buf);

Getpw () looks for user account data from /etc/passwd that matches the uid specified by the parameter uid, and returns -1 if it cannot find the relevant data.

The format of the returned buf string is as follows:
Id: password: uid: group id: full name: root :shell

Return value: returns 0 for success and -1 for error.

Additional instructions
1. Getpw () has potential security issues, please try to use other functions instead.
2. The system using shadow has pulled out the user password /etc/passwd, so the password obtained using getpw() will be "x".

sample


#include <pwd.h>
#include <sys/types.h>
main()
{
  char buffer[80];
  getpw(0, buffer);
  printf("%sn", buffer);
}

Perform:


root:x:0:0:root:/root:/bin/bash


C getpwnam() function: gets the data of the specified account from the password file
The header file:


#include <pwd.h>  #include <sys/types.h>

Definition function:


struct passwd * getpwnam(const char * name);

Getpwnam () is used to search the account name specified by parameter name one by one, and when found, the data of this user is returned in passwd structure. Refer to getpwent() for the passwd structure.

Return value: returns the passwd structure data. If NULL is returned, there is no data or an error has occurred.

sample



#include <pwd.h>
#include <sys/types.h>
main()
{
  struct passwd *user;
  user = getpwnam("root");
  printf("name:%sn", user->pw_name);
  printf("uid:%dn", user->pw_uid);
  printf("home:%sn", user->pw_dir);
}

Perform:


name:root
uid:0
home:/root

C getpwuid() function: gets the data for the specified uid from the password file
The header file:


#include <pwd.h>  #include <sys/types.h>

Definition function:


struct passwd * getpwuid(uid_t uid);

Getpwuid () is used to search the user identification number specified by the parameter uid one by one, and when found, it will return the data of the user in a structure.

Return value: returns the passwd structure data. If NULL is returned, there is no data or an error has occurred.

sample


#include <pwd.h>
#include <sys/types.h>
main()
{
  struct passwd *user;
  user= getpwuid(6);
  printf("name:%sn", user->pw_name);
  printf("uid:%dn", user->pw_uid);
  printf("home:%sn", user->pw_dir);
}

Perform:


name:shutdown
uid:6
home:/sbin


Related articles: