Sometime we need to add a user on Linux environment from command line or from a shell/bash script and give it sudo access. Linux has command useradd
which can be used to this purpose and sudo permission can be given using /etc/sudoers.d directory. Here are the steps for this on Ubuntu Linux (will work on Amazon linux and other linux flavours also):
Add a user with default shell as bash
To add user (say user1) with default shell bash, without password and create home directory if needed, run the following command as root:
$ useradd user1 -m -s /bin/bash
In case you want to create a user with password use -p
. This will prompt you for a password.
Authorizing user’s key to ssh
It is a good idea to use user’s key to ssh to machine as that user. Run the following commands for that as root:
$ su - user1 $ mkdir ~/.ssh $ cd ~/.ssh $ cat [user1_public_key_file] >> authorized_keys $ chown user1
Now you can login to the machine using the following command:
ssh -i [user1_private_key_file] user@host
Add password less sudo access
To provide user sudo access we can create a file in /etc/sudoders.d/user and the following line in it:
user1 ALL=(ALL) NOPASSWD: ALL
Please note that this has to be run as root user. Now login as user1 and run any command with sudo to test. e.g. run ls with sudo as shown below:
sudo ls -l
We have used user1 for the purpose of this article. You can use any other user and replace user1 wit it in above instructions.