Что потребности файлов состоят в том, чтобы быть редактированием для добавления пользователя? и что быть запись?

Я пытаюсь записать программу C для добавления нового пользователя к моей Ubuntu 14.04.
Я отредактировал
1)/etc/passwd

sachin:x:65535:1:sachin:/home/sachin:/bin/bash

2)/etc/shadow

sachin:$6$VwBWgroA$t4KXLWIf81sWtiA1/a.fRLrXaOAflGtMo73hGvCzp/M6S8oizZ4iqk.vYbkblXZj2hgGXJxlJ.M2hghGO.a650:16294::::::

3). профиль

stty istrip
PATH=/bin:/usr/bin:/usr/local/bin:/usr/share/bin:.
export PATH

После этого, когда я работаю - ls -l /home/

drwxr-xr-x 43 mrcr mrcr 4096 Aug 12 10:27 mrcr
d-w------t  2 sachin    daemon    4096 Aug 12 11:11 sachin

Где "sachin" создается моим rpogram, "mrcr" обычно создается. Я изменил полномочия как обычный пользователь домой

drwxr-xr-x 2 sachin    daemon    4096 Aug 12 11:11 sachin

Я скопировал все файлы от "mrcr" корневого каталога до "sachin" корневого каталога (.bashrc, Рабочий стол.. и т.д.)

Теперь на экране входа в систему "sachin" там для входа в систему. но даже если я ввожу правильный пароль, я не могу войти в систему в него. Это загрузит снова тот же экран входа в систему. данный ниже мой весь код,

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

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

main(int argc, char **argv)
{

    struct passwd *userlist;
    int count, usernumber, len1;
    FILE *tmp, *stmp, *mailer, *profile;
    char *commentfield, *username, *userdir, *home;
    char *mailcomment, *mailmail, reply;

    commentfield = (char *)malloc(1024*sizeof(char));
    username = (char *)malloc(8*sizeof(char));
    userdir = (char *)malloc(256*sizeof(char));
    home = (char *)malloc(256*sizeof(char));
    mailcomment = (char *)malloc(1024*sizeof(char));
    mailmail = (char *)malloc(512*sizeof(char));

    if (argc!=4)
    {
        printf("usage : %s [dirname- no slashes] [logname] [comment - in quotes]\n", argv[0]);
        exit(1);
    }

    if( (strlen(argv[2]) < 5) || (strlen(argv[2]) > 8) )
    {
        printf("pls enter logname between 5-8 \n");
        exit(1);
    }

    signal(SIGHUP, SIG_IGN);
    signal(SIGINT, SIG_IGN);

    setpwent();

    count = 0;

    while((userlist = getpwent()) != NULL)
    {
        if(count < userlist->pw_uid)
        {
            count = userlist->pw_uid ; 
            usernumber = count + 1;
        }
    }
    printf("usernumber : %d\n", usernumber);

    endpwent();

    sprintf(commentfield,"%s", argv[3]);
    sprintf(username, "%s", argv[2]);
    sprintf(userdir, "%s", argv[1]);
    sprintf(home, "/%s/%s", argv[1], argv[2]);



    printf("\n Check this out here: \n");
    printf("-----------------------------------------------");
    printf("\n username      :\t %s", username);
    printf("\n Home Directory:\t %s", home);
    printf("\n comment       :\t %s", commentfield);
    printf("\n______________________________________________\n\n");

    printf("all of this ok? n/y: ");
    scanf("%c", &reply);

    if(reply != 'y')
    {
        printf("\n exiting....u entered not y");
        exit(1);
    } 

    tmp = fopen("/etc/passwd", "a");
    if (tmp == NULL)
    {
        printf("\npermission denied\n");
        exit(1);
    }
    fprintf(tmp, "%s:x:%d:1:%s:%s:/bin/bash\n", username, usernumber, commentfield, home);
    fclose(tmp);



    stmp = fopen("/etc/shadow", "a");
    if (stmp == NULL)
    {
        printf("\npermission denied\n");
        exit(1);
    }
    fprintf(stmp, "%s:*LK*:::::::\n", username);
    fclose(stmp);

    mkdir(home, 0755);
    chdir(home);


    profile = fopen(".profile", "a");
    fprintf(profile, "stty istrip\n");
    fprintf(profile, "PATH=/bin:/usr/bin:/usr/local/bin:/usr/share/bin:.\n");
    fprintf(profile, "export PATH\n");
    fprintf(profile, "\n\n");
    fclose(profile);

    chown(home, usernumber, 1);
    chown(".profile", usernumber, 1);
    chmod(".profile", 0644);


    printf("\n\nALL done!!!!!!!\n Now set the password: ");
    execl("/usr/bin/passwd", "passwd", username, NULL);
    printf("\n\n SUCCESS PASSWORD IS SET.....BYE!!!\n\n");

}

ВОПРОСЫ:

  1. что потребности файлов состоят в том, чтобы быть редактированием?

  2. Как я могу запустить программу без быть корнем?

  3. что изменяет i потребностей вставить мой код?

0
задан 12 August 2014 в 22:45

1 ответ

Я отправлю ответ, но отмечу, что существует инструмент adduser , который менее подвержен ошибкам и более сложен.

  1. Источник - http://www.tldp.org/LDP/sag/html/adduser.html

11.2.4. При создании пользователя рукой

Для создания новой учетной записи вручную выполните эти шаги:

Edit /etc/passwd with vipw and add a new line for the new account. Be careful with > the syntax. Do not edit directly with an editor! vipw locks the file, so that other commands won't try to update it at the same time. You should make the password field be `*', so that it is impossible to log in.

Similarly, edit /etc/group with vigr, if you need to create a new group as well.

Create the home directory of the user with mkdir.

Copy the files from /etc/skel to the new home directory.

Fix ownerships and permissions with chown and chmod. The -R option is most useful. > The correct permissions vary a little from one site to another, but usually the following commands do the right thing:

cd /home/newusername
chown -R username.group .
chmod -R go=u,go-w .
chmod go= .

Set the password with passwd. 

после установки пароля на последнем шаге учетная запись будет работать. Вы не должны устанавливать его, пока все остальное не было сделано, иначе пользователь может непреднамеренно войти в систему, в то время как Вы все еще копируете файлы.

  1. можно использовать polkit (раньше известный как Policy Kit).

3.:

  • main функция должна возвращать целое число (int).

  • не копируют .profile, копируют целый /etc/skel каталог

0
ответ дан 7 October 2019 в 06:58

Другие вопросы по тегам:

Похожие вопросы: