惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
Vulnerabilities – Threatpost
V
V2EX
GbyAI
GbyAI
Recent Announcements
Recent Announcements
Microsoft Security Blog
Microsoft Security Blog
阮一峰的网络日志
阮一峰的网络日志
Hugging Face - Blog
Hugging Face - Blog
T
Tailwind CSS Blog
Y
Y Combinator Blog
C
Check Point Blog
爱范儿
爱范儿
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
美团技术团队
雷峰网
雷峰网
IT之家
IT之家
WordPress大学
WordPress大学
V
Visual Studio Blog
Microsoft Azure Blog
Microsoft Azure Blog
MyScale Blog
MyScale Blog
N
News and Events Feed by Topic
罗磊的独立博客
S
SegmentFault 最新的问题
S
Security Affairs
aimingoo的专栏
aimingoo的专栏
F
Fortinet All Blogs
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
H
Hacker News: Front Page
Google DeepMind News
Google DeepMind News
B
Blog
O
OpenAI News
C
Cisco Blogs
Simon Willison's Weblog
Simon Willison's Weblog
The Last Watchdog
The Last Watchdog
Hacker News: Ask HN
Hacker News: Ask HN
博客园_首页
人人都是产品经理
人人都是产品经理
C
Cybersecurity and Infrastructure Security Agency CISA
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Help Net Security
Help Net Security
月光博客
月光博客
J
Java Code Geeks
L
LangChain Blog
博客园 - 司徒正美
Stack Overflow Blog
Stack Overflow Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
Apple Machine Learning Research
Apple Machine Learning Research
T
The Exploit Database - CXSecurity.com
N
News and Events Feed by Topic
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

DigitalOcean Community Tutorials

Mastering grep with Regular Expressions for Efficient Text Search It's Time to Break Up with Your Cloud: Why AI Teams are Switching We Built a Private-Document AI App to Test Platform Security. Here Is What We Could Actually Verify. PostgreSQL Explained: A Complete Beginner-to-Advanced Guide How To Install and Configure Postfix on Ubuntu How To Build a Web Application Using Flask in Python 3 Build AI Reading List with DigitalOcean Functions and Mistral How To Concatenate Strings in Python How to Allow MySQL Remote Access Securely How To Install and Use Docker on Rocky Linux How To Build a Multi-Agent AI System with Docker Agent DSPy Use Cases: Build Optimized LLM Pipelines How To Submit AJAX Forms with jQuery Build an AI-Powered GPU Fleet Optimizer with the DigitalOcean AI Platform ADK Monitor GPU Utilization in Real Time: A Complete Guide Reduce File Size of Images in Linux - CLI and GUI methods Reduce PDF File Size in Linux: Tools and Methods How To Set Up a Private Docker Registry on Ubuntu How To Troubleshoot Terraform: Errors and Fixes How to Use Go Modules Python Multiprocessing Example: Process, Pool & Queue Convert Class Components to Functional Components with React Hooks How To Install and Configure Ansible on Ubuntu LLM Tokenizers Simplified: BPE, SentencePiece, and More How To Monitor System Authentication Logs on Ubuntu How to Use Traceroute and MTR to Diagnose Network Issues How to Deploy Postgres to Kubernetes Cluster Importing Packages in Go: A Complete Guide Create RAID Arrays with mdadm on Ubuntu How To Make an HTTP Server in Go How To Set Up Time Synchronization on Ubuntu How To Use Struct Tags in Go apt-key Deprecation: Add Repositories with GPG on Ubuntu Linux ps Command: 20 Real-World Examples Python struct.pack and struct.unpack for Binary Data Deadlock in Java: Examples, Detection, and Prevention How To Use Find and Locate to Search for Files on Linux Structured Resume Skill Extraction Using Mistral-7B Inference How to Use the Python Main Function How to Set Up NemoClaw on a DigitalOcean Droplet with 1-Click Build an End-to-End RAG Pipeline for LLM Applications From Single to Multi-Agent Systems: Key Infrastructure Needs Back Up Data to Object Storage Using Restic How to Generate Videos with LTX-2.3 on DigitalOcean GPU Droplets How To Install LAMP Stack (Apache, MySQL, PHP) on Ubuntu How to Download Files with cURL How To Use Variadic Functions in Go Generate UUIDs with uuidgen on Linux How To Use EJS to Template Your Node Application How to Install Node.js on Ubuntu (Step-by-Step Guide) MongoDB Indexes: Improve Query Performance with Node.js LLM Tool Calling with DigitalOcean AI Platform and Databases What are Text Diffusion Models? - An Overview Crafting a Game from Scratch with GPT-5.4 Building Long-Term Memory in AI Agents with LangGraph and Mem0 How To Install PHP 7.4 and Set Up a Local Development Environment on Ubuntu 20.04 Build a GraphQL API in Go to Upload Files to Spaces How To Lint and Format Code with ESLint in Visual Studio Code Train YOLO26 for Retail Object Detection on DigitalOcean GPUs How To Work with JSON in MySQL How to Use the JavaScript .map() Method Building a Scalable App with MongoDB Using DigitalOcean's MCP Server How to Create an SSH Key in Linux: Easy Step-by-Step Guide Measure MySQL Query Performance with mysqlslap How To Use *args and **kwargs in Python 3 Nemotron 3 helped me find the perfect dish rack? A2A vs MCP - How These AI Agent Protocols Actually Differ How To Install and Manage Supervisor Docker Container Images with Watchtower on Ubuntu Getting Started with Qwen3.5 Vision-Language Models How To Create a New Sudo-Enabled User on Ubuntu How to Use Ansible to Install and Set Up Docker on Ubuntu How To Enable Remote Desktop Protocol Using xrdp on Ubuntu 22.04 How To Convert a String to a List in Python How To Check If a String Contains Another String in Python How to Read a Properties File in Python Python Command Line Arguments: sys.argv, argparse, getopt Mastering Grep command in Linux/Unix: A Beginner's Tutorial Understanding Python Data Types How to Implement a Stack in C With Code Examples Python os.system() vs subprocess: Run System Commands How To Install and Use Docker Compose on Ubuntu How To Order Query Results in Laravel Eloquent How To Define and Use Handlers in Ansible Playbooks How To Install and Use SQLite on Ubuntu How To Install and Use Homebrew on macOS How To Manage DateTime with Carbon in Laravel and PHP How To Install Git on Ubuntu How To Install and Secure Redis on Ubuntu How To Build and Install Go Programs on Linux Using ldflags to Set Version Information for Go Applications How To Build a Node.js Application with Docker How To Add JavaScript to HTML How To Reset Your MySQL or MariaDB Root Password How To Add Images in Markdown How To Set Up a Production Elasticsearch Cluster with Ansible How To Set Up a Firewall Using firewalld on CentOS Understanding Systemd Units and Unit Files How To Set Up Replication in MySQL How To Use the .htaccess File
How to Add and Delete Users on Ubuntu
Jamon Camisso · 2022-03-12 · via DigitalOcean Community Tutorials

