Sign In
Sign In

How to Install Jupyter Notebook on Ubuntu 22.04

How to Install Jupyter Notebook on Ubuntu 22.04
Anees Asghar
Technical writer
Ubuntu
14.02.2025
Reading time: 7 min

Jupyter Notebook is a free and open tool that enables users to generate engaging files to script and run code, render mathematical expressions, show graphs, and add explanatory text. It's extensively applied in data science, machine learning, and academic research. Ubuntu 22.04 users can install Jupyter Notebook efficiently with minimal effort.

In this write-up, we'll elaborate on stepwise instructions needed to install Jupyter on Ubuntu 22.04.

System Requirements

Before proceeding with the installation, you must fulfill the below-listed requirements:

  • Ubuntu 22.04 must be properly set up and running.
  • Jupyter relies on Python3, which is generally included in most Linux distributions. Verifying its presence by executing the python3 --version command in the terminal.
  • pip serves as the package manager for Python and is necessary for installing Jupyter Notebook and other libraries. So, verify the pip’s installed version before proceeding.

Key Advantages of Jupyter

Jupyter (also known as IPython Notebook) provides numerous benefits, making it highly popular in data science, machine learning, and coding education:

  • It enables real-time coding and execution, simplifying debugging and testing.
  • Although primarily designed for Python, it also supports other languages such as R and Julia.
  • We can incorporate notes, formulas, and visualizations (like charts and graphs) alongside our code, making it easy to explain our work. 
  • It integrates code, comments, and outputs in one document, so it's easy to share and collaborate with others. 
  • You can even add extra features and widgets to make your work more interactive. Moreover, it helps us keep a clear record of our steps, making it simple for others to follow or reproduce our work.

Overall, its versatility and intuitive attributes make it an excellent application for anyone looking to boost their coding, learning, and collaboration experience.

Installing Jupyter on Ubuntu 22.04

Setting up Jupyter Notebook on Ubuntu 22.04 requires a few simple steps to get it running:

Upgrade Your System

Before adding any new programs, it's advisable to refresh repositories:

sudo apt update && sudo apt upgrade -y

This command refreshes all the installed packages to their latest available versions, with the -y flag automatically confirming the action:

Image1

Python3 and Pip Installation

If Python3 and pip are not set up in your system yet, you can install them by employing the below-given commands:

sudo apt install python3 -y #Install Python3
sudo apt install python3-pip -y #Install pip for Python3

To demonstrate that pip is set up properly, check its version using the given command:

pip3 --version

The resultant screenshot indicates that pip 22.0.2 is appropriately installed on the system:

Image3

Preparing a Virtual Environment

Once Python3 is installed, you can set up a virtual environment. First, let’s install venv module for Python that enables us to create virtual environments:

sudo apt install python3.10-venv

After this, create a new directory named hostman by employing the command:

mkdir hostman

Let’s navigate to the newly created project directory by running the cd command:

cd hostman

Now we can create a virtual environment where Jupyter Notebook can be installed:

python3.10 -m venv jupyterNotebook-venv

Once the environment is established, enable it by running:

source jupyterNotebook-venv/bin/activate

Image2

Installing Jupyter/IPython

Once Python and pip are appropriately installed, we can proceed with the Jupyter installation.

Before moving ahead, we need to update pip3 to the most recent version:

pip install --upgrade pip

Image5

Next, execute the given command to install Jupyter alongside its associated dependencies:

pip3 install jupyter

The image demonstrates that Jupyter Notebook is properly installed alongside all essential components:

Image4

Confirm Jupyter Installation Status

To check the installation status of Jupyter on your Ubuntu system, confirm its version:

jupyter --version

It retrieves the installed Jupyter version alongside other corresponding components, including JupyterLab and Jupyter_Server, if available:

Image7

How Jupyter Works

Once the setup is finished, run the Jupyter Notebook utilizing the command:

jupyter notebook

This will kick off the Jupyter server and provide a response that resembles the following:

Image6

To access Jupyter, copy the above-highlighted URL and paste it into your computer browser:

Image9

Notebook Setup

Browse the New panel available on the dashboard, expand the dropdown menu, and select Python3 (ipykernel):

Image8

Script Execution

Once your Jupyter notebook is good to use, specify your code, and press Shift + Enter to execute the script:

print("Welcome to Hostman!")

