Sign In
Sign In

How to Add a New Sudo User in Ubuntu

How to Add a New Sudo User in Ubuntu
Hostman Team
Technical writer
Ubuntu
12.02.2025
Reading time: 10 min

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 root@166.1.227.189

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/nano
hostman 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.

And if you’re looking for a reliable, high-performance, and budget-friendly solution for your workflows, Hostman has you covered with Linux VPS Hosting options, including Debian VPS, Ubuntu VPS, and VPS CentOS.

Ubuntu
12.02.2025
Reading time: 10 min

Similar

Ubuntu

Installing and Configuring cloud-init on Ubuntu

cloud-init is the de facto industry standard for automated initialization of virtual machines in cloud environments. This powerful configuration tool is activated at the first boot of an instance and allows execution of a predefined set of tasks without manual intervention. Its key functions include: Automating basic system setup, including assigning a hostname. User account management: creating users, assigning permissions, and configuring authentication mechanisms. Automatic deployment of SSH keys for secure access. Configuration of network interfaces according to specified parameters. Operations with disk storage, such as mounting and formatting volumes. Execution of custom scripts for post-installation configuration, which may include installing software, deploying application code, and applying fine-tuned settings. Although cloud-init is primarily designed for public clouds (AWS, Google Cloud, Azure, Hostman), it can also be used on local virtual machines and even on physical servers to standardize their initial setup. And if you’re looking for a reliable, high-performance, and budget-friendly solution for your workflows, Hostman has you covered with Linux VPS Hosting options, including Debian VPS, Ubuntu VPS, and VPS CentOS. In this article, we will look at how to install, configure, and use cloud-init on Ubuntu. Installation In most Ubuntu images, cloud-init is already preinstalled. Canonical (the developer of Ubuntu) also releases images called Ubuntu Cloud Images, specially prepared and optimized for running in cloud environments. In Hostman, all Ubuntu images already include cloud-init. You can additionally check for cloud-init with the command: cloud-init --version If the command outputs a version (as shown in the screenshot above), then cloud-init is already installed in the system. If the response is Command cloud-init not found, install the utility with: apt update && apt -y install cloud-init After installation, cloud-init will automatically run at every system boot. Note that cloud-init runs before the server connects to the network. Configuration File Structure All cloud-init configuration files are located in /etc/cloud/: /etc/cloud/clean.d/ — directory for cleanup scripts. These scripts are executed when the command cloud-init clean is run. /etc/cloud/cloud.cfg — the main configuration file. This sets the default settings for all initialization stages. /etc/cloud/cloud.cfg.d/ — directory for user configuration files with the .cfg extension. Files are processed in alphabetical order and override settings from the main file. This is the preferred location for custom configurations. /etc/cloud/templates/ — contains templates used by cloud-init to generate system files. /var/lib/cloud/ — stores cache, data, and scripts generated during cloud-init execution. Modules Modules in cloud-init are separate executable components that perform specific configuration tasks when a VM first boots. Each module is responsible for its own area: network configuration, user creation, package installation, etc. An important feature of modules is their execution order: they do not run randomly, but in a strict sequence consisting of stages: Init Stage (Initialization stage): Runs immediately after mounting the root filesystem. Modules needed to prepare the system for main configuration are executed here (e.g., mounting additional disks). Config Stage (Configuration stage): The main stage where most modules run: network setup, package installation, SSH key setup, user creation. Final Stage: Executes modules for tasks that should occur at the very end, such as sending system readiness notifications or running user scripts. Local Usage of cloud-init Let’s test cloud-init locally, i.e., run it after the server has already booted. We will create two scenarios: The first scenario will create a new user named new-admin, assign a password, and grant administrator rights. The second scenario will install the packages atop, tree, net-tools. Since we will use a password for the new user, we need to generate its hash, as all passwords (and other secrets) are specified in plain text by default. . To get a hash, install the whois package, which contains the mkpasswd utility: apt -y install whois Run the utility with the SHA-512 hashing algorithm: mkpasswd -m sha-512 --stdin Enter the password for the user and press Enter. The utility will generate a password hash. Copy this hash for later use. As noted earlier, user configuration files are stored in /etc/cloud/cloud.cfg.d. Create a new file 99-new-admin-config.cfg:nano /etc/cloud/cloud.cfg.d/99-new-admin-config.cfg Use the following content: #cloud-config users: - name: new-admin passwd: $6$BSAzGG4SFvsn//vD$ds8oM53OIs6qXiCIhMTl10bwQfe9u5WxGKADzwyPsODniGhYAXCUOAoyUkJLs.H9z0PxqLr7BxEJ18hT2VEyR/ sudo: ALL=(ALL) ALL shell: /bin/bash groups: sudo Check syntax for errors: cloud-init schema --config-file /etc/cloud/cloud.cfg.d/99-new-admin-config.cfg If there are no errors, the command will return Valid schema. Before running the script, clear the previous configuration: cloud-init clean Run the configuration:cloud-init single --name users-groups --file /etc/cloud/cloud.cfg.d/99-new-admin-config.cfg After the new configuration is applied, check for the new-admin user: id new-admin Next, install the packages. Create a new file: nano /etc/cloud/cloud.cfg.d/99-install-packages.cfg Use the following content: #cloud-config package_update: true package_upgrade: true packages: - atop - tree - net-tools Check syntax: cloud-init schema --config-file /etc/cloud/cloud.cfg.d/99-install-packages.cfg Clear configuration:  cloud-init clean Run the script to install the packages: cloud-init single --name package_update_upgrade_install --file /etc/cloud/cloud.cfg.d/99-install-packages.cfg Verify the installed packages: dpkg -l | grep -E "atop|tree|net-tools" Using cloud-init in Hostman Hostman cloud servers running Linux support cloud-init via the control panel. Scenarios can be configured both during server ordering and later during usage. Let’s look at the practical use of cloud-init. We will create a scenario that will: Create a new user named new-usr; Configure SSH key authentication for new-usr; Install two packages: mc, ncdu; Change the hostname to hostman-server; Create a file test-file.txt in the /tmp directory. If cloud-init scripts have already been run on the server, run cloud-init clean before applying the configuration below. Our script will run when creating a virtual server; we can add it at step 7: Since SSH key authentication will be used for the new user, generate keys in advance. On another device (Windows, macOS, Linux), run the command: ssh-keygen Save the keys in the default directory (.ssh in the home directory). Then obtain the public key value (.pub file): cat ~/.ssh/id_ed25519.pub Replace id_ed25519.pub with your own filename if different. In the control panel, in the cloud-init block, enter the following syntax: #cloud-config packages: - mc - ncdu users: - name: "new-usr" groups: sudo shell: /bin/bash sudo: ['ALL=(ALL) NOPASSWD:ALL'] ssh_authorized_keys: - ssh-rsa AAAAC3NzaC1lZDI1NTE5AAAAIFoUTI5BKDBDgKLIMpM71m/YI7dTtFKQiSIivRk9pUbs alex@DESKTOP-VTUJHJ9 lock_passwd: true hostname: hostman-server preserve_hostname: false runcmd: - [touch, /tmp/test-file.txt] In the ssh_authorized_keys field, enter your own public key. Complete the server order by clicking “Order.” Once the server is created, connect via SSH with the new user and verify that all specified actions were completed. Verify the user: id new-usr Verify installed packages: dpkg -l | grep -E "mc|ncdu" Verify hostname: hostname Verify file existence: ls -lah /tmp/test-file.txt Conclusion cloud-init is a powerful tool for automating the initial setup of servers in Ubuntu. With its capabilities, you can deploy fully configured servers in seconds, minimize human error, and easily scale infrastructure. The main strength of cloud-init lies in its ability to transform a virtual machine template into a fully configured, production-ready server instance without manual intervention. Automating network configuration, security updates, user creation, and software deployment are the advantages that make it indispensable for DevOps engineers and system administrators.
04 September 2025 · 7 min to read
Java

