Skip to main content

How to Configure and Enable SSH in Ubuntu

Published on:
.
19 min read
.
For German Version

SSH (Secure Shell) is a cryptographic network protocol developed to provide secure remote management and data transmission. SSH ensures secure operations such as encrypted login sessions, command execution, file transfers (SCP, SFTP), and tunneling over unsecured networks. On Linux servers in particular, properly installing and configuring the SSH service is considered one of the fundamental security measures for system administrators.

The Ubuntu operating system includes OpenSSH, which supports the SSH protocol, in its official repositories. This allows users to configure both the client and server sides quickly and securely. SSH enables the use of asymmetric key-based authentication methods instead of passwords, forming the foundation of multi-factor security systems. Moreover, features like logging, access control settings, and connection restrictions offer system administrators detailed oversight and monitoring capabilities.

In this guide, we will technically cover how to install and enable the SSH service on Ubuntu 22.04 or later versions, including configuration steps, security enhancements, and troubleshooting techniques.

Requirements

To implement this SSH configuration guide, you must meet the following requirements.

  • Ubuntu 22.04 LTS or a newer version: This version includes up-to-date and secure versions of OpenSSH packages. It is compatible with systemd-based service management (systemctl).
  • sudo or root user privileges: System-level permissions are required for installing, configuring, and managing the SSH service. The sudo command allows temporary execution with administrative privileges.
  • Active internet connection: An internet connection is necessary to download required packages (e.g., openssh-server, fail2ban, etc.) via the package manager (APT) and to keep the system updated.
Get Started with Zenarmor Today For Free

1. Install SSH Server

Installing the SSH server is the first step to enabling remote system administration. On Ubuntu, this functionality is provided by the openssh-server package. You mya install SSH server on Ubuntu by running the following command.

sudo apt update && sudo apt install openssh-server –y

This command updates the system package lists and installs the SSH server, preparing it to accept incoming connections.

tip

The -y flag automatically answers “yes” to any prompts during installation. It is useful for automation or quick deployments.

warning

After installation, the SSH service starts automatically. However, your firewall may not yet allow SSH connections. Running with default configurations could pose a security risk. Therefore, it is important to proceed with proper configuration and access control steps.

2. Start and Enable SSH Service

Starting the SSH service makes it immediately available for use. Additionally, enabling the service ensures that it will automatically start on system boot. You may start and enable the SSH service by running the next command.

sudo systemctl start ssh
sudo systemctl enable ssh

The first command starts the service immediately. The second command ensures that the service starts automatically every time the system reboots.

tip

The SSH service usually starts automatically after installation. However, on customized or minimal installations, this step might need to be performed manually.

note

The systemctl command is part of Ubuntu's systemd-based service control system and is the primary tool for managing services.

warning

Once the SSH service is started, the system becomes accessible from external networks. Therefore, it’s important to configure access controls and firewall rules before or immediately after starting the service.

3. Verify SSH Installation

Verifying that the SSH service is running correctly is a critical step in confirming a successful installation. This check is useful after a system reboot or configuration changes to ensure the service is still active. You may view the SSH service status by running the following command.

sudo systemctl status ssh

This command displays the current operational status of the SSH service. If the output includes "active (running)", the service is functioning correctly. If the SSH service is not running, you can start it by running the next command.

sudo systemctl start ssh

You can inspect detailed logs using the following command.

journalctl -u ssh
tip

If you encounter messages like "inactive" or "failed", double-check the configuration file for syntax errors or verify that there is no port conflict.

4. Configure SSH (Optional)

After installing the SSH service, key security and access control settings can be configured through the SSH configuration file, /etc/ssh/sshd_config. This step is recommended for creating a custom access policy tailored to your system’s needs.

sudo nano /etc/ssh/sshd_config

This command opens the main configuration file of the SSH daemon using the nano text editor.

tip

For any changes made in /etc/ssh/sshd_config file to take effect, the SSH service must always be restarted. Otherwise, the new settings will not be applied. Common security-related directives in the SSH server configuration file are given below.

  • Port 2222: Use a less common port, such as 2222 instead of the default 22.
  • PermitRootLogin no: Disable direct login for the root user
  • PasswordAuthentication no: Enforce key-based login to prevent password attacks
  • AllowUsers user1 user2: Restrict SSH access to specific users, such as user1 and user2.

To apply your changes, restart the SSH service by running the next command.

sudo systemctl restart ssh

Restarting the service ensures that your configuration updates are loaded into memory.

tip

It is strongly recommended to back up the configuration file before making any changes by running the next command.

sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup
warning

If you change the SSH port without updating your firewall rules, you may lock yourself out of the system. When making remote changes, keep a second terminal session open to avoid accidental disconnection.

5. Adjust Firewall Settings (If Applicable)

Once the SSH service is correctly installed and configured, it’s essential to ensure that your firewall (e.g., UFW) allows inbound connections to the SSH port. Otherwise, incoming connection attempts from outside the network will be blocked.

sudo ufw allow ssh

This command opens TCP port 22 on UFW (Uncomplicated Firewall), which is the default port for SSH. If you’ve changed the port in the SSH configuration file, you must modify this command accordingly.If you’ve configured a different port in /etc/ssh/sshd_config, make sure your UFW rule reflects that. For example, if you set your SSH port to 2222, use the following command to allow SSH access.

sudo ufw allow 2222/tcp

It’s recommended to explicitly specify the protocol (TCP/UDP) when allowing custom ports.

tip

To check which services and ports are currently allowed through the firewall, run the next command.

sudo ufw status verbose

6. Test SSH Connection from Another Machine

After completing the SSH setup, it is essential to verify that the configuration works correctly by testing the connection from a remote machine. This test confirms that the port, username, and firewall settings have been properly configured.

ssh username@server_ip_address

Replace username and server_ip_address with values appropriate for your system.

note

If you're connecting for the first time, the SSH server’s authentication key is not yet registered on the client. You will see a prompt like given below.

“Are you sure you want to continue connecting?”

Type yes to proceed.

If you're using a custom port (e.g., 2222) for SSH service, connect the SSH server using -p parameter. The -p flag is required when connecting on a non-default SSH port.

ssh -p 2222 username@server_ip_address
tip

After a successful login, you can use the who or w commands to confirm the session is active. Additionally, try hostname or uptime on the remote server to check its identity and system status.

warning

If the connection fails, possible causes include the SSH service not running, the firewall blocking the port, an incorrect IP address, or misconfigurations in the sshd_config file.

What is the Importance of SSH in Ubuntu?

SSH (Secure Shell) is a foundational protocol for secure remote management on Ubuntu and other Linux-based operating systems. It plays a critical role in securing operations performed over networks. Since SSH transmits encrypted data instead of plain text, it allows system administrators to safely access systems even over public or potentially untrusted networks.

Due to Ubuntu’s widespread use in server environments, SSH has become an integral component of the system. It works seamlessly with tools like OpenSSH, offering a robust security infrastructure by default.

Key advantages of using SSH are as follows.

  • Secure Remote Terminal Access: System administrators can securely perform all operations via the terminal without physical access to the machine. It's as simple as connecting with ssh user@server.
  • Encrypted File Transfers: Files can be securely transferred using SCP (Secure Copy) and SFTP (SSH File Transfer Protocol), with end-to-end encryption.
  • Automation and Script-Based Management: SSH accelerates maintenance tasks by enabling remote script execution in automation workflows. Tools like Ansible, Fabric, and rsync are all built on top of SSH.
  • Port Forwarding and Tunneling: SSH enables the creation of secure tunnels by forwarding remote services to local ports. This protects sensitive data while it travels across the internet.
  • Key-Based Authentication: SSH supports authentication via RSA or ECDSA key pairs instead of passwords. This not only strengthens security but also simplifies identity management.

Why Is SSH Critical?

SSH service is vital due to the following reasons.

  • Confidentiality: All data transmissions are encrypted; usernames, passwords, and content cannot be intercepted in plaintext.
  • Integrity: Data arrives exactly as it was sent, without tampering during transmission.
  • Authorization: Through its authentication mechanisms, SSH ensures that only authorized users can access the system.

How to Install OpenSSH Client on Ubuntu 22.04?

The OpenSSH client (openssh-client) includes the command-line tools required to securely connect to another system using the SSH protocol. On Ubuntu desktop editions, this client is typically installed by default. However, in minimal or server installations, it may need to be installed manually. You may update the package list and install the OpenSSH client by running the next command..

sudo apt update && sudo apt install openssh-client –y

The first command updates the local package index. The second installs the OpenSSH client.

To verify the SSH client installation, check the SSH client version by running the next command.

ssh –V

If the output returns a version like OpenSSH_8.x, the client is installed successfully.

note

The openssh-client package includes tools like ssh, scp, and sftp, which are used for remote access, file copying, and file transfers.

warning

A system with only the SSH client installed can initiate connections to other SSH servers but cannot accept incoming connections. If you need the system to act as an SSH server, you must install the openssh-server package.

