Adding and deleting users is a basic function that every admin needs to know. Users are added for a multitude of reasons from giving them a home directory for storage to enabling services that require a username such as email, FTP and SSH. In this tutorial we will cover adding a user, removing a user and resetting their password.
Adding a User
The command to add a user is
useradd and takes the form of
useradd [options] username at its simplest. The most useful options for this command are
-c option allows you to create a comment for the new user. To add a comment it would be of the format
adduser mytest -c "your comment here".
If you were adding a user for FTP to a website you would need to set the home directory away from the default
/home/username/ to the location of the web directory. If, for instance, your server is set up with all vhosts in
/var/www/domain2.com etc., and you have just added domain2.com, you will now want to add an FTP user. To set the home directory to /var/www/domain2.com use
adduser -d /var/www/domain2.com username.
-s option sets the shell. Sometimes when you add a user you don’t want them to have a shell. For instance for a service or a user with only FTP access. To do this use
adduser -s /sbin/nologin username.
Removing a user
To remove a user from your system you would use
Changing the password
To change the password of a user you need to use the
passwd command like this:
passwd username. You will then be asked to enter the new password twice. There are a couple of options available to the
passwd command but the
-e is the only one we will cover here. If you want to force a user to change their password at their next login use
passwd -e username.
Changing the password from a script
To change a user’s password from a script you would use the command
chpasswd. This command can also be used to bulk change passwords. It takes an input from the standard input in the format of
username:password. To call this from a script (dependent on language of course) you would use a command like this
echo \"$user:$passwd\" | chpasswd.
Adding the new user to the sudoers group
To add a user to the sodoers group use this command
usermod -aG sudo username. They will now have access to everything that members of the sudoers group does. Please see our
sudo tutorial for more details.
The usermod command
As you can see in the previous section the
usermod command can be used to change the supplementary group that a user belongs to. It can also be used to do many other things such as change the main group, change the home directory and add a comment. Please see the man pages
man usermod for details.