Image12

Installing Jupyter through Anaconda

Anaconda offers a simple and efficient method to install the Jupyter Notebook. If Anaconda is preinstalled on our machine, we can proceed with the Jupyter’s installation/setup by typing the given command:

conda install jupyter

It automatically downloads and installs Jupyter alongside necessary dependencies, making sure it’s good to use without requiring an additional setup process.

Installing JupyterLab on Ubuntu

JupyterLab presents a dynamic and adaptable platform for handling notebooks, writing code, and analyzing data. It functions as an advanced variant of the Jupyter Notebook, offering a more customizable and feature-rich experience. JupyterLab efficiently organizes multiple notebooks, code consoles, and various documents within a tabbed layout. It also supports real-time coordination/collaboration, easy file navigation, and integrates with multiple development tools, making it ideal for handling complex tasks.

While Jupyter is great for simpler tasks, JupyterLab offers a more advanced experience. To begin utilizing JupyterLab, we must first install it on our system with the below-provided command:

pip3 install jupyterlab

After completing the installation, we can access JupyterLab by employing this command:

jupyter-lab

It will commence JupyterLab in our browser, which presents a more advanced interface for managing notebooks.

Uninstalling Jupyter From Ubuntu

If Jupyter is no longer required, you can uninstall it effortlessly. Employ this command to remove Jupyter alongside its associated dependencies:

pip3 uninstall jupyter -y

Image10

To completely remove Jupyter, including stored settings, cached data, and user configurations, delete the associated files and directories:

rm -rf ~/.jupyter
rm -rf ~/.local/share/jupyter

Image11

This process ensures that Jupyter is entirely removed, leaving no leftover files in the system.

Effective Ways to Optimize Jupyter Notebook Usage

Below are some effective tips for configuring and operating Jupyter Notebook on Ubuntu:

  • Before installation, update your system and confirm that Python3 and pip are properly installed.
  • Utilize a virtual environment to maintain an efficient, dedicated environment and prevent conflicts with other Python projects.
  • To avoid compatibility concerns, make sure that Python and pip have been updated to the newest versions.
  • Utilize pip to install Jupyter inside the virtual environment to efficiently handle required dependencies.
  • If you need a more advanced interface with enhanced features such as real-time collaboration and file management, consider installing JupyterLab instead of Jupyter Notebook.

Executing these practices guarantees a precise setup and an efficient and productive platform for coding, analytical work, and research projects.

Final Thoughts

Jupyter or IPython Notebook is an essential medium for developers, researchers, and learners working with coding and data analysis. Its capability to seamlessly integrate code, graphs, and explanations into a single document makes it a perfect choice for collaborative work and educational purposes.

Installing Jupyter on Ubuntu 22.04 is simple, and by implementing the instructions demonstrated in this post, you can quickly set up a productive workspace. Additionally, utilizing best practices such as using a virtual environment and keeping Python and pip updated helps maintain a seamless experience.

Ubuntu
14.02.2025
Reading time: 7 min

Similar

Ubuntu

How to Install and Use Composer on Ubuntu