Switching between Java Versions on Ubuntu

Managing multiple Java versions on Ubuntu is essential for developers working on diverse projects. Different applications often require different versions of the Java Development Kit (JDK) or Java Runtime Environment (JRE), making it crucial to switch between these versions efficiently. Ubuntu provides powerful tools to handle this, and one of the most effective methods is using the update-java-alternatives command. Switching Between Java Versions In this article, the process of switching between Java versions using updata-java-alternatives will be shown. This specialized tool simplifies the management of Java environments by updating all associated commands (such as java, javac, javaws, etc.) in one go.  And if you’re looking for a reliable, high-performance, and budget-friendly solution for your workflows, Hostman has you covered with Linux VPS Hosting options, including Debian VPS, Ubuntu VPS, and VPS CentOS. Overview of Java version management A crucial component of development is Java version control, especially when working on many projects with different Java Runtime Environment (JRE) or Java Development Kit (JDK) needs. In order to prevent compatibility problems and ensure efficient development workflows, proper management ensures that the right Java version is utilized for every project. Importance of using specific Java versions You must check that the Java version to be used is compatible with the application, program, or software running on the system. Using the appropriate Java version ensures that the product runs smoothly and without any compatibility issues. Newer versions of Java usually come with updates and security fixes, which helps protect the system from vulnerabilities. Using an out-of-date Java version may expose the system to security vulnerabilities. Performance enhancements and optimizations are introduced with every Java version. For maximum performance, use a Java version that is specific to the application. Checking the current Java version It is important to know which versions are installed on the system before switching to other Java versions.  To check the current Java version, the java-common package has to be installed. This package contains common tools for the Java runtimes including the update-java-alternatives method. This method allows you to list the installed Java versions and facilitates switching between them. Use the following command to install the java-common package: sudo apt-get install java-common Upon completing the installation, verify all installed Java versions on the system using the command provided below: sudo update-java-alternatives --list The report above shows that Java versions 8 and 11 are installed on the system. Use the command below to determine which version is being used at the moment. java -version The displayed output indicates that the currently active version is Java version 11. Installing multiple Java versions Technically speaking, as long as there is sufficient disk space and the package repositories support it, the administrator of Ubuntu is free to install as many Java versions as they choose. Follow the instructions below for installing multiple Java versions. Begin by updating the system using the following command:   sudo apt-get update -y && sudo apt-get upgrade -y To add another version of Java, run the command below. sudo apt-get install <java version package name> In this example, installing Java version 17 can be done by running:  sudo apt-get install openjdk-17-jdk openjdk-17-jre Upon completing the installation, use the following command to confirm the correct and successful installation of the Java version: sudo update-java-alternatives --list Switching and setting the default Java version To switch between Java versions and set a default version on Ubuntu Linux, you can use the update-java-alternatives command.  sudo update-java-alternatives --set <java_version> In this case, the Java version 17 will be set as default: sudo update-java-alternatives --set java-1.17.0-openjdk-amd64 To check if Java version 17 is the default version, run the command:  java -version The output shows that the default version of Java is version 17. Managing and Switching Java Versions in Ubuntu Conclusion In conclusion, managing multiple Java versions on Ubuntu Linux using update-java-alternatives is a simple yet effective process. By following the steps outlined in this article, users can seamlessly switch between different Java environments, ensuring compatibility with various projects and taking advantage of the latest features and optimizations offered by different Java versions. Because Java version management is flexible, developers may design reliable and effective Java apps without sacrificing system performance or stability.
22 August 2025 · 4 min to read
Ubuntu