Introduction

Adding and removing users on a Linux system is one of the most important system administration tasks to familiarize yourself with. When you create a new system, you are often only given access to the root account by default.

While running as the root user gives you complete control over a system and its users, it is also dangerous and possibly destructive. For common system administration tasks, it’s a better idea to add an unprivileged user and carry out those tasks without root privileges. You can also create additional unprivileged accounts for any other users you may have on your system. Each user on a system should have their own separate account.

For tasks that require administrator privileges, there is a tool installed on Ubuntu systems called sudo. Briefly, sudo allows you to run a command as another user, including users with administrative privileges. In this guide, you’ll learn how to create user accounts, assign sudo privileges, and delete users.

Deploy your frontend applications from GitHub using DigitalOcean App Platform. Let DigitalOcean focus on scaling your app.

Key Takeaways:

  • Using the root account for routine tasks is discouraged due to security risks; instead, create standard users and elevate privileges only when necessary using sudo.
  • The adduser command offers a straightforward and interactive way to create new user accounts, including setting passwords and optional profile details.
  • Administrative privileges are most effectively managed by adding users to the sudo group, which grants them the ability to execute commands with elevated permissions.
  • The visudo command should always be used when editing the /etc/sudoers file, as it validates changes and helps prevent configuration errors that could break access control.
  • Removing a user account does not automatically delete their files; using options like --remove-home ensures complete cleanup when required.
  • User accounts can be temporarily disabled without deletion by locking passwords or assigning a non-login shell, preserving user data while restricting access.

Prerequisites

To complete this tutorial, you will need access to a server running Ubuntu. If you don’t have an Ubuntu server, you can refer to How To Set Up an Ubuntu Server on a DigitalOcean Droplet to quickly set up a server. Ensure that you have root access to the server and firewall enabled. To set this up, follow our Initial Server Setup with Ubuntu.

Adding a User

If you are signed in as the root user, you can create a new user at any time by running the following:

  1. adduser newuser

