现在的位置: 首页 > 综合 > 正文

用户登录及权限设置

2013年02月08日 ⁄ 综合 ⁄ 共 760字 ⁄ 字号 评论关闭

如何处理用户登录及权限设置?

struct passwd *pw; // used for /etc/passwd

struct spwd *spw; // used for /etc/shadow

char *username = "Pacific"; //用户名

char *input_passwd = "123456"; // 输入的密码

char *passwd;

char tmp[13];

 

if (getuid() != 0) { /* 只有root有权作此操作 */

printf("Login incorrect.\n");

return;

};

/* 取得/etc/passwd中间对应于本用户的数据结构 */

if ((pw = getpwnam(username)) == NULL) {

printf("Login incorrect.\n");

return;

};

/* 取得/etc/shadow中被隐藏的密码 */

spw = getspnam(username);

if (spw == NULL || (passwd = spw->sp_pwdp) == NULL) {

printf("Login incorrect.\n");

return;

};

 

/* 取得passwd的前12个字节作为种子 */

strncpy(tmp, passwd, 12);

/* 判断输入的密码加密后是否与原密码相同 */

if (strcmp(passwd, crypt(input_passwd, tmp)) != 0) {

/* 密码错误 */

printf("Login incorrect.\n");

return;

};

/* 密码正确,改变程序权限 */

setuid(pw->pw_uid);

 

/* 获得并进入用户根目录 */

if (pw->pw_dir) strncpy(path, pw->pw_dir, PATH_MAX);

else strcpy(path, "/");

chdir(path);

【上篇】
【下篇】

抱歉!评论已关闭.