How to Generate SSH Keys for Passwordless Login?

SSH key-based authentication provides a more secure and automation-friendly alternative to password-based login. It is especially critical for servers requiring persistent access or for use in automated systems. This method involves generating a private/public key pair. The public key is copied to the server, and during the connection, the client authenticates itself using the private key only.

  1. Generate SSH Key Pair: The following command creates .ssh/id_rsa (private key) and .ssh/id_rsa.pub (public key) files.

    ssh-keygen -t rsa -b 4096

    A 4096-bit RSA key is strong and widely supported. When you run the command, it will prompt you for a file name, passphrase, and other options.

    tip

    If you choose to set a passphrase during key generation, you'll be asked to enter it whenever the key is used, this adds an extra layer of security. For automation scenarios, you may leave it blank.

  2. Copy Public Key to the Remote Server: Use the following command to append your public key to the target user's ~/.ssh/authorized_keys file on the server.

    ssh-copy-user id@server_ip

    This securely transfers the public key to the remote server and prepares it for passwordless login.

    note

    The ssh-copy-id command will ask for your password one last time on the remote host to complete the key installation. After this, passwords will no longer be required for SSH access.

  3. Test the Passwordless SSH Login: To test the passwordless SSH login configuration, you may run the following command.

    ssh user@remote_host

    If everything is set up correctly, the system will allow access without asking for a password.

    tip

    If SSH still prompts for a password, it likely means the key was not added to the correct user's account or the file permissions are incorrect. Ensure the ~/.ssh/authorized_keys file has chmod 600 and the ~/.ssh directory has chmod 700.

How to Configure SSH for Enhanced Security?

While the default SSH settings are functional for most systems, servers exposed to public networks require stricter security measures. This section outlines recommended configurations to secure the SSH service against unauthorized access.

To apply the following steps, open the SSH configuration file.

sudo nano /etc/ssh/sshd_config

This file is the main configuration for defining how the SSH daemon operates.

  1. Disable Password Authentication: Disabling password authentication when using key-based login increases overall security.

    PasswordAuthentication no
    warning

    Make sure key-based login is working properly before disabling password authentication, or you may lock yourself out of the system.

  2. Disable Root Login: Since the root account has full administrative privileges, direct SSH access to root should be disabled.

    PermitRootLogin no
    warning

    Ensure that at least one user account with sudo privileges exists before disabling root access.

  3. Limit SSH Access to Specific Users: To reduce the attack surface, you can restrict SSH access to specific users.

    AllowUsers adminuser backupuser

    In this example, only adminuser and backupuser will be allowed to log in via SSH.

  4. Change the Default SSH Port: Changing the default port (22) to a non-standard port can help reduce low-level scanning and automated attack attempts.

    Port 2222
    warning

    After changing the port, make sure to update your firewall rules (e.g., UFW or iptables) to allow the new port.

  5. Restart SSH Service: To apply any configuration changes, you must restart the SSH service.

    sudo systemctl restart ssh

    This step is necessary after every modification to the SSH configuration file.

These settings protect your SSH server against both automated attacks and targeted intrusion attempts, enhancing your network security.

How to Troubleshoot SSH Connection Issues?

When an SSH connection fails, it's important to follow a systematic approach to diagnose the root cause and resolve the issue quickly. This section explains common error scenarios and troubleshooting steps.

  1. Check SSH Service Status: First, verify whether the SSH service is running.

    sudo systemctl status ssh

    If the output does not show “active (running),” the service may be stopped or misconfigured.

    To start or restart the service, run the following command.

    sudo systemctl restart ssh
  2. Examine SSH Logs: To see detailed information about connection issues, review the SSH logs.

    journalctl -u ssh

    This command lists all log entries related to the SSH service. Connection attempts and error messages will appear here.

    tip

    To check logs for a specific time range, use the --since parameter.

    journalctl -u ssh --since "10 minutes ago"
  3. Check Firewall Rules: Your firewall (UFW, iptables) might be blocking access to the SSH port.

    sudo ufw status verbose

    Ensure that the allowed port (default is 22) appears in the list. If you’re using a custom port, like 2222, confirm that it’s permitted.

    warning

    If UFW rules are missing or incorrect, you could lose remote access. Always keep an active SSH session open when modifying firewall settings.

  4. Test Port Accessibility from Client: Check whether the SSH port on the remote system is accessible by running the following command.

    telnet server_ip 22

    or

    nc -zv server_ip 2222

    If the port is unreachable, there may be a routing or firewall appliance blocking the connection.

  5. Verify IP Address and Hostname: A wrong IP address or DNS resolution can cause connection failures. Re-verify the server’s IP.

    ip a
    hostname -I

    Ensure the server has the correct IP and that the address you’re trying to reach corresponds to the right machine.

  6. Check SSH Client Output for Errors: Use verbose mode during connection attempts to get detailed error messages by running the following command.

    ssh -v user@server_ip

    This output helps identify at which stage the connection fails (e.g., network, authentication, protocol).