Composer is a cross-platform tool for managing dependencies in projects written in PHP. With Composer, you can manage numerous libraries and frameworks, known as "packages." Installing the required packages allows you to extend the standard PHP functionality, speeding up and simplifying development. All installed packages become project dependencies. Thus, Composer can be considered a full-fledged dependency manager, similar to those used in many programming languages. Additionally, Composer has a comprehensive package repository called Packagist, where you can search for, download, and install the required packages. This guide provides detailed instructions on installing Composer on an Ubuntu server and using it for PHP projects. Prerequisites In this tutorial, we use: A VPS server running Ubuntu 22.04 PHP interpreter version 8.1.2 Composer dependency manager version 2.8.2 Installing Composer First, update the list of existing APT repositories: sudo apt update Next, install the packages required to download and use Composer: sudo apt install curl php-cli unzip -y These packages include: curl: A tool for making HTTP requests. php-cli: An interpreter to run PHP scripts. unzip: A utility to extract ZIP archives. The -y flag answers "yes" to all installation prompts. Composer installation is automated using a PHP script provided by its developers. Download the installation script from the official Composer website using an HTTP request: curl -sS https://getcomposer.org/installer -o composerInstall.php The -sS flag runs curl in silent mode, suppressing all output except for errors. The -o flag specifies the filename and the directory where the file will be placed. To ensure the file has been downloaded, check the contents of the current directory: ls You should see the following output in the terminal, including the installation script: composerInstall.php  resize.log  snap This guide covers the global installation of Composer, meaning it can be run from any directory without specifying the absolute path. To perform a global installation, execute the downloaded PHP script with additional parameters: php composerInstall.php --install-dir=/usr/local/bin --filename=composer The --install-dir flag specifies the directory where Composer will be installed. The --filename flag defines the name of the binary file accessible from the terminal. In this case, Composer is installed in the system's binary directory: /usr/local/bin. After running the script, you'll see the following output in the terminal: All settings correct for using Composer Downloading... Composer (version 2.8.2) successfully installed to: /usr/local/bin/composer Use it: php /usr/local/bin/composer Since the installation script is no longer needed, you can delete it: rm composerInstall.php To launch Composer for the first time, run: composer You may see the following message in the terminal: Do not run Composer as root/super user! See https://getcomposer.org/root for details Continue as root/super user [yes]? Composer warns against running it as the root user due to potential risks but allows you to proceed. For this guide, we will continue using Composer as-is by confirming with yes. Afterward, you will see a welcome message along with a list of available options and commands with brief descriptions. Composer is now fully installed. Configuring Composer The main file used to manage dependencies is composer.json, which describes the packages required for the proper functioning of a project. Composer follows the Infrastructure as Code (IaC) approach, describing the local project infrastructure through a configuration file rather than manual settings adjustments in a graphical interface. However, Composer allows configuration management not only by manually editing the file in a text editor but also through console commands, providing a more interactive way to handle configurations. Basic Commands Using Composer involves several fundamental commands that interact with the composer.json configuration file: init: Initializes a project. require: Adds a package. install: Installs dependencies. update: Updates packages. Although Composer offers many more commands, these are the most frequently used. Creating a Directory Create a separate directory for the PHP project: mkdir phptest Then navigate to the directory: cd phptest This directory will store both the project’s source code and the required dependency files. Searching for a Library Suppose we are working on a small project that performs various string transformations. As a dependency, we need a specific library that provides functions for manipulating string content. In this guide, we will implement a common programming function called slugify, which converts a sequence of words into a single long word containing only lowercase ASCII characters and hyphens. The slugify function is often used to transform arbitrary headings into URL-friendly formats without spaces. Rather than writing this function ourselves, we will use Composer to find a suitable library in the official package registry, add it as a dependency, and let Composer handle its download, installation, and integration into the project. To find the necessary library, follow these steps: Open the Composer's official package registry in a browser. Enter "slugify" in the search bar. Look for the most suitable package based on its parameters and description. The search results display key metrics for each available package: The number of installations via Composer (top right) The number of GitHub stars (bottom right) In general, popular packages tend to be more stable since they are used by a larger number of developers. Selecting a Package In this guide, we will use the package cocur/slugify. The package name, similar to a GitHub repository, contains the author (provider) and the library name separated by a forward slash (/). We can navigate to the package's page by clicking its name to see more details about the library’s implementation, such as dependency lists, descriptions with code examples, test coverage badges, license type, and more. Additionally, pay attention to the available package versions, as you need to specify the version during dependency installation. By following this process, you can search for and select suitable packages for a PHP project, which can later be used as dependencies to provide specific functions. Installing a Dependency To install the required package, use the require command. This either records the dependency in the composer.json configuration file or creates it if it does not exist: composer require cocur/slugify:4.6 In this guide, we are using cocur/slugify version 4.6.0. After running the command, you might encounter an error indicating missing system libraries: ./composer.json has been created Running composer update cocur/slugify Loading composer repositories with package information Updating dependencies Your requirements could not be resolved to an installable set of packages. Problem 1 - Root composer.json requires cocur/slugify 4.1 -> satisfiable by cocur/slugify[v4.1.0]. - cocur/slugify v4.1.0 requires ext-mbstring * -> it is missing from your system. Install or enable PHP's mbstring extension. This console output informs us that the ext-mbstring system library is missing, which is necessary for cocur/slugify to work correctly. You can manually search for the library using the APT package manager: sudo apt search mbstring The search results will show: Sorting... Done Full Text Search... Done php-mbstring/jammy 2:8.1+92ubuntu1 all MBSTRING module for PHP [default] php-patchwork-utf8/jammy 1.3.1-1 all UTF-8 strings handling for PHP php-symfony-polyfill-mbstring/jammy 1.24.0-1ubuntu2 all Symfony polyfill for the Mbstring extension php-symfony-polyfill-util/jammy 1.24.0-1ubuntu2 all Symfony utilities for portability of PHP codes php8.1-mbstring/jammy-updates,jammy-security 8.1.2-1ubuntu2.19 amd64 MBSTRING module for PHP The first result is the library we need. Install it with: sudo apt install php-mbstring -y Once the missing library is installed, rerun the command to install the package: composer require cocur/slugify:4.6 This time, the console output should confirm a successful installation: ./composer.json has been created Running composer update cocur/slugify Loading composer repositories with package information Updating dependencies Lock file operations: 1 install, 0 updates, 0 removals - Locking cocur/slugify (v4.6.0) Writing lock file Installing dependencies from lock file (including require-dev) Package operations: 1 install, 0 updates, 0 removals - Downloading cocur/slugify (v4.6.0) - Installing cocur/slugify (v4.6.0): Extracting archive Generating autoload files No security vulnerability advisories found. Check the directory contents with: ls You will see new files generated by Composer: composer.json  composer.lock  vendor Each file and directory serves a specific purpose: composer.json — Contains information about the required dependencies composer.lock — Records details about installed dependencies vendor — Stores the project’s installed dependencies If you use a version control system like Git, exclude the vendor directory from the repository. Take a look inside composer.json: cat composer.json It should look like this: { "require": { "cocur/slugify": "4.6" } } You’ll notice the require block specifying the package cocur/slugify version 4.6. You can find more detailed information about possible version values in the official Composer documentation. Using Composer Including Dependencies Once you have installed a dependency, you can include it in the project code using the automatically generated autoload.php script, located in the vendor directory. When this script is included in the PHP application, the functions and classes of the installed dependencies become available for use. Let's create the main file of our application: sudo nano main.php Then, fill it with the following content: <?php require __DIR__ . '/vendor/autoload.php'; use Cocur\Slugify\Slugify; $slugify = new Slugify(); // PHP_EOL is needed for line breaks in the console echo '[english]: ' . $slugify->slugify('How to deal with composer') . PHP_EOL; ?> Now, you can run the script: php main.php The output in the console terminal should look like this: [english]: how-to-use-composer Updating Dependencies Composer allows you to check for new versions of libraries based on version ranges defined in the composer.json configuration file: composer update Alternatively, you can update a specific package by specifying its name: composer update cocur/slugify Installing Dependencies If your PHP project contains a composer.json file, but the specified dependencies are not yet installed, you need to install them. Let’s first remove all existing packages and related information: rm -R vendor composer.lock The -R flag is necessary for recursive deletion of files and directories. After that, try running the script: php main.php You will see the expected error message in the console because the dependencies are missing: PHP Warning: require(/root/phptest/vendor/autoload.php): Failed to open stream: No such file or directory in /root/phptest/main.php on line 2 PHP Fatal error: Uncaught Error: Failed opening required '/root/phptest/vendor/autoload.php' (include_path='.:/usr/share/php') in /root/phptest/main.php:2 Stack trace: #0 {main} thrown in /root/phptest/main.php on line 2 Now, let's reinstall the dependencies based on the data from the configuration file: composer install After that, run the script again: php main.php The console should display the expected result without any errors: [english]: how-to-install-and-use-composer Conclusion You can install Composer on Ubuntu 22.04 automatically using an installation script from the official Composer website. Although Composer has many commands to manage the composer.json configuration file, in practice, only a few basic ones are commonly used: composer init composer require composer install composer update You can find comprehensive information on how to use Composer in the official documentation.
14 February 2025 · 10 min to read
Ubuntu

