Search code examples
node.jslinuxubuntuchild-process

How to create new user in Linux using nodejs


Below is the code i'm using to run linux command it run but, doesn't show anything in terminal to set new password, group nothing. terminal just runs forever and doesn't exit.

   const child = execFile('sudo',['adduser', 'gku5'], (error, stdout, stderr) => {
    if (error) {
      throw error;
    }
   console.log(stdout);
   }); ```


Solution

  • The command is not adduser, but useradd. For instance, i want to add new user named kbr. The command will be like this-

    sudo useradd kbr
    

    Your program should look like this-

       const child = execFile('sudo',['useradd', 'gku5'], (error, stdout, stderr) => {
        if (error) {
          throw error;
        }
       console.log(stdout);
       });

    And about the output. useradd shows output in RHEL, but it doesn't happen in other distribution. Please refer to this answer for this.

    About the output, you can cat the auth.log file to show the output. For instance, cat /var/log/auth.log | tail -1 would show, something like this,

    Jan 27 19:04:16 useradd[32328]: failed adding user 'kbr', data deleted
    

    So, the program should look like this-

    child = exec('sudo useradd kbr | cat /var/log/auth.log | tail -1',
        function (error, stdout, stderr) {
            console.log('output: ' + stdout);
            if (error !== null) {
                 console.log('exec error: ' + error);
            }
        });