These checks will uncover the majority of SSH issues. If the problem persists, review your sshd_config file for configuration errors or conflicting settings.

How to Disable SSH Root Login for Security?

The root account has the highest level of privileges on a system, which makes direct SSH access to root a significant security risk. Disabling this access helps reduce brute-force attacks and prevents unauthorized administrative access. To disable SSH root login, you mya follow the next steps.

  1. Open the SSH Configuration File: To edit the SSH configuration, open the sshd_config file with the following command.

    Sudo nano /etc/ssh/sshd_config

    This file controls how the SSH server behaves, including all access policies.

  2. Locate and Modify PermitRootLogin: Find the line containing PermitRootLogin and change its value as follows.

    PermitRootLogin no

    If the current value is yes or prohibit-password, modify it accordingly.

    tip

    If the line begins with a #, it is commented out and will be ignored. Remove the # to activate the setting.

  3. Ensure There Is a Sudo-Privileged User: Before disabling root login, make sure there is at least one user on the system with sudo privileges. Otherwise, you may lose administrative access. You may add a user with sudo privileges by running the following commands.

    sudo adduser adminuser
    sudo usermod -aG sudo adminuser

    This user can now perform administrative tasks using sudo.

    warning

    If you're working remotely, keep an existing SSH session open while making these changes. This can prevent accidental lockout if something goes wrong.

  4. Restart the SSH Service: To apply the configuration changes, restart the SSH service.

    sudo systemctl restart ssh

    This step must be performed after every configuration change.

  5. Test the Configuration: Try to log in as root to confirm that the restriction is working.

    ssh root@server_ip

    If you receive a “Permission denied” message, the configuration has been successfully applied.

Disabling root login is a fundamental security measure, especially on systems exposed to the internet, and helps reduce the attack surface significantly.

How to Use SSH with a Firewall (UFW and Fail2Ban)?

When the SSH service is exposed to the public internet, it becomes a common target for attacks. To strengthen security, two essential layers of protection, UFW and Fail2Ban, are recommended. While UFW (Uncomplicated Firewall) is used for network-level access control, Fail2Ban is a beneficial tool for dynamic IP blocking against brute-force login attempts. You may secure your SSH server with UFW and Fail2Ban by following the next steps.

  1. Allow SSH Through UFW: By default, SSH uses TCP port 22. Allow access to this port through UFW.

    sudo ufw allow ssh

    This command allows TCP connections on port 22 based on the definitions in /etc/services.

    If you’ve changed your SSH port (e.g., to 2222), run the next command.

    sudo ufw allow 2222/tcp

    To view current UFW rules:

    sudo ufw status verbose
    warning

    Before enabling UFW, make sure SSH access is allowed via the currently active session. Otherwise, you may lose remote access to the server.

    Enable UFW by running the following command.

    sudo ufw enable
  2. Install Fail2Ban: Fail2Ban monitors system log files and automatically bans IP addresses that have multiple failed login attempts. Install Fail2Ban by running the following command.

    sudo apt install fail2ban –y

    After installation, the Fail2Ban service starts automatically.

  3. Configure Fail2Ban for SSH: To customize the configuration without altering the default settings, create a jail.local file.

    sudo nano /etc/fail2ban/jail.local

    The recommended configuration for SSH is given below.

    ini
    [sshd]
    enabled = true
    port = ssh
    logpath = /var/log/auth.log
    maxretry = 3
    findtime = 600
    bantime = 3600

    This setup blocks any IP address that fails to log in 3 times within 10 minutes for a duration of 1 hour.

    note

    If you’ve changed your SSH port, update port = ssh to port = 2222 (or your custom port).

  4. Restart Fail2Ban Service: To activate the new configuration, restart the Fail2Ban service.

    sudo systemctl restart fail2ban
  5. Monitor Fail2Ban Status: To view active jails and currently banned IPs, run the following commands.

    sudo fail2ban-client status
    sudo fail2ban-client status sshd

    These commands show which jails are active and list the IPs currently being blocked.

    When used together, Fail2Ban and UFW provide both static (port-level) and dynamic (behavior-based) protection for your SSH service, greatly improving your server’s security posture.