How to Add and Delete Users on Ubuntu

In multi-user environments like Ubuntu Linux, effective user management isn’t just a technical task—it’s a cornerstone of system security and operational efficiency. Whether you’re administering a corporate server, a development workstation, or a personal machine, controlling who has access and what they can do ensures resources are allocated appropriately and sensitive data remains protected. Consider a scenario where a disgruntled employee retains access to critical systems after leaving an organization. Without proper user management protocols, this oversight could lead to data breaches, service disruptions, or compliance violations.  Conversely, a well-maintained system minimizes attack surfaces, streamlines collaboration, and simplifies auditing. This guide dives deep into Ubuntu’s user management tools, offering step-by-step instructions, advanced customization techniques, and security best practices to help you maintain a secure and organized environment. Creating User Accounts Ubuntu provides multiple tools for user creation, each catering to different administrative needs. Below, we explore both beginner-friendly and advanced methods. Simplified Setup with adduser The adduser command is ideal for administrators who prefer an interactive, guided setup. It automates key steps like home directory creation and password assignment, reducing the risk of errors. sudo adduser john_doe  After executing this command, Ubuntu will prompt you to: Set a strong password: Enter it twice to confirm. Add optional user details: Full name, phone number, or room number (useful for organizational tracking). Verify inputs: Confirm "Y" to finalize the account. What Happens Behind the Scenes? A home directory (/john_doe/) is created with default configuration files (e.g., .bashrc, .profile) copied from /etc/skel. A primary group named john_doe is generated, and the user is added to it. Account metadata is stored in /etc/passwd, while encrypted passwords are saved to /etc/shadow. When to Use adduser: Quick setup for standard users. Environments where consistency in home directory structure is critical. Advanced Configuration with useradd For precise control, useradd allows administrators to define parameters explicitly. This method is favored in scripting or automated workflows. sudo useradd -m -d /opt/auditors/john_doe -s /bin/zsh -G auditors,security john_doe  Let’s break down the above command: -m: Creates the user’s home directory. -d: Specifies a custom home directory path (e.g., /opt/auditors/john_doe). -s: Sets the default shell (Zsh in this case; replace with /bin/fish for Fish shell). -G: Adds the user to secondary groups (auditors and security). However, unlike adduser, useradd doesn’t set a password. Use passwd afterward: sudo passwd john_doe When to Use useradd: Bulk user creation via scripts. Non-standard home directory locations (e.g., network-mounted storage). Integration with configuration management tools like Ansible.  Verifying and Troubleshooting New Accounts After creating an account, you can confirm its configuration: First, you can check User ID (UID) and group memberships: id john_doe Output: uid=1002(john_doe) gid=1002(john_doe) groups=1002(john_doe),1003(auditors),1004(security) Next, you can inspect home directory permissions: ls -ld /home/john_doe Ensure ownership is assigned correctly: drwxr-xr-x 2 john_doe john_doe 4096 Jul 10 10:00 /home/john_doe Common Pitfalls: Missing Home Directory: Omit -m in useradd? Run sudo mkhomedir_helper john_doe to create it retroactively. Incorrect Shell: Edit /etc/passwd manually or use usermod -s /bin/bash john_doe. Tailoring Permissions with Groups Groups are the backbone of Linux permission management, enabling administrators to control access to files, directories, and applications Linux Group Hierarchy Primary Group: Assigned at user creation; owns files created by the user. Secondary Groups: Grant additional privileges (e.g., sudo for admin rights, docker for container management). Example: Restricting Access to a Web Directory sudo groupadd webdevsudo chown -R :webdev /var/www/htmlsudo chmod -R 2775 /var/www/html  # Setgid ensures new files inherit group ownership Add users to the webdev group: sudo usermod -aG webdev john_doe Granting Administrative Privileges Members of the sudo group gain root access via the sudo command. Let’s add a user to the sudo group: sudo usermod -aG sudo john_doe We can test the sudo access using: sudo -l -U john_doe The above command lists all the allowed commands for the john_doe user. For a more precise control, you can edit /etc/sudoers with visudo: sudo visudo Then add lines like: john_doe ALL=(ALL) NOPASSWD: /usr/bin/apt updatejohn_doe ALL=(ALL) /usr/bin/systemctl restart apache2 In the above: NOPASSWD allows running specific commands without a password. The second rule requires john_doe to use a password to restart Apache with sudo privilege. Password Policies and Account Security Weak passwords and stale accounts are prime targets for attackers. Ubuntu offers tools to enforce robust security practices. Enforcing Strong Passwords Install password quality library: sudo apt install libpam-pwquality  Then, edit /etc/security/pwquality.conf to set: minlen = 12dcredit = -1  # Require at least one digitucredit = -1  # Require at least one uppercase letterenforce_for_root  # Apply policies to root Next, set password expiration: sudo chage -M 90 -W 14 john_doe Here, the password expires every 90 days and warns 14 days before the expiration date. Locking and Unlocking Accounts You can temporarily lock user accounts using: sudo passwd -l john_doe The above command prevents login but retains files. To unlock the user account, use the below command: sudo passwd -u john_doe Additionally, you can set account expiration using the below command: sudo usermod -e 2024-12-31 john_doe This can come quite handy when working with a contractor. Monitoring and Auditing To view login history, use the command: last john_doe Furthermore, you can check active sessions using: who | grep john_doe Next, you can audit sudo commands using: sudo grep 'john_doe' /var/log/auth.log Removing User Accounts Safely Improper deletion can lead to orphaned files or broken dependencies. Follow the below steps to remove users neatly: Preserving Data with deluser sudo deluser john_doe The above command removes the user but retains /home/john_doe. You can archive the home directory to backup storage. 2. Complete Account Removal To remove an account completely, use the below command: sudo deluser --remove-home john_doe However, you must take caution, as the command irreversibly deletes all user files. For service accounts (e.g., mysql), use --remove-all-files to delete configuration files: sudo deluser --remove-all-files mysql Advanced Cleanup with userdel On non-Debian systems, use: sudo userdel -r john_doe The above command deletes user and home directory. To detect orphaned files, use: sudo find / -uid 1002 Replace 1002 with the user’s UID. Best Practices for System Integrity Here are some best practices to keep in mind when deleting files: Regular Audits: Use last example_user to review login history. Group Hygiene: Remove obsolete groups with groupdel. Backup Strategies: Archive home directories before deletion. Conclusion Mastering Ubuntu user administration involves strategic use of adduser, usermod, and deluser alongside proactive security measures. By implementing these techniques, you’ll optimize resource allocation, enforce access controls, and maintain a robust system architecture.
13 February 2025 · 6 min to read
Ubuntu