If you are signed in as a non-root user who has been given sudo privileges, you can add a new user with the following command:

  1. sudo adduser newuser

Either way, you will be required to respond to a series of questions:

  • Assign and confirm a password for the new user.
  • Enter any additional information about the new user. This is optional and can be skipped by pressing ENTER if you don’t wish to utilize these fields.
  • Finally, you’ll be asked to confirm that the information you provided was correct. Press Y to continue.

Your new user is now ready for use and can be logged into with the password that you entered.

If you need your new user to have administrative privileges, continue on to the next section.

Granting a User Sudo Privileges

If your new user should have the ability to execute commands with root (administrative) privileges, you will need to give the new user access to sudo. Let’s examine two approaches to this task: first, adding the user to a pre-defined sudo user group, and second, specifying privileges on a per-user basis in sudo’s configuration.

Adding the New User to the Sudo Group

By default, sudo on Ubuntu systems is configured to extend full privileges to any user in the sudo group.

You can view what groups your new user is in with the groups command:

  1. groups newuser

Output

newuser : newuser

By default, a new user is only in their own group because adduser creates this in addition to the user profile. A user and its own group share the same name. In order to add the user to a new group, you can use the usermod command:

  1. usermod -aG sudo newuser

The -aG option tells usermod to add the user to the listed groups.

Please note that the usermod command itself requires sudo privileges. This means that you can only add users to the sudo group if you’re signed in as the root user or as another user that has already been added as a member of the sudo group. In the latter case, you will have to precede this command with sudo, as in this example:

  1. sudo usermod -aG sudo newuser

Specifying Explicit User Privileges in /etc/sudoers

As an alternative to putting your user in the sudo group, you can use the visudo command, which opens a configuration file called /etc/sudoers in the system’s default editor, and explicitly specify privileges on a per-user basis.

Using visudo is the only recommended way to make changes to /etc/sudoers because it locks the file against multiple simultaneous edits and performs a validation check on its contents before overwriting the file. This helps to prevent a situation where you misconfigure sudo and cannot fix the problem because you have lost sudo privileges.

If you are currently signed in as root, run the following:

  1. visudo

If you are signed in as a non-root user with sudo privileges, run the same command with the sudo prefix:

  1. sudo visudo

Traditionally, visudo opened /etc/sudoers in the vi editor, which can be confusing for inexperienced users. By default on new Ubuntu installations, visudo will use the nano text editor, which provides a more convenient and accessible text editing experience. Use the arrow keys to move the cursor, and search for the line that reads like the following:

/etc/sudoers

root    ALL=(ALL:ALL) ALL

Below this line, add the following highlighted line. Be sure to change newuser to the name of the user profile that you would like to grant sudo privileges:

/etc/sudoers

root     ALL=(ALL:ALL) ALL
newuser ALL=(ALL:ALL) ALL

Add a new line like this for each user that should be given full sudo privileges. When you’re finished, save and close the file by pressing CTRL + X, followed by Y, and then ENTER to confirm.

Testing Your User’s Sudo Privileges

Now your new user is able to execute commands with administrative privileges.

When signed in as the new user, you can execute commands as your regular user by typing commands as normal:

  1. some_command

You can execute the same command with administrative privileges by typing sudo ahead of the command:

  1. sudo some_command

When doing this, you will be prompted to enter the password of the regular user account you are signed in as.

Deleting a User

In the event that you no longer need a user, it’s best to delete the old account.

You can delete the user itself, without deleting any of their files, by running the following command as root:

  1. deluser newuser

If you are signed in as another non-root user with sudo privileges, you would use the following:

  1. sudo deluser newuser

If, instead, you want to delete the user’s home directory when the user is deleted, you can issue the following command as root:

  1. deluser --remove-home newuser

If you’re running this as a non-root user with sudo privileges, you would run the same command with the sudo prefix:

  1. sudo deluser --remove-home newuser

If you previously configured sudo privileges for the user you deleted, you may want to remove the relevant line again:

  1. visudo

Or use the following command if you are a non-root user with sudo privileges:

  1. sudo visudo

/etc/sudoers

root     ALL=(ALL:ALL) ALL
newuser ALL=(ALL:ALL) ALL   # DELETE THIS LINE

This will prevent a new user created with the same name from being accidentally given sudo privileges.

If a group was primarily for a specific user who has been deleted, and no other users are members of that group, you might want to remove it. You can do this using the delgroup command:

  1. sudo delgroup groupname

Locking a User Instead of Deleting