What Are the Benefits of Using SSH Keys for Authentication?

SSH key-based authentication offers a significantly more secure and efficient alternative to traditional username/password combinations for encrypted connections. This authentication mechanism relies on a cryptographic key pair consisting of two main components: a private key, which remains confidential and is stored on the client machine, and a public key, which is uploaded to the server. This approach has become the standard method for both personal system access and modern automation or cloud infrastructure.

Key advantages of SSH key-based authentication are as follows;

  • Stronger Security: Keys are composed of long, randomly generated character sequences, making them highly resistant to brute-force attacks. There's no risk of compromising password databases.
  • No Password Transmission: Passwords are never transmitted during authentication, eliminating the risk of interception or sniffing over the network.
  • Automation-Friendly: SSH keys allow for passwordless login—essential for automated scripts and cron jobs. They ensure seamless integration in CI/CD workflows.
  • Access Control Per Key: Each user can have a unique key pair. Individual keys can be revoked without affecting others. Access can be controlled granularly via the ~/.ssh/authorized_keys file.
  • Key Revocation Without Changing System Passwords: To revoke access, you simply remove the associated public key from the server. No need to reset system passwords.
  • Support for Passphrase-Protected Private Keys: Private keys can be secured with a passphrase for added protection. Even if the key is lost, unauthorized usage is prevented.
  • Portable and Reusable: SSH keys can be reused across multiple servers and are easy to transfer. This is especially helpful for administrators managing multiple systems.

SSH key-based authentication provides a structured and effective layer of defense, particularly against password-based attacks. For this reason, it is strongly recommended to implement key-based authentication in any secure SSH configuration.

How to Change the Default SSH Port?

The default SSH port (22) is one of the most commonly scanned and targeted by attackers. Changing the SSH port is an effective way to reduce the system's attack surface. While this measure alone does not guarantee complete security, it helps avoid low-level automated port scans. You may change the default SSH port by following the next steps.

  1. Open the SSH Configuration File: To define a new port number, edit the SSH configuration file.

    sudo nano /etc/ssh/sshd_config

    This file determines how the SSH daemon behaves, including which port it listens on.

  2. Set a Custom Port Number: Locate the following line and replace it with your desired port number. For example:

    Port 2222
    note

    Choose a port number above 1024 that is not already used by another service.

  3. Allow the New Port through the Firewall: If you're using UFW, you must explicitly allow access to the new port. Otherwise, incoming connections will be blocked.

    sudo ufw allow 2222/tcp

    The existing “ssh” rule only applies to port 22—new rules are required for custom ports.

  4. Restart the SSH Service: To apply the changes, restart the SSH service.

    sudo systemctl restart ssh

    If there's a syntax or configuration error, the service may fail to restart, so keep a test session open beforehand.

  5. Test the New Port Connection: Try connecting via the new port.

    ssh -p 2222 user@server_ip
    tip

    If you don’t have physical access to the server or are working remotely, always keep a second SSH session open before making changes. This helps prevent accidental lockout in case something goes wrong.

    warning

    If the new port doesn't work and firewall rules haven’t been updated, you may lose access to the server. Proceed cautiously and verify each step.

While this method won't eliminate brute-force attacks altogether, switching from commonly used ports helps make your SSH access less obvious and harder to target.

How to Enable and Use SSH Agent for Managing SSH Keys?

The SSH agent is a helper program designed to simplify the management of passphrase-protected private keys. It securely holds your decrypted private key in memory after you enter the passphrase once, eliminating the need to re-enter it for every SSH connection. This enhances the user experience without compromising security.

  1. Start the SSH Agent: The SSH agent runs per session and starts as a background process in memory.

    eval "$(ssh-agent -s)"

    This command starts a new agent process and sets the SSH_AUTH_SOCK environment variable.

  2. Add Your Private Key to the Agent: To add your protected private key to the agent, run the following command.

    ssh-add ~/.ssh/id_rsa

    This loads the key into memory, allowing passwordless use for subsequent SSH connections.

    If your key file is located elsewhere, specify the path.

    ssh-add ~/.ssh/custom_key
  3. View Loaded Keys: To list the keys currently loaded in the agent, run the following command.

    ssh-add –l

    This shows all active keys available for use in the session.

  4. Remove Keys from the Agent (Optional): To remove a specific key from the agent, run the following command.

    ssh-add -d ~/.ssh/id_rsa

    To remove all keys, run the following command.

    ssh-add –D
  5. Automate SSH Agent Loading on Login (Optional): In graphical environments like GNOME, KDE, or macOS, the SSH agent is started automatically. In CLI-only sessions, add the following line to your .bashrc or .profile file to enable it on login by running the following command.

    eval "$(ssh-agent -s)" > /dev/null
    note

    The SSH agent stores the passphrase only in memory. After a system reboot, you'll need to enter it again.

    warning

    While the SSH agent memory is isolated, other processes running under the same user may theoretically access it. For untrusted environments, avoid using keys without a passphrase.

