文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>修改linux密码

修改linux密码

时间:2006-12-24  来源:slnsnow

/************************
gcc -o test_shadow test_shadow.c -lcrypt
test_shadow username old_passwd new_passwd
/usr/bin/test_shadow
************************/
#include <stdio.h>
#include <stdlib.h>
#include <shadow.h>
#include <time.h>
#include <string.h>
#include <sys/types.h>
#include <pwd.h>
#include <unistd.h>
#define L_PASSWD 100
#define N_PASSWD 160
char *get_salt(); char line[L_PASSWD][N_PASSWD]; int main(int argc,char *argv[])
{
    struct passwd *pw;
    char str[N_PASSWD];
    char *crypt_code;
    char *salt;
    struct spwd *sp;
    char salt_cmp[13];
    if(argc != 4)
    {
        fprintf(stderr,"Usage:%s sys_user old_passwd new_passwd\n",argv[0]);
        exit(1);
    }
   
    sp = getspnam(argv[1]);
    strncpy(salt_cmp,sp->sp_pwdp,12);
    salt_cmp[12] = '\0';
    if(strcmp(sp->sp_pwdp,(char*)crypt(argv[2],salt_cmp)))
    {
        fprintf(stderr,"You input a wrong old_passwd for user %s.\n",argv[1]);
        fprintf(stderr,"Retry or discard.\n");
        exit(254);
    }
    salt = get_salt();     pw = getpwnam(argv[1]);     crypt_code = (char *)crypt(argv[3],salt);
   
    if((strlen(pw->pw_name)+strlen(crypt_code)+strlen(pw->pw_gecos)+
strlen(pw->pw_dir)+strlen(pw->pw_shell)+8) < N_PASSWD)
    {
        sprintf(str,"%s:%s:%u:%u:%s:%s:%s",pw->pw_name,crypt_code,\
pw->pw_uid,pw->pw_gid,pw->pw_gecos,pw->pw_dir,pw->pw_shell);
        }
        else
        {
                fprintf(stderr,"Too short buffer!\n");
                exit(255);
        }
    char *fpath = "/etc/passwd";
    FILE *fp;
    int i = 0;
    char tmp[N_PASSWD];
    if((fp=fopen(fpath,"r")) == NULL)
    {
        perror("fopen error:\n");
        exit(2);
    }
   
    while(fgets(tmp,N_PASSWD-1,fp))
    {
        if(strncmp(tmp,pw->pw_name,strlen(pw->pw_name)))
        {
            strcpy(line[i],tmp);
        }
        else
        {
            strcpy(line[i],str);
        }
        i++;
    }
    fclose(fp);
    int j = 0;
       
    if((fp=fopen(fpath,"w")) == NULL)
        {
                perror("fopen error:\n");
                exit(2);
        }
    while(j<i)
    {
        fputs(line[j],fp);
        j++;
    }
    fclose(fp);
    free(salt);
    return 0;
}
char *get_salt()
{
    int i = 0;
    int n = 0;
    char *alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    char *salt;
    salt = (char *)malloc(13*sizeof(char));
    salt[0] = '$';
    salt[1] = '1';
    salt[2] = '$';   
    srand(time(NULL));   
    while(i<8)
    {
        n = rand()%52;
        salt[i+3] = alpha[n];
        i++;
    }
   
    salt[11] = '$';
    salt[12] = '\0';
    return salt;
}
相关阅读 更多 +
排行榜 更多 +
蓝星战士

蓝星战士

飞行射击 下载
书桌看吧

书桌看吧

浏览阅读 下载
铠甲勇士之英雄传说

铠甲勇士之英雄传说

冒险解谜 下载