There are scenarios where you might want to temporarily disable a user account instead of deleting it permanently. Locking a user account typically involves making it impossible for them to log in without removing their home directory, files, or user ID.

Locking the Password

You can “lock” a user’s password which will prevent them from authenticating using their account password. This is a common and effective way to disable login for a user. If you’re signed in as root, you can do this using the following command:

  1. passwd -l username

If you are signed in as a non-root user who has been given sudo privileges, you can lock the password with the following command:

  1. sudo passwd -l username

The -l option renders the original password invalid by prepending a ! character to the hashed password in /etc/shadow.

To unlock a user’s password and allow them to log in again, using their original password, run the following command:

  1. passwd -u username

And if you are signed in as a non-root user with sudo privileges, you can use the following command:

  1. sudo passwd -u username

The -u option unlocks the password by removing the lock (the ! prefix) from the password hash so the existing password works again.

Note that locking a password only disables password-based authentication. For example, if the user can authenticate using SSH keys, they may still be able to access the system unless you also disable SSH access for that user.

Disabling the Account (No Login Shell)

Another approach is to change the user’s default login shell to a non-existent or null shell (like /usr/sbin/nologin or /bin/false). This prevents the user from establishing an interactive shell session upon login.

To change a user’s shell to /usr/sbin/nologin:

  1. sudo usermod -s /usr/sbin/nologin username

To revert the shell to their original (e.g., /bin/bash):

  1. sudo usermod -s /bin/bash username

FAQs

1. What is the difference between adduser and useradd?

adduser is a high-level, and user-friendly script that simplifies the process of creating a new user account. It interactively prompts for information, automatically creates a home directory, copies skeleton files (like .bashrc, .profile), sets appropriate permissions, and assigns a default shell. In most cases, it’s the recommended command for creating users on Debian-based systems like Ubuntu.

useradd is a lower-level binary that provides fine-grained control over user creation. It does not create a home directory or copy skeleton files by default, requiring these to be specified with options or handled manually. It’s often used in scripts or for automated system management where precise control and non-interactive operation are necessary.

2. How do I give a user sudo privileges in Ubuntu?

The most common and recommended way to grant sudo privileges to a user on Ubuntu is by adding them to the sudo group. Members of this group are typically configured to be able to execute commands with root privileges.

You can add an existing user to the sudo group using the usermod command:

  1. sudo usermod -aG sudo username

Replace username with the actual name of the user. The -a flag stands for “append” and -G specifies the supplementary group. Changes usually take effect upon the user’s next login.

3. Does deleting a user also remove their files?

By default, the deluser command in Ubuntu (without specific options) deletes the user account but leaves their home directory and mail spool intact.

To remove a user’s home directory and mail spool along with the account, you should use the --remove-home option:

  1. sudo deluser --remove-home username

If you wish to remove the user’s home directory and also create a backup before deletion, you can use the --backup-home option:

  1. sudo deluser --backup-home username

4. Can I recover a deleted user?

Directly “recovering” a deleted user account with a single command is generally not possible in Linux. Once a user account is deleted, its entry is removed from system files like /etc/passwd, /etc/shadow, and /etc/group.

However, the possibility of data recovery depends on how the user was deleted. If only the account was deleted (e.g., deluser username without --remove-home), the user’s home directory and files will still exist on the system. You can then recreate the user with the same username and, if possible, the same User ID (UID) and Group ID (GID), then point their new home directory to the old one. This allows them to regain access to their original files.

5. How can I check if a user has sudo privileges?

You can verify whether a user has sudo privileges by checking their group membership. Users in the sudo group typically have administrative access. Run:

  1. groups username

If sudo appears in the output, the user has sudo privileges. Alternatively, you can inspect the /etc/sudoers file (using visudo) to see if explicit permissions have been assigned.

6. How can I switch between users in Ubuntu?

You can switch to another user account using the su (substitute user) command:

  1. su - username

This starts a new login session for the specified user and prompts for their password. If you already have sudo privileges, you can switch users without needing their password:

  1. sudo su - username

This is commonly used by administrators to perform tasks as another user.

Conclusion

You should now have a fairly good handle on how to add and remove users from your Ubuntu system, along with how to manage sudo privileges, remove user groups and lock user accounts. Effective user management is important for maintaining the security, organization, and integrity of the Ubuntu system. The skills you learned today will allow you to separate users and give them only the access that they are required to do their job.

For more information about how to configure sudo, check out our guide on how to edit the sudoers file.

For more Ubuntu-based content, check out the following articles:

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.