精华区 [关闭][返回]

当前位置:网易精华区>>讨论区精华>>电脑技术>>● Linux>>Linux之开发篇>>[转载]用C程序修改用户密码应该调用什么函数?

主题:[转载]用C程序修改用户密码应该调用什么函数?
发信人: kevintz(Geek)
整理人: arira(2001-06-05 12:34:36), 站内信件
★原文转载自CLanguage版kevintz的《Re:[转载]:用C程序修改用户密码应该调用什么函数?》★
【 在 zeus_h 的大作中提到:】
:★原文转载自Linux版zeus_h的《用C程序修改用户密码应该调用什么函数?》★
:man passwd找不到结果。
:还可以MAN什么?
:
:......

下面是linux下passwd程序的源代码,is it easy ?
编译时连接 -lpam -lpam_misc
---------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>

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

#include <security/pam_appl.h>
#include <security/pam_misc.h>

/* ------ some static data objects ------- */

static struct pam_conv conv = {
     misc_conv,
     NULL
};

/* ------- the application itself -------- */

int main(int argc, char *argv[])
{
     const char *user;
     int just_expired, retval;
     pam_handle_t *pamh=NULL;

     if (argc > 3) {
          fprintf(stderr, "usage: %s [-u] [username]\n"
                  "\tA program for changing the authentication tokens of\n"
                  "\ta user. Use -u to only change those tokens that have\n"
                  "\texpired\n"
                  , argv[0]);
          exit(1);
     }

     just_expired = 0;
     user = NULL;

     if (argc >= 2)
          if (!strcmp(argv[1],"-u")) {
               just_expired = PAM_CHANGE_EXPIRED_AUTHTOK;
               if (argc == 3)
                    user = argv[2];
          } else if (argc == 3) {
               fprintf(stderr,"usage: passwd [-u] [username]\n");
               exit(1);
          } else if (argc == 2)
               user = argv[1];

     if (user == NULL) {
          if ((user = getlogin()) == NULL) {
               fprintf(stderr, "passwd: cannot retrieve user's name\n");
               exit(1);
          }
     } else if (getuid() != 0) {
          fprintf(stderr, "passwd: only root can supply a user's name\n");
          exit(1);
     }

     /* here we know whose passwords are to be changed and whether
        we'll change everything or just the expired ones */

     retval = pam_start("passwd", user, &conv, &pamh);

     while (retval == PAM_SUCCESS) {      /* use loop to avoid goto... */

          /* the user is authenticated by the passwd module; change
             the password(s) too. */

          retval = pam_chauthtok(pamh, just_expired);
          if (retval != PAM_SUCCESS)
               break;

          /* all done */

          retval = pam_end(pamh, PAM_SUCCESS);
          if (retval != PAM_SUCCESS)
               break;

          /* quit gracefully */

          fprintf(stderr,
                  "passwd: %s authentication tokens updated successfully\n"
                  ,just_expired ? "expired":"all" );
          exit(0);
     }

     if (pamh != NULL)
          (void) pam_end(pamh,PAM_SUCCESS);

     if (retval != PAM_SUCCESS)
          fprintf(stderr, "passwd: %s\n", pam_strerror(pamh,retval));

     exit(1);
}


[关闭][返回]