Using the SSH agent improves both security and convenience by eliminating repeated passphrase prompts per session. It’s especially useful for frequent connections, automation scripts, Git workflows, and CI/CD pipelines.

How to Use SSH Tunneling to Access Remote Services Securely?

SSH tunneling (port forwarding) is an effective way to securely access services running on a remote system from your local network. It protects data traffic by routing it through the encrypted SSH connection. This technique is commonly used to access remote databases, web interfaces, VNC sessions, or custom applications securely.

SSH tunneling can be implemented in three ways:

  1. Local port forwarding (most common)
  2. Remote port forwarding
  3. Dynamic port forwarding (SOCKS proxy)
tip

SSH tunneling is a lightweight, user-level alternative to VPNs. It operates per session rather than system-wide. Port forwarding may be restricted in some corporate networks or behind NAT devices. Check firewall rules and the AllowTcpForwarding setting on the SSH server.

SSH tunneling is a lightweight yet powerful solution for secure remote access. It combines encryption, flexibility, and ease of use, making it an essential tool for developers, system administrators, and data analysts in their daily workflows.

Local port forwarding

In this section, we'll focus on local port forwarding. Local port forwarding maps a local port on your machine to a service on a remote server. The general syntax is for SSH local port forwarding is given below.

ssh -L [local_port]:[remote_host]:[remote_port] user@ssh_server

Example:

ssh -L 8080:localhost:80 [user@192.168.1.10](mailto:user@192.168.1.10)

In this example, traffic to localhost:8080 on your local machine is forwarded to localhost:80 on the remote server.

