Enable SSH on Ubuntu at a Glance
To enable SSH on Ubuntu you install one package, confirm it listens, open the firewall and switch to key login.
The steps apply to Ubuntu Server and Ubuntu Desktop 22.04 LTS, 24.04 LTS and 26.04 LTS on a normal install that runs systemd. WSL and containers often start without systemd, so the service commands can differ there. You need an account with sudo rights and, on a remote server, a second way in such as the provider web console, in case a firewall or config change locks you out.
Ubuntu Server may already have SSH if OpenSSH was ticked during installation, while Ubuntu Desktop normally needs the package added. If you are starting from scratch, Ubuntu VPS hosting gives you root access and a provider console as your way back in.
| Step | Command | Notes |
|---|---|---|
| Check if it is installed | dpkg-query -W openssh-server | Safe to run first |
| Install the server | sudo apt install openssh-server | Starts SSH on port 22 |
| Check it is listening | sudo ss -tlnp 'sport = :22' | Shows the listener and its process |
| Allow it in ufw | sudo ufw allow OpenSSH | Needed when ufw is active or before you enable it |
| Connect | ssh user@203.0.113.10 | From your own computer |
| Switch to keys | ssh-keygen -t ed25519 and ssh-copy-id | Then turn password login off |
The first six sections are the essential setup. Key login and the day one settings are the recommended security, and the rest is reference for port changes, disabling SSH and fixing errors.
The addresses in this guide, 203.0.113.10 for the server and 203.0.113.25 for your own computer, are documentation examples. Replace them with your real addresses. The account name laneadmin is an example too.
Check Whether SSH Is Already Installed
Check whether SSH is already installed before adding anything, because many server and cloud images ship with it.
dpkg-query -W -f='${Status} ${Version}\n' openssh-serverinstall ok installed 1:9.6p1-3ubuntu13.20That is the real result on the Ubuntu 24.04.5 test system. If the package is missing, the command says no packages were found instead. The ssh command on its own is only the client, so ssh -V working does not mean this machine accepts SSH connections.
ssh -VOpenSSH_9.6p1 Ubuntu-3ubuntu13.20, OpenSSL 3.0.13 30 Jan 2024Install OpenSSH Server on Ubuntu
To install OpenSSH server on Ubuntu, refresh the package lists and install the openssh-server package with apt.
sudo apt update
sudo apt install openssh-serverThe package creates the server host keys under /etc/ssh/, installs the systemd units and starts listening on TCP port 22 for IPv4 and IPv6. You can confirm which version apt picked.
apt-cache policy openssh-serveropenssh-server:
Installed: 1:9.6p1-3ubuntu13.20
Candidate: 1:9.6p1-3ubuntu13.20Installed and Candidate match, so the installed package is the version apt currently selects from your configured repositories. That version depends on your Ubuntu release, repository setup and package priorities.
Start and Enable the SSH Service
How you start and enable the SSH service depends on the release, because Ubuntu 22.10 and later use systemd socket activation by default.
| Release | What listens on port 22 | Start and enable at boot |
|---|---|---|
| Ubuntu 22.04 LTS | ssh.service, the sshd daemon itself | sudo systemctl enable --now ssh |
| Ubuntu 24.04 LTS and 26.04 LTS | ssh.socket, which starts ssh.service on the first connection | sudo systemctl enable --now ssh.socket |
On a standard install the package starts SSH and enables it at boot, so these commands are mainly for a server where someone turned it off. Check the state with systemctl status.
# Ubuntu 22.04
sudo systemctl status ssh.service --no-pager
systemctl is-enabled ssh.service
# Ubuntu 24.04 and 26.04
sudo systemctl status ssh.socket --no-pager
systemctl is-enabled ssh.socketYou want active and enabled from the unit for your release. On 24.04 and 26.04, ssh.service can show as inactive right after a reboot while ssh.socket is active. That is normal, because the socket holds port 22 and starts the daemon when the first connection arrives.
This is the socket unit shipped in the 24.04 package. It listens on IPv4 and IPv6 separately. Inspection of the Ubuntu 26.04 package, openssh-server 1:10.2p1-2ubuntu3.8, found an identical ssh.socket file and the same socket generator, and its install script enables ssh.socket. Those package contents were inspected, not run on an installed 26.04 system.
cat /usr/lib/systemd/system/ssh.socket[Unit]
Description=OpenBSD Secure Shell server socket
Before=sockets.target ssh.service
ConditionPathExists=!/etc/ssh/sshd_not_to_be_run
[Socket]
ListenStream=0.0.0.0:22
ListenStream=[::]:22
BindIPv6Only=ipv6-only
Accept=no
FreeBind=yes
[Install]
WantedBy=sockets.target
RequiredBy=ssh.serviceThe 24.04 service unit carries Alias=sshd.service, so systemctl restart sshd and systemctl restart ssh reach the same unit. The real unit name is ssh.
Confirm SSH Is Listening
Confirm SSH is listening with ss, which shows the port, the address family and the process that owns the socket.
sudo ss -tlnp 'sport = :22'The filter matches the source port exactly, so it cannot pick up a port such as 2222 by accident. This is the real result from the test server, which listened on port 22815, so run it with 22 on your own server.
State Recv-Q Send-Q Local Address:Port Peer Address:PortProcess
LISTEN 0 128 0.0.0.0:22815 0.0.0.0:* users:(("sshd",pid=15005,fd=4))A normal Ubuntu server with IPv6 shows a 0.0.0.0:22 line and a [::]:22 line, and the process name can differ while only the 24.04 socket is active. A listener proves the server side is ready. It does not prove a firewall in between lets you through.
Allow SSH Through the Ubuntu Firewall
To allow SSH through the Ubuntu firewall, add the ufw rule first and only then turn ufw on, or you can lock yourself out.
On Ubuntu, ufw starts out disabled with a default incoming policy of deny. While it stays inactive it blocks nothing, which is why SSH works straight after the install.
sudo ufw statusStatus: inactiveThe openssh-server package ships a ufw application profile in /etc/ufw/applications.d/openssh-server, so you can allow it by name.
sudo ufw app info OpenSSHProfile: OpenSSH
Title: Secure shell server, an rshd replacement
Description: OpenSSH is a free implementation of the Secure Shell protocol.
Port:
22/tcpThe profile covers TCP 22 only. SSH does not use UDP, so there is no UDP rule to add. If you moved SSH to another port, allow that port number instead of the profile.
Add the Rule and Enable ufw
Add the rule and enable ufw in this order, then read the status back.
sudo ufw allow OpenSSH
sudo ufw enable
sudo ufw status verboseEnabling ufw flushes its chains and may drop existing connections, so when you run it over SSH it asks you to confirm. The status should list OpenSSH ALLOW IN Anywhere and, when IPv6 is on, a matching (v6) line. Ubuntu turns IPv6 rules on in /etc/default/ufw.
grep '^IPV6=' /etc/default/ufwIPV6=yesTo preview a rule without changing anything, add --dry-run. This is the rule ufw generated for the profile on the test system, which has no IPv6, so only the IPv4 rule appears.
sudo ufw --dry-run allow OpenSSH### tuple ### allow tcp 22 0.0.0.0/0 any 0.0.0.0/0 OpenSSH - in
-A ufw-user-input -p tcp --dport 22 -j ACCEPT -m comment --comment 'dapp_OpenSSH'Limit or Restrict the SSH Rule
A limit or restrict rule narrows who can reach SSH. Use one of these in place of the open rule, not beside it, because the open rule still lets everyone in.
# Option 1, rate limit SSH connections
sudo ufw limit OpenSSH
# Option 2, allow SSH only from your own address
sudo ufw allow proto tcp from 203.0.113.25 to any port 22Pick one option, not both. The limit rule denies an address that opens 6 or more connections within 30 seconds, which slows password guessing but does not stop a patient attacker. The second rule allows only one source address, so keep it current if your address changes. If you added the open rule earlier, remove it with sudo ufw delete allow OpenSSH or the restriction has no effect.
Check Firewalls Outside Ubuntu
Firewalls outside Ubuntu block SSH too. A cloud security group, a hosting panel firewall or a home router needs TCP 22 allowed before you can connect from the internet.
Connect to Ubuntu Over SSH for the First Time
To connect to Ubuntu over SSH, run ssh with your user name and the server address from a terminal on your own computer.
ssh laneadmin@203.0.113.10Linux and macOS include this OpenSSH client. On Windows 10 and 11 it is an optional feature, so add OpenSSH Client under Optional features if ssh is not found. On the first connection the client shows the server key fingerprint and asks you to trust it. This is the real prompt from the test server, which listened on 127.0.0.1 port 22815.
The authenticity of host '[127.0.0.1]:22815 ([127.0.0.1]:22815)' can't be established.
ED25519 key fingerprint is SHA256:qVyzWc+b0xQ5Dk5CK8Vk2sp9XAgrNEYZjts11/e4kS8.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '[127.0.0.1]:22815' (ED25519) to the list of known hosts.Only answer yes when the fingerprint matches the server. Read it on the server itself through the provider console. The two values must be identical.
ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub256 SHA256:qVyzWc+b0xQ5Dk5CK8Vk2sp9XAgrNEYZjts11/e4kS8 testhost (ED25519)That output came from the test host key, which is why it matches the prompt above. Your server has its own key and its own fingerprint.
Test the Port Before Signing In
Test the port before signing in when a login fails, so you know whether the network or the sign in is the problem.
nc -vz 203.0.113.10 22These are real results from the test system, first against the open test port and then against a port with no listener.
Connection to 127.0.0.1 22815 port [tcp/*] succeeded!
nc: connect to 127.0.0.1 port 22816 (tcp) failed: Connection refusedsucceeded proves a TCP connection reached something on that port. It does not prove the account, the key or the password will work. If nc is not installed, go straight to the ssh attempt with -v.
Reach Ubuntu Behind a Home Router
To reach Ubuntu behind a home router, forward a TCP port on the router to the machine private address and port 22.
ufw on the machine still has to allow the port, and you connect to the router public address. Only do this with key login and the day one settings below in place, because the port is then open to the whole internet.
Save the Server in Your SSH Config
Save the server in your SSH config on your own computer, so a short name replaces the address, user and key.
Host my-ubuntu
HostName 203.0.113.10
User laneadmin
IdentityFile ~/.ssh/id_ed25519
IdentitiesOnly yesPut those lines in ~/.ssh/config on the client, not on the server, then connect with ssh my-ubuntu. The same kind of entry, pointed at the test server, printed connected as laneadmin.
Set Up SSH Key Login
SSH key login replaces the password with a key pair, and you set it up from your own computer, not on the server.
Create the Key Pair
Create the key pair with ssh-keygen and protect it with a passphrase when it asks.
ssh-keygen -t ed25519 -C "laptop key"Ed25519 is the type the Ubuntu documentation recommends, with RSA 4096 as a fallback for old systems. The private key stays on your computer in ~/.ssh/id_ed25519. Only the .pub file goes to the server.
Copy the Public Key to the Server
Copy the public key to the server with ssh-copy-id, which signs in with your password one last time and adds the key.
ssh-copy-id laneadmin@203.0.113.10The Windows OpenSSH tools do not include ssh-copy-id. In PowerShell this command does the same job. It was not run for this guide.
type $env:USERPROFILE\.ssh\id_ed25519.pub | ssh laneadmin@203.0.113.10 "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"If you add the key by hand through the console, the folder and file permissions matter. sshd ignores an authorized_keys file that other users can write to. These are the permissions on the test account.
ls -la /home/laneadmin/.sshdrwx------ 2 laneadmin laneadmin 4096 Nov 26 08:59 .
drwxr-x--- 3 laneadmin laneadmin 4096 Nov 26 08:59 ..
-rw------- 1 laneadmin laneadmin 96 Nov 26 08:59 authorized_keysProve the Key Is Used
Prove the key is used with ssh -v, because a login that silently falls back to a password looks the same from outside.
ssh -v laneadmin@203.0.113.10 true 2>&1 | grep -E 'Server accepts key|Authenticated to'debug1: Server accepts key: client_ed25519 ED25519 SHA256:gc4QkWeQgGr+UpDlDZbnRYR56RMfG9q9xgt/x1UU+gw explicit
Authenticated to 127.0.0.1 ([127.0.0.1]:22815) using "publickey".using "publickey" is the line that matters. If it says password or keyboard-interactive, the key was not accepted and you must fix that before the next section.
SSH Settings Worth Changing on Day One
The SSH settings worth changing on day one turn off password login and root login, once key login is proven to work.
| Setting | Effective value on stock Ubuntu 24.04 | Day one value | What it does and does not do |
|---|---|---|---|
PasswordAuthentication | yes | no | Ends password guessing. A stolen private key still works, so use a passphrase |
KbdInteractiveAuthentication | no | no | Closes the other password style prompt |
PermitRootLogin | prohibit-password, shown by sshd as without-password | no | Root cannot sign in at all. You use sudo from your own account |
AllowUsers | not set, so every account | your user names | Only listed accounts may sign in. A typo locks everyone out |
MaxAuthTries | 6 | 3 | Fewer attempts per connection. It does not limit new connections |
LoginGraceTime | 120 seconds | 30 | Drops connections that never finish signing in |
X11Forwarding | yes | no | Turns off remote graphical windows a server rarely needs |
The middle column is what sshd -T reported for the unchanged Ubuntu 24.04 config on the test system. Run the same check on your own server, because another release, an image or an earlier edit can change it.
sudo sshd -T | grep -E '^(passwordauthentication|kbdinteractiveauthentication|permitrootlogin|x11forwarding|maxauthtries|logingracetime) 'logingracetime 120
maxauthtries 6
permitrootlogin without-password
passwordauthentication yes
kbdinteractiveauthentication no
x11forwarding yesBack Up Before You Edit
Back up before you edit, and keep your current SSH session open until a new login has worked.
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.original
sudo cp -a /etc/ssh/sshd_config.d /etc/ssh/sshd_config.d.originalIf anything breaks, sign in through the console, delete the file you added in the next step and restart the service. The open session is your faster way back.
Write the Settings in a Drop In File
Write the settings in a drop in file under /etc/ssh/sshd_config.d/ so package updates never have to merge your edits into the main file.
sudo nano /etc/ssh/sshd_config.d/10-hardening.confPermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3
LoginGraceTime 30
X11Forwarding no
AllowUsers laneadminPut your own user names after AllowUsers, separated by spaces. Ubuntu reads the drop in files before the rest of sshd_config, and for most settings the first value sshd reads wins. That is why the file name starts with a low number.
Validate the Config Before Applying
Validate the config before applying it, because sshd will not start with a bad line and you would lose the next login.
sudo sshd -t && echo config okNo output from sshd -t means the file is valid. A typo such as PermitRootLogin_no, an easy slip when copying settings, fails like this and returns exit code 255. The path shown is the config copy used on the test system.
/root/w/ubuntu-enable-ssh/sshd_config.d/99-typo.conf line 1: no argument after keyword "PermitRootLogin_no"
/root/w/ubuntu-enable-ssh/sshd_config.d/99-typo.conf: terminating, 1 bad configuration optionsA valid file can still be overridden. sshd -T prints the values sshd will really use, so check those, not just the file you wrote.
sudo sshd -T | grep -E '^(permitrootlogin|passwordauthentication|kbdinteractiveauthentication|pubkeyauthentication|maxauthtries|logingracetime|x11forwarding|allowusers) 'logingracetime 30
maxauthtries 3
permitrootlogin no
pubkeyauthentication yes
passwordauthentication no
kbdinteractiveauthentication no
x11forwarding no
allowusers laneadminWatch for Cloud Image Overrides
Cloud image overrides can switch password login back on, because cloud-init may add its own file, such as 50-cloud-init.conf.
On the test system a file with PasswordAuthentication yes named 50-cloud-init.conf lost to 10-hardening.conf, and sshd -T showed passwordauthentication no. Renamed to 60-hardening.conf, the same settings lost and sshd -T showed yes. The lower number wins, which is easy to miss without sshd -T.
Apply and Prove the New Settings
Apply and prove the new settings with a restart, then a fresh login from a second terminal while the first stays open.
sudo systemctl restart sshThe service unit uses KillMode=process, so a restart replaces the listening daemon and leaves sessions that are already open running. In the test, a session started before the restart finished its command afterwards. Now prove that keys work and passwords do not. The output below is from the test server on 127.0.0.1.
ssh laneadmin@203.0.113.10 'echo key login works for $(whoami)'
ssh -o PreferredAuthentications=none -o BatchMode=yes laneadmin@203.0.113.10 truekey login works for laneadmin
laneadmin@127.0.0.1: Permission denied (publickey).Before the change the same probe answered Permission denied (publickey,password). The list in brackets is what the server still offers, so password missing from it proves password login is off. It does not prove the key on your laptop is safe, so keep a passphrase on it.
The server log records why each login was accepted or refused. On Ubuntu you read it with journalctl. The test server wrote the same messages to a log file, and these lines are from it after the change.
sudo journalctl -u ssh -n 20 --no-pagerUser root from 127.0.0.1 not allowed because not listed in AllowUsers
Accepted publickey for laneadmin from 127.0.0.1 port 42728 ssh2: ED25519 SHA256:gc4QkWeQgGr+UpDlDZbnRYR56RMfG9q9xgt/x1UU+gwChange the SSH Port on Ubuntu 22.04 to 26.04
To change the SSH port on Ubuntu 22.04 to 26.04, set Port in sshd config, then restart the service or, on 24.04 and later, the socket.
On 24.04 and 26.04 a service restart alone does nothing for the port.
The 24.04 package says so in a comment at the top of /etc/ssh/sshd_config.
# When systemd socket activation is used (the default), the socket
# configuration must be re-generated after changing Port, AddressFamily, or
# ListenAddress.
#
# For changes to take effect, run:
#
# systemctl daemon-reload
# systemctl restart ssh.socketThe regeneration is done by sshd-socket-generator. Run against a copy of the config with Port 2222 in a drop in file, it wrote this socket override, which replaces port 22 on IPv4 and IPv6.
# Automatically generated by sshd-socket-generator
[Socket]
ListenStream=
ListenStream=0.0.0.0:2222
ListenStream=[::]:2222First look for Port lines that are already active, because sshd uses the first value it reads and an earlier file would win over yours.
sudo grep -RniE '^[[:space:]]*Port[[:space:]]+' /etc/ssh/sshd_config /etc/ssh/sshd_config.d/No output means no file sets a port yet. The full sequence on 24.04 and 26.04 then opens the new port, validates, confirms the effective value, regenerates the socket and checks the listener. Port 2222 is an example.
sudo ufw allow 2222/tcp
echo 'Port 2222' | sudo tee /etc/ssh/sshd_config.d/20-port.conf
sudo sshd -t
sudo sshd -T | grep '^port '
sudo systemctl daemon-reload
sudo systemctl restart ssh.socket
sudo ss -tlnp 'sport = :2222'With the drop in file on the test config, sshd -T printed port 2222. On 22.04 there is no generator, so run sudo sshd -t and then sudo systemctl restart ssh instead of the two socket lines. Then sign in from a second terminal with ssh -p 2222 laneadmin@203.0.113.10 and allow TCP 2222 in any cloud firewall too.
Keep port 22 open until that login works. A different port cuts log noise from scanners, but it is not a security measure on its own. More detail is in the guide to changing the SSH port safely.
Disable SSH on Ubuntu When You Need To
To disable SSH on Ubuntu 24.04 and 26.04, stop and disable both the socket and the service, or the socket starts the daemon again.
# Ubuntu 22.04
sudo systemctl disable --now ssh.service
# Ubuntu 24.04 and 26.04
sudo systemctl disable --now ssh.socket ssh.serviceRun this from the console, not over SSH, on a remote server. Turn it back on with sudo systemctl enable --now ssh.socket on 24.04 and 26.04 or sudo systemctl enable --now ssh on 22.04. Removing the package with sudo apt remove openssh-server also works and keeps your config files.
Troubleshoot SSH on Ubuntu
To troubleshoot SSH on Ubuntu, start from the exact error, because each one points at a different layer.
| What you see | Likely cause | Fix |
|---|---|---|
Connection refused | Nothing listens on that port, or the wrong port | Check sudo ss -tlnp, then systemctl status ssh on 22.04 or systemctl status ssh.socket on 24.04 and 26.04 |
Connection timed out | A firewall drops the packets, or the address is wrong | Check ufw, the cloud firewall and the IP address |
Permission denied (publickey) | Password login is off and the key was not accepted | Check the key, authorized_keys permissions and AllowUsers |
Too many authentication failures | Your agent offered more keys than MaxAuthTries allows | Connect with -i ~/.ssh/id_ed25519 -o IdentitiesOnly=yes |
REMOTE HOST IDENTIFICATION HAS CHANGED | The server was rebuilt or the address now points elsewhere | Confirm the new fingerprint, then ssh-keygen -R 203.0.113.10, or ssh-keygen -R '[203.0.113.10]:2222' for a custom port |
| New port has no effect on 24.04 or 26.04 | The socket was not regenerated | Run systemctl daemon-reload and restart ssh.socket |
| Service will not start | A bad line in the config | Run sudo sshd -t and fix the line it names |
For anything else, follow the server log live with sudo journalctl -fu ssh while you try to connect, and run the client with ssh -v to see where the two sides stop.
Questions people ask
How do I enable SSH on Ubuntu?
Run sudo apt install openssh-server. It starts SSH on port 22 and enables it at boot. Then allow OpenSSH in ufw if the firewall is active.
Is SSH enabled by default on Ubuntu?
It depends on how Ubuntu was installed. Many server and cloud images include it and many desktop installs do not, so check with dpkg-query -W openssh-server.
Why is ssh.service inactive on Ubuntu 24.04 and 26.04?
Ubuntu 24.04 and 26.04 use socket activation. ssh.socket listens on port 22 and starts ssh.service when the first connection arrives.
What is the difference between ssh and sshd on Ubuntu?
On Ubuntu the systemd unit is named ssh, and sshd is an alias for it. The program that runs is /usr/sbin/sshd, while ssh alone is the client.
How do I check if SSH is running on Ubuntu?
Run sudo ss -tlnp 'sport = :22' for the listener, then systemctl status on ssh for 22.04 or ssh.socket for 24.04 and 26.04. A real login from another machine is the final proof.
Do I need to open port 22 in ufw?
Only if ufw is active, and it is inactive on a fresh install. Add sudo ufw allow OpenSSH before sudo ufw enable, and allow TCP 22 in any cloud firewall too.
Should I allow root login over SSH?
Usually not. Ubuntu already blocks root passwords with prohibit-password. Sign in as your own user with a key and use sudo, then set PermitRootLogin no.
Can I enable SSH on Ubuntu Desktop the same way?
Yes. The same openssh-server package and steps work on Ubuntu Desktop, which then accepts SSH connections like a server.
Sources
- Ubuntu Server documentation, OpenSSH server
- Ubuntu Discourse, SSHd now uses socket-based activation (Ubuntu 22.10 and later)
- Launchpad bug 2069041, Changing Port in sshd_config requires calling systemctl daemon-reload
- Ubuntu manpage, sshd_config(5) for Ubuntu 24.04
- Ubuntu manpage, sshd(8) for Ubuntu 24.04
- Ubuntu manpage, ufw(8) for Ubuntu 24.04
- Ubuntu Server documentation, Firewalls
- Launchpad, openssh package in Ubuntu 26.04 (Resolute)
- Microsoft Learn, OpenSSH for Windows overview