ulak blade
ulak blade

Reputation: 2665

C++ how can I add a linux user to a group programatically

is it possible to add a user on Linux to a group, programatically when I start my program? I am using C++. I know it can be done with the shell, but I need to do it in my C++ program, however I don't know what to use.

Upvotes: 4

Views: 1577

Answers (3)

Messa
Messa

Reputation: 25201

This task is solved by many configuration management software. For example in Salt:

def adduser(name, username):
    on_redhat_5 = __grains__.get('os_family') == 'RedHat' and __grains__.get('osmajorrelease') == '5'    
    if __grains__['kernel'] == 'Linux':
        if on_redhat_5:
            cmd = 'gpasswd -a {0} {1}'.format(username, name)
        else:
            cmd = 'gpasswd --add {0} {1}'.format(username, name)
    else:
        cmd = 'usermod -G {0} {1}'.format(name, username)
    retcode = __salt__['cmd.retcode'](cmd, python_shell=False)
    return not retcode

As you can see, operating system commands are used. Which one depends on what operating system it is :)

Upvotes: 0

eerorika
eerorika

Reputation: 238461

Jared Sutton's two options are valid, but I'd like to point out that you don't have to implement editing /etc/group yourself if you use an existing library.

I know of at least busybox, which has implemented this. There's a function defined in libbb/update_passwd.c

int update_passwd(const char *filename, // /etc/group
    const char *name,                   // username
    const char *new_passwd,             // nullptr
    const char *member)                 // groupname

If you do want to implement it yourself, then you can check out how their function works.

Upvotes: 1

Jared Sutton
Jared Sutton

Reputation: 181

You could take 2 approaches:

  1. Use the system() call to execute a shell command to do the work.
  2. Directly modify the /etc/group file. It should be fairly easy to locate the line that contains the group you wish to add to, and then append the user you want to add on the end (making sure to add a comma if there's already a group member).

Given the choice, I'd probably use the first option from the above.

EDIT: As @DevSolar pointed out in his comment, this answer is assuming that your system is using standard local authentication using passwd/shadow/group files in /etc. If your system is NOT using local auth, then that's a completely different ballgame.

Upvotes: 3

Related Questions