To access the forwarded SSH service while the SSH connection is active, open your browser and navigate to [http://localhost:8080](http://localhost:8080). This connects you securely to port 80 on the remote server through an encrypted tunnel.

Use cases for local port forwarding are listed below.

  • Connecting to a remote MySQL database

    ssh -L 3307:localhost:3306 dbadmin@dbserver
  • Secure access to web-based services (e.g., Apache, Grafana):

    ssh -L 8081:127.0.0.1:3000 admin@remote_host
  • Secure remote desktop (RDP/VNC) connections

    ssh -L 5901:localhost:5901 user@remote_desktop

    You may run the tunnel in the background without opening a shell. The following command sets up the tunnel silently and doesn't launch a shell session.

    ssh -fN -L 8080:localhost:80 user@remote_host

Remote Port Forwarding

Remote port forwarding allows a remote system to open access to its port on your local system.

ssh -R 2222:localhost:22 user@remote_host

This forwards incoming traffic to the remote host's port 2222 into your local machine's SSH service.

Dynamic Port Forwarding (SOCKS Proxy)

Creates an encrypted proxy connection for your browser or applications.

ssh -D 1080 user@remote_host

This sets up a SOCKS5 proxy, ideal for securing web traffic on untrusted networks.

How to Monitor and Audit SSH Access Logs?

Regular monitoring and auditing of SSH access is critically important for maintaining system security. Detecting malicious login attempts, failed authentications, and administrative actions requires active surveillance of system logs. On Ubuntu systems, SSH-related activity is typically logged in auth.log or tracked using journalctl on systems that utilize systemd.

You may monitor and audit SSH access logs by using the following methods.

  • View SSH Login Attempts via journalctl: On modern Ubuntu systems, SSH logs can be filtered and viewed via the systemd journal.

    sudo journalctl -u ssh

    This command lists only log entries related to the SSH service.

    Use the --since flag to view logs from a specific time range

    sudo journalctl -u ssh --since "yesterday"
  • Examine Authentication Log Directly: The traditional log file /var/log/auth.log contains records of both successful and failed login attempts.

    sudo grep 'sshd' /var/log/auth.log

    You can filter entries using terms like Accepted, Failed, or Invalid user. For example, to list only successful logins, run the following command.

    grep 'Accepted' /var/log/auth.log
  • Use who, w and last commands: To inspect current or past user login sessions, use the following commands.

    • who: Shows users currently logged into the system.
    • w: Displays active sessions along with their duration and processes.
    • last: Lists recently logged-in users with corresponding IP addresses in chronological order.
  • Enable Verbose SSH Logging (Advanced): For advanced monitoring, you can increase the logging level in the SSH configuration file.

    sudo nano /etc/ssh/sshd_config

    Modify or add the following line.

    text
    LogLevel VERBOSE

    This setting logs pre-authentication details such as attempted usernames.

    Don’t forget to restart the SSH service to apply the changes.

    sudo systemctl restart ssh
  • Monitor in Real-Time: To watch log entries live as they occur, run the following command.

    sudo tail -f /var/log/auth.log

    New SSH-related log entries will appear in real-time in your terminal.

  • Integrate with Security Tools: SSH access logs can be centrally managed or analyzed using various security tools.

    • Fail2Ban: Monitors logs and bans IPs after multiple failed login attempts
    • Logwatch: Generates daily summary reports of log activity
    • SIEM tools (e.g., Splunk, Graylog, ELK Stack): Aggregates logs across multiple systems for centralized analysis
warning

SSH logs may contain sensitive personal data. They should be stored and accessed in compliance with privacy regulations like GDPR.

Monitoring SSH access logs helps you understand who connected, when, and how, enabling early detection of unauthorized access attempts. This audit process is a vital component of your defensive infrastructure.

How to Configure SSH on Ubuntu for Remote Desktop Access?

SSH can be used not only for terminal-based remote access but also to securely launch graphical applications remotely. One method for doing this is X11 Forwarding, which allows GUI applications on a remote Ubuntu system to display on your local machine. This feature is ideal for system administrators, developers, and remote support personnel who need access to desktop-based tools.

You may configure SSH for remote desktop access by following the next steps.

  1. Install Required Packages on the Server: Make sure the necessary packages for X11 forwarding are installed on the remote Ubuntu system.

    sudo apt update
    sudo apt install xauth x11-apps
    • xauth: manages X11 session authentication.

    • x11-apps: includes basic graphical test utilities.

  2. Enable X11 Forwarding in SSH Server Configuration: Open the SSH server configuration file to enable X11 forwarding.

    sudo nano /etc/ssh/sshd_config

    Ensure the following lines are present and not commented out (no # at the beginning):

    text
    X11Forwarding yes
    X11DisplayOffset 10
    X11UseLocalhost yes

    Save the file and restart the SSH service.

    sudo systemctl restart ssh
    note

    X11 forwarding only supports GUI applications run by the logged-in user. A desktop environment (like GNOME or XFCE) is not required.

  3. Connect from the Client with X11 Forwarding Enabled: On your local system (typically Linux or macOS with XQuartz), start an SSH session with X11 forwarding enabled.

    ssh -X user@remote_host

    The -X flag enables X11 forwarding in the SSH client.

    Alternatively, you can use -Y for trusted forwarding, which is less restrictive.

    ssh -Y user@remote_host
  4. Launch GUI Applications Remotely: Once connected, you can run a graphical application remotely.

    xclock

    This command opens a simple analog clock window. If it appears on your local screen, the setup is working correctly.

  5. Use SSH for Full Remote Desktop (VNC over SSH) / (Optional): You can secure full desktop access by tunneling VNC traffic over SSH.

    ssh -L 5901:localhost:5901 user@remote_host

    Then connect using your local VNC client to localhost:5901 securely through SSH.

    tip

    Best Practices and Tips

    • X11 forwarding is secure but resource-intensive. It may perform poorly over slow networks.
    • All X11 traffic is encrypted through the SSH tunnel—no VPN is required.
    • Use -Y (trusted forwarding) with caution. It is not recommended on untrusted remote systems.
    warning

    Windows clients require additional software (such as Xming or VcXsrv) to support X11. Also, ensure your SSH client supports the -X flag.

Using X11 forwarding with SSH provides a lightweight, secure way to interact with remote systems graphically. It's especially helpful for system administrators who occasionally need GUI tools outside the terminal.

How to Set Up SSH for File Transfer with SFTP or SCP?

The SSH protocol not only allows for secure remote command execution but also provides an encrypted and secure channel for file transfer. This functionality is enabled through two primary methods:

  • SCP (Secure Copy Protocol): Fast and direct file transfer from the command line
  • SFTP (SSH File Transfer Protocol): An interactive, FTP-like file management interface

Both methods rely on SSH for user authentication, using either passwords or SSH keys, and ensure end-to-end encryption of data in transit.

For either method to work, the target system must be running the SSH server (openssh-server). Additionally, the client machine should have the OpenSSH client installed.

sudo apt install openssh-server openssh-client

On Ubuntu desktop editions, the client is usually preinstalled.

Transfer Files Using SCP

SCP uses a syntax similar to the cp command and allows you to quickly copy files to or from a remote server.

To send a file from your local system to the remote host using scp, run the following command.

scp file.txt user@remote_host:/home/user/

To download a file from the remote server, run the following command.

scp user@remote_host:/etc/hosts ./hosts_copy

To copy a directory or multiple files, use the -r flag:

scp -r myfolder/ user@remote_host:/home/user/

Manage Files with SFTP

SFTP provides an interface similar to FTP, but all traffic is tunneled over SSH and encrypted.

To initiate an SFTP session, run the following command.:

sftp user@remote_host

Basic commands within an SFTP session are listed below.

  • ls:Lists files on the remote server
  • cd: Changes the current directory
  • get file.txt: Downloads a file from the remote server
  • put file.txt: Uploads a file to the remote server
  • exit: Ends the session

SFTP is supported by many graphical clients, such as FileZilla (Linux, Windows, macOS), WinSCP (Windows) and Cyberduck (macOS). Typical connection parameters for SFTP client

tip

SCP may fail or time out when transferring large files over unstable connections. For more robust transfers, consider using rsync.

Because both SCP and SFTP operate on top of SSH, they require no additional setup. They are ideal solutions for system administrators who need secure, fast, and flexible file transfer capabilities.

How to Use SSH for Automation and Scripting?

SSH is not only useful for manual remote access but also serves as a powerful tool for automating tasks such as system administration, maintenance, deployment, and data transfer. Using scripts, you can establish SSH connections to execute commands, trigger scripts, and synchronize files on remote systems.

This capability is widely used in DevOps, system administration, and CI/CD environments.

Best practices for SSH automation are as follows.

  • Enforce key-based login only—never use passwords in automation
  • Start scripts with set -e to halt on errors
  • Encrypt private keys with a passphrase and load them using ssh-agent
  • Log outputs and errors using 2>&1 | tee logfile.txt
tip

If your scripts need to run sudo commands, make sure the user has passwordless sudo (NOPASSWD) configured. Otherwise, automation will fail when prompted for a password.

Run a Remote Command Non-Interactively

The simplest automation scenario involves executing a single remote command via SSH.

ssh user@remote_host "uptime"

This command prints the remote system's uptime in your local terminal.

tip

Enclose the command in double quotes to prevent the shell from interpreting it locally.

Execute Multiple Commands Remotely

To run several commands in sequence using the && operator.

ssh user@remote_host "df -h && free -m && uname -r"

Each command runs in order. The && operator ensures the next command only runs if the previous one succeeds.

Automate SSH in a Shell Script

You can place SSH commands inside a Bash script for automation.

#!/bin/bash
HOST="192.168.1.100"
USER="admin"
ssh ${USER}@${HOST} "sudo apt update && sudo apt upgrade -y"

This script remotely triggers a package update on the target server.

Use SSH Key Authentication in Scripts

Key-based authentication is essential for automation. Without it, password prompts will break the process. You can test connectivity before proceeding.

if ssh -q user@host exit; then
echo "Connected successfully"
else
echo "Connection failed"
fi

Use SSH Multiplexing for Performance

To speed up sequential SSH operations, enable connection sharing using ControlMaster in your SSH config.

perl
Host remote_host
ControlMaster auto
ControlPath ~/.ssh/control-%r@%h:%p
ControlPersist 10m

This reduces overhead by reusing an existing SSH session.

Combine SSH with Cron Jobs

You can automate tasks using cron.

0 3 * * * /usr/bin/ssh user@remote_host "/usr/local/bin/backup.sh"

This cron job runs the remote backup script daily at 3:00 AM.

Conclusion

Script-based SSH automation allows you to perform tasks like system updates, backups, service restarts, and data synchronization—remotely, securely, and on schedule.

SSH is the backbone of secure remote access and management on Ubuntu. In this guide, we’ve covered how to set it up, harden its security, and enhance its functionality for daily use.

Whether you're managing a single server or orchestrating automation across dozens, a solid SSH setup directly impacts your system’s security and efficiency. You can strengthen your defenses with key-based authentication, prevent brute-force attacks using Fail2Ban, and tailor SSH behavior through tunneling and X11 forwarding.

At the heart of every strong configuration lie simple, consistent practices. Close unnecessary access points, restrict ports wisely, and monitor logs regularly to maintain both external security and internal order.

With the guidance in this setup guide, you’re now equipped to use SSH on Ubuntu more consciously, securely, and effectively.

Get Started with Zenarmor Today For Free