How to Install and Configure SSH on Ubuntu 22.04

A secure connection between a client and a server is made possible via the SSH network protocol. Since all communications are encrypted, distant network attacks and data theft across the network are avoided. Let’s say you have ordered a cloud server from Hostman. You will need SSH installed and configured to connect to and administer the server. The guide below will describe how to install SSH on Ubuntu 22.04 and configure it. SSH Key configuration is pretty simple on Ubuntu Prerequisites Before proceeding with the installation and configuration of the Secure Shell service, ensure the following requirements are met: Linux Command Line Skills for Configuration Having a solid grasp of basic Linux commands like sudo, apt, nano, and systemctl is essential when setting up the service. These commands will be frequently used during the installation and configuration process. It's crucial to be comfortable working within the command line environment to manage the service effectively. Root or Sudo Access for Setup To install and configure the server, administrative (root) privileges are required. Users must either have sudo access or be logged in as root. Without these privileges, the setup process cannot proceed. Internet Connection for Package Download A stable internet connection is necessary to install the OpenSSH server and any additional related packages. Without a functional connection, the system cannot retrieve the required software components. Configuring Firewall for Access If a firewall, like ufw, is enabled on the system, it may block remote access by default. It is essential to configure your firewall to allow incoming connections. Use ufw or another firewall tool to ensure port 22 is open and accessible. Access to the System (Local or Remote) To configure the service locally, you must have physical access to your computer; otherwise, it must be remotely accessible through its IP address. To connect, make sure the system is correctly linked to the network. Don't forget, that you can deploy your cloud server fast and cheap by choosing our VPS Server Hosting. Step 1: Prepare Ubuntu The first thing you need to do before you start installing SSH on Ubuntu is to update all apt packages to the latest versions. To do this, use the following command: sudo apt update && sudo apt upgrade Step 2: Install SSH on Ubuntu OpenSSH is not pre-installed on the system, so let's install it manually. To do this, type in the terminal: sudo apt install openssh-server The installation of all the necessary components will begin. Answer "Yes" to all the system prompts.  After the installation is complete, go to the next step to start the service. Step 3: Start SSH Now you need to enable the service you just installed using the command below: sudo systemctl enable --now ssh On successful startup, you will see the following system message. The --now key helps you launch the service and simultaneously set it to start when the system boots. To verify that the service is enabled and running successfully, type: sudo systemctl status ssh The output should contain the Active: active (running) line, which indicates that the service is successfully running. If you want to disable the service, execute:  sudo systemctl disable ssh It disables the service and prevents it from starting at boot. Step 4: Configure the firewall Before connecting to the server via SSH, check the firewall to ensure it is configured correctly. In our case, we have the UFW installed, so we will use the following command: sudo ufw status In the output, you should see that SSH traffic is allowed. If you don't have it listed, you need to allow incoming SSH connections. This command will help with this: sudo ufw allow ssh Step 5: Connect to the server Once you complete all the previous steps, you can log into the server using the SSH protocol. You will need the IP address or domain name of the server as well as the name of a user that was created on the server in order to complete this step. In the terminal line, enter the command: ssh username@IP_address Or:  ssh username@domain Important: To successfully connect to a remote server, SSH must be installed and configured on the remote server and the user's computer from which you make the connection.  - Step 6 (optional): Create Key Pair for Secure Authentication For enhanced security, consider configuring a key pair instead of relying on password authentication. To generate one, use the following command: ssh-keygen Step 7: Configure SSH Having completed the previous five steps, you can already connect to the server remotely. However, you can further increase the connection's security by changing the default connection port to another or changing the password authentication to key authentication. These and other changes require editing the SSH configuration file. The main OpenSSH server settings are stored in the main configuration file sshd_config (location: /etc/ssh). Before you start editing, you should create a backup of this file:  sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.initial If you get any errors after editing the configuration file, you can restore the original file without problems. After creating the backup, you can proceed to edit the configuration file. To do this, open it using the nano editor: sudo nano /etc/ssh/sshd_config In the file, change the port to a more secure one. It is best to set values from the dynamic range of ports (49152 - 65535) and use different numbers for additional security. For example, let's change the port value to 49532. To do this, we uncomment the corresponding line in the file and change the port as shown in the screenshot below. SSH Key Configuration Description in Linux Terminal In addition to this setting, we recommend changing the password authentication mode to a more secure key authentication mode. To do this, uncomment the corresponding line and make sure the value is "Yes", as shown in the screenshot. Authentication Key should be Enabled Now, let's prohibit logging on to the server as a superuser by changing the corresponding line as shown in the picture below. Don't Forget to Close Access to Root Login There are other settings you can configure to increase the server security:  UseDNS checks if the hostname matches its IP address. The value "Yes" enables this parameter. PermitEmptyPasswords prohibits using empty passwords for authentication if the value is "No." MaxAuthTries limits the number of unsuccessful attempts to connect to the server within one communication session.  AllowUsers and AllowGroups are responsible for the list of users and groups allowed to access the server: # AllowUsers User1, User2, User3# AllowGroups Group1, Group2, Group3 Login GraceTime sets the time provided for successful authorization. We recommend reducing the value of this parameter by four times. ClientAliveInterval limits the time of user inactivity. After exceeding the specified limit, the user is disconnected. After making all the changes in the main configuration file, save them and close the editor.  Restart the service to make the changes take effect: sudo systemctl restart ssh If you have changed the port in the configuration file, you should connect using the new port:  ssh -p port_number username@IP_address Or: ssh -p port_number_port_username@domain Troubleshooting Connection Issues Ensure the service is running with: sudo systemctl status ssh Restart it if necessary: sudo systemctl restart ssh Check firewall settings to allow traffic on port 22: sudo ufw allow 22 Confirm the system is reachable by running: ping <server-ip-address> Disabling the Service If you need to disable remote access for any reason, follow these steps: Stop the Service To temporarily stop accepting connections: sudo systemctl stop ssh Prevent Automatic Startup To disable it from starting on reboot: sudo systemctl disable ssh Confirm Inactive Status Verify that the service is no longer running: sudo systemctl status ssh Uninstall the Server If the service is no longer needed, remove it and its associated configuration files: sudo apt remove openssh-server Conclusion This article presents a step-by-step guide on installing and configuring SSH in Ubuntu 22.04 and describes how to edit the main configuration file to improve security. We hope this guide helps you to set up a secure remote connection to your Ubuntu server. And if you’re looking for a reliable, high-performance, and budget-friendly solution for your workflows, Hostman has you covered with Linux VPS Hosting options, including Debian VPS, Ubuntu VPS, and VPS CentOS.To see more about SSH keys click here.
21 August 2025 · 7 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