How to Add a New Sudo User in Ubuntu

The acronym sudo stands for "substitute user and do." The sudo program allows regular users in the system to perform tasks that would typically require the superuser (root), who has full privileges and access rights. This approach enables system management under a user with limited privileges, reducing the risk of errors or unauthorized access to critical system functions. Thus, you can create a separate user with access to the sudo utility but without access to many system functions, the misuse of which could harm the system. The key difference between sudo and su (substitute user) is that sudo switches users temporarily, without asking for the user's password. In this guide, we'll go over how to create a new user in Ubuntu 22.04 and add them to the sudo group, thus providing extended privileges for system management. Creating a New User for Sudo Before creating a new user with special privileges, you need to log into the system as the superuser. If you're using a server running Ubuntu, connect to it via SSH as the root user: ssh root@IP_ADDRESS For example, the connection command might look like this: ssh [email protected] After that, the terminal will prompt you to enter the root password.  For security reasons, the terminal won't display the password characters as you type them. Next, create a new user by assigning them a chosen name: adduser hostman The terminal will show a few messages indicating the creation of the new user, a new group to which they are automatically added, and a directory associated with the user: Adding user `hostman' ... Adding new group `hostman' (1001) ... Adding new user `hostman' (1000) with group `hostman' ... Creating home directory `/home/hostman' ... Copying files from `/etc/skel' ... Next, the terminal will ask you to set a password for the new user and provide additional information about them: Changing the user information for hostman Enter the new value, or press ENTER for the default Full Name []: Room Number []: Work Phone []: Home Phone []: Other []: Is the information correct? [Y/n] After filling out the information, press y to confirm. You have created a new user. Adding a User to the Sudo Group Now, you need to add the new user to the special sudo group, which will grant them extended privileges: usermod -aG sudo hostman The -a flag is necessary to ensure that the specified group does not replace other groups the user is already a part of. In this case, the user hostman is at least part of the previously created hostman group. The -G flag is used to specify additional groups we want to add the user to. It is different from the -g flag, which sets the user's primary group. In this case, the primary group for the user hostman is the hostman group. Now, you can switch to the new user: su - hostman Immediately after switching, the terminal will display a message stating that commands can now be executed as the administrator (root) using sudo: To run a command as administrator (user "root"), use "sudo <command>".See "man sudo_root" for details. By the way, you can always check which user is currently executing commands: whoami The terminal will display the active user's name: hostman Running Commands with Sudo Sudo As root To test the new user's privileges, try listing the contents of the system directory /root: sudo ls -la /root The -la flag is a combination of two flags: -l specifies a detailed (long) format for listing the contents of the filesystem. -a includes directories whose names start with a dot. Thus, the ls command will show all the contents of the /root directory in detail. When running this command for the first time, the terminal will ask for the password set for the user hostman: [sudo] password for hostman: After entering the password, you will see the contents of the /root directory: total 48 drwx------ 7 root root 4096 Nov 20 05:30 . drwxr-xr-x 20 root root 4096 Nov 20 12:09 .. drwx------ 3 root root 4096 Nov 11 12:17 .ansible -rw-r--r-- 1 root root 4078 Nov 20 10:12 .bash_history -rw-r--r-- 1 root root 3106 Oct 15 2021 .bashrc drwx------ 2 root root 4096 Nov 11 12:17 .cache drwxr-xr-x 3 root root 4096 Nov 19 05:36 .local -rw------- 1 root root 214 Nov 18 04:26 .mysql_history -rw-r--r-- 1 root root 161 Jul 9 2019 .profile -rw-r--r-- 1 root root 1372 Nov 18 04:16 resize.log drwx------ 3 root root 4096 Nov 11 12:17 snap drwx------ 2 root root 4096 Nov 18 04:16 .ssh Note that using sudo does not require wrapping the command in quotes or anything else. The target command is written naturally right after sudo. If you enter the above command without using sudo: ls -la /root You will see an access denied message: ls: cannot open directory '/root': Permission denied Another basic command that is run with sudo is updating the list of available repositories: sudo apt update Similarly, if you try to update repositories without sudo, you'll get an access restriction message: Reading package lists... Done E: Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied) E: Unable to lock directory /var/lib/apt/lists/ W: Problem unlinking the file /var/cache/apt/pkgcache.bin - RemoveCaches (13: Permission denied) W: Problem unlinking the file /var/cache/apt/srcpkgcache.bin - RemoveCaches (13: Permission denied) Thus, any attempt to use a command requiring administrator privileges will result in an access denied message in the terminal. Sudo As Another User With sudo, you can execute commands not only as root but also as any other user. First, let's switch back to the root user: su - root The terminal will prompt for the root user's password. Now, let's try executing a command that requires administrative privileges as the user hostman, using the -u flag: sudo -u hostman ls -la /root The terminal will display the familiar access denied message: ls: cannot open directory '/root': Permission denied Next, let's switch back to the hostman user: su - hostman For clarity, we can perform the same action under the hostman user: sudo -u root ls -la /root First, the terminal asks for the hostman user's password and then displays the contents of the specified directory: total 52 drwx------ 7 root root 4096 Nov 20 15:39 . drwxr-xr-x 20 root root 4096 Nov 20 12:09 .. drwx------ 3 root root 4096 Nov 11 12:17 .ansible -rw-r--r-- 1 root root 4171 Nov 20 15:21 .bash_history -rw-r--r-- 1 root root 3106 Oct 15 2021 .bashrc drwx------ 2 root root 4096 Nov 11 12:17 .cache drwxr-xr-x 3 root root 4096 Nov 19 05:36 .local -rw------- 1 root root 214 Nov 18 04:26 .mysql_history -rw-r--r-- 1 root root 161 Jul 9 2019 .profile -rw-r--r-- 1 root root 1372 Nov 18 04:16 resize.log drwx------ 3 root root 4096 Nov 11 12:17 snap drwx------ 2 root root 4096 Nov 18 04:16 .ssh -rw-r--r-- 1 root root 0 Nov 20 15:39 .sudo_as_admin_successful Configuring Sudo Access Permissions You can restrict the permissions of a particular user in the sudo group to only executing specific allowed commands. To check this, let's first switch back to the root user: su - root Setting Access Permissions To configure unique access permissions for each sudo user, we need to open the /etc/sudoers file: sudo nano /etc/sudoers Then, we can add the description of allowed commands using the following format: USER HOST=(AVATAR:GROUP) COMMANDS Where: USER: The user that will initiate the sudo command. HOST: The hostname where the sudo command will be executed. This is relevant when using multiple machines. AVATAR: The user under whose name the allowed commands will be executed via sudo. GROUP: The group the user belongs to. COMMANDS: The set of commands (which may consist of just one command) that the user can execute via sudo. In the simplest case, you can allow to execute all commands under any user: hostman ALL=(ALL:ALL) ALL In a more complex case, only specific commands can be allowed from a limited set of users: hostman ALL=(root:ALL) /usr/bin/apt,/usr/bin/rm,/bin/nano Note that command sets are listed comma-separated without spaces. To find the full paths to the binaries of necessary commands, you can use the whereis utility: whereis apt rm nano The terminal will display information about the specified commands: apt: /usr/bin/apt /usr/lib/apt /etc/apt /usr/share/man/man8/apt.8.gz rm: /usr/bin/rm /usr/share/man/man1/rm.1.gz nano: /usr/bin/nano /usr/share/nano /usr/share/man/man1/nano.1.gz /usr/share/info/nano.info.gz The first path listed after the command name is the actual address of the binary file. To activate the specified restrictions, you need to replace the line that allows sudo group users to execute any root commands: %sudo ALL=(ALL:ALL) ALL With a similar one but with a comment symbol at the beginning, to disable the setting: #%sudo ALL=(ALL:ALL) ALL Now you can switch back to the hostman user: su - hostman And let's try running the familiar command to list the contents of the /root directory: sudo ls -la /root The terminal will display a message indicating that the specified command is prohibited on this host: Sorry, user hostman is not allowed to execute '/usr/bin/ls /root' as root on <hostname>. However, the command to update repositories will still work: sudo apt update Checking Access Rights Of course, you can find out the details of a user's privileges by simply viewing the contents of the /etc/sudoers file. However, there's an easier way, by using the sudo command itself: sudo -l -U hostman The -l flag lists all commands the user is allowed to use. The -U flag specifies the target username. If omitted, the terminal will display access rights for the root user. In the terminal, you will see a message detailing the access rights for the specified user: Matching Defaults entries for hostman on <hostname>: env_reset, mail_badpass, secure_path=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin, use_pty User hostman may run the following commands on <hostname>: (root : ALL) /usr/bin/apt, /usr/bin/rm, /bin/nano The key part of the output is: User hostman may run the following commands on <hostname>: (root : ALL) /usr/bin/apt, /usr/bin/rm, /bin/nano This indicates that the user hostman can run the following commands as root: /usr/bin/apt /usr/bin/rm /bin/nano These are exactly the commands specified in the /etc/sudoers configuration file. This way, you can quickly review the privileges of a specific user without the need to search through the /etc/sudoers file manually. Additionally, you can simplify the process of obtaining user privilege information by checking the permission for executing a specific command: sudo -l -U hostman ls If the command is not allowed, there will be no output in the terminal. However, if it is allowed: sudo -l -U hostman apt The terminal will display the full path to the command's binary: /usr/bin/apt This way, you can check whether the current user can execute a specific command when unsure about their access rights. Disabling Password Prompt The sudo utility allows running commands without explicitly entering a password. However, disabling the password prompt is not considered secure, so perform this configuration at your own risk. To disable the password prompt, you need to open the /etc/sudoers file: sudo nano /etc/sudoers Then, add a new line containing the NOPASSWD keyword and a list of commands for which the password is not required: hostman ALL=(root:ALL) NOPASSWD: /usr/bin/apt You should also separate commands that require a password from those that don't. For example, the allowed commands with a password prompt should be listed separately from the ones without: hostman ALL=(root:ALL) /usr/bin/rm,/bin/nanohostman ALL=(root:ALL) NOPASSWD: /usr/bin/apt This way, you'll have two sections for allowed commands: one requiring a password and one that doesn't. Conclusion Although the sudo command resembles the su command, there is a key difference between them: su stands for "substitute user". sudo stands for "substitute user and do". Thus, su performs a full user switch, requiring an explicit password input, while sudo only simulates executing a command as another user, without switching the user entirely. For this reason, sudo is much safer when granting extended privileges to another user. The user won't need the root password, as they can execute administrator commands under their own user account. Additionally, unique permissions (access rights) for each individual user in the sudo group can be configured in a special configuration file. In this file, you can also specify whether a password is necessary to run certain commands.
12 February 2025 · 10 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support