Create Sudo-Enabled User on Linux
The main idea of this post comes from here: How To Create a New Sudo-enabled User on Ubuntu 20.04 [Quickstart]. You can go there for other versions and distributions.
How to?
Step 1. Adding new user
First, we should add a new user to our system adduser
, with basic configurations. You should replace “tony” with your username.
1 | # adduser tony |
It will immediately prompt you to set password for this user.
1 | New password: |
Following is some extra information, which may not make sense. So just press Enter to leave them by default.
Step 2. Add the user to sudo
group
Now that we have the new user, add it to sudo
group using usermod
.
1 | # usermod -aG sudo tony |
This is it, then you should be able to use sudo
as tony.
Step 3. Verify sudo
access
Change to the user using su tony
or login to the user using login tony
, and try to run a command with sudo
. For example, sudo apt update
. If it prompts you to enter the password, then everything works well.
However, there is possibility that you may encounter this:
1 | -bash: sudo: command not found |
It may happen when you’re in a docker image, which do not have sudo
command by default. So you should install it as root.
1 | # apt install sudo |
After installation, the problem will be no more.
Step 4. sudo
without password (optional)
Sometimes you may use sudo
in automation scripts, where user input is not available. This case, you may need to allow sudo
execution without password. To achieve this,
1 | sudo visudo |
If you’re using Ubuntu, then the default editor is probably nano. Go to the bottom of the file, and add this line. Replace “tony” to your username.
1 | tony ALL=(ALL:ALL) NOPASSWD: ALL |
Then, hit Ctrl + X
, Y
, then Enter
to save and quit. Now, sudo
will no longer prompt password.
Extra
Now that we have the user, how can we login as the new user, instead of root by default?
For SSH connection, we can simply change the username and password for the server IP. If you are using docker, things would be a little more tricky. For example, if you have a container called “tony-container”, in which you added a user called “tony”, then you can use this command below to run the bash in it with this profile in its home directory.
1 | docker exec -it --user tony -w /home/tony tony-container bash |
If you care about highlighting, here is a example .bashrc
file. Copy it, or override options respectively in yours. One thing to notice is that, in a docker container, TERM
variable may not be set. You can either set it in docker exec
using -e TERM=xterm-256color
or add export TERM=xterm-256color
in .bashrc
.
1 | # ~/.bashrc: executed by bash(1) for non-login shells. |