If you’re running an Ubuntu server, you’ve probably noticed that SSH connections use port 22 by default. While this works perfectly fine, it’s like leaving your front door key under the welcome mat – everyone knows where to look! Changing your default SSH port is one of the simplest yet most effective ways to enhance your server’s security.
In this comprehensive guide, I’ll walk you through every step of changing the default SSH port on Ubuntu, from the initial backup to testing your new configuration. Whether you’re a system administrator managing multiple servers or a developer setting up your first VPS, this tutorial will help you secure your Ubuntu system against automated attacks.
Why Change the Default SSH Port?
Before we dive into the technical steps, let’s understand why changing the default SSH port matters for your server security.
Reducing Automated Attacks
Port 22 is like a neon sign for attackers. Automated bots constantly scan the internet looking for servers with SSH running on the default port. By changing to a non-standard port, you immediately reduce the number of automated attack attempts your server receives.
Security Through Obscurity
While changing the SSH port isn’t a bulletproof security measure, it’s an excellent first line of defense. Think of it as moving your house number – burglars driving around looking for easy targets won’t find you as easily.
Compliance Requirements
Some organizations require non-standard ports for SSH connections as part of their security policies. If you’re working in a regulated industry, this change might be mandatory.
Reduced Log Noise
You’ll notice significantly fewer failed login attempts in your system logs, making it easier to spot legitimate security concerns among the noise.
Prerequisites Before Changing SSH Port
Before we start modifying your SSH configuration, make sure you have:
- Root or sudo access to your Ubuntu server
- An active SSH connection to your server (don’t close this until you’ve tested the new port!)
- Physical or console access to your server (in case something goes wrong)
- Basic knowledge of text editors like nano or vim
- Firewall management knowledge for your specific setup
Important Warning: Never change SSH settings without having a backup connection method. If something goes wrong, you could lock yourself out of your server permanently.
Step-by-Step Guide to Change SSH Port on Ubuntu
Let’s walk through the complete process of changing your SSH port safely and effectively.
Step 1: Backup Your SSH Configuration
Before making any changes, always create a backup of your current SSH configuration. This simple step can save you hours of troubleshooting if something goes wrong.
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup
This command creates a backup file that you can restore if needed. You can also add a timestamp to your backup:
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup.$(date +%Y%m%d)
Step 2: Choose a New Port Number
Selecting the right port number is crucial for avoiding conflicts with other services. Here are the guidelines:
Port Range Recommendations:
- Avoid ports 1-1024: These are reserved for system services and require root privileges
- Choose ports 1024-65535: These are generally safe for user applications
- Popular choices: 2222, 2020, 8022, or any number above 10000
Check Port Availability
Before settling on a port, verify it’s not already in use:
sudo netstat -tlnp | grep :PORT_NUMBER
Replace PORT_NUMBER
with your chosen port. If you see no output, the port is available.
You can also use this command to check:
lsof -i :PORT_NUMBER -S
Step 3: Edit the SSH Configuration File
Now comes the main event – editing the SSH daemon configuration file. The SSH configuration is stored in /etc/ssh/sshd_config
.
Open the Configuration File:
sudo nano /etc/ssh/sshd_config
Locate the Port Directive:
Look for a line that says #Port 22
or Port 22
. In most Ubuntu installations, this line is commented out (starts with #).
Make the Change:
Remove the # symbol and change 22 to your chosen port number:
Port 2222
Save and Exit:
If you’re using nano, press Ctrl+O
to save, then Enter
to confirm, and Ctrl+X
to exit.
Important Note: Be extremely careful when editing this file. A single typo can prevent the SSH service from starting, potentially locking you out of your server.
Step 4: Configure Firewall Settings
After changing the SSH port, you must update your firewall rules to allow connections on the new port. The steps vary depending on your firewall setup.
Using UFW (Uncomplicated Firewall)
UFW is Ubuntu’s default firewall management tool. Here’s how to configure it:
Check UFW Status:
sudo ufw status
Allow the New SSH Port:
sudo ufw allow 2222/tcp
Optional – Remove Old SSH Rule:
After testing the new port, you can remove the old rule:
sudo ufw delete allow 22/tcp
Using iptables
If you’re using iptables directly:
sudo iptables -A INPUT -p tcp --dport 2222 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
Don’t forget to save your iptables rules so they persist after reboot.
Step 5: Restart SSH Service
Once you’ve made the configuration changes, restart the SSH service to apply them:
For Ubuntu 18.04, 20.04, and 22.04:
sudo systemctl restart ssh
Alternative method:
sudo service ssh restart
Check Service Status:
sudo systemctl status ssh
You should see output indicating that SSH is active and running. Look for a line showing your new port number.
Step 6: Test the New SSH Port
This is the most critical step – testing your new configuration before closing your current SSH session.
Verify SSH is Listening on the New Port:
sudo ss -tlnp | grep :2222
You should see output similar to:
tcp LISTEN 0 128 0.0.0.0:2222 0.0.0.0:*
Test Connection from Another Terminal:
Open a new terminal window and try connecting:
ssh username@your_server_ip -p 2222
Only disconnect your original SSH session after confirming the new port works perfectly.
Ubuntu Version-Specific Considerations
Different Ubuntu versions may have slight variations in SSH configuration and service management.
Ubuntu 22.04 and Later Versions
Ubuntu 22.04 introduced some changes to SSH service management. If you’re having trouble with the port change not taking effect:
Check for Socket-Based Activation:
sudo systemctl status ssh.socket
Restart Both SSH Service and Socket:
sudo systemctl daemon-reload
sudo systemctl restart ssh.socket
sudo systemctl restart ssh
Alternative Configuration Method:
Some users report needing to disable the socket and use traditional service startup:
sudo systemctl disable ssh.socket
sudo systemctl enable ssh.service
Ubuntu 18.04 and 20.04
These versions typically use the traditional SSH service management:
Service Name:
The service is called ssh
(not sshd
like in some other distributions).
Configuration Check:
grep -i port /etc/ssh/sshd_config
This command shows you the current port configuration.
Common Issues and Troubleshooting
Even with careful preparation, you might encounter some issues. Here are the most common problems and their solutions.
SSH Service Won’t Start
Symptoms: The SSH service fails to restart after making changes.
Solution:
- Check the configuration file for syntax errors:
sudo sshd -t
- If there are errors, restore your backup:
sudo cp /etc/ssh/sshd_config.backup /etc/ssh/sshd_config
- Review the system logs:
sudo journalctl -u ssh.service
Cannot Connect to New Port
Symptoms: SSH refuses connections on the new port.
Troubleshooting Steps:
- Verify the port is listening:
sudo netstat -tlnp | grep ssh
- Check firewall rules:
sudo ufw status verbose
- Test with verbose output:
ssh -v username@server_ip -p 2222
Firewall Blocking Connections
Symptoms: Connection attempts time out.
Solutions:
- Temporarily disable UFW for testing:
sudo ufw disable
(Remember to re-enable it after testing!)
- Check if the rule was added correctly:
sudo ufw status numbered
- Add the rule again if missing:
sudo ufw allow 2222/tcp
Security Best Practices
Changing the SSH port is just one part of a comprehensive security strategy. Here are additional recommendations:
Use Key-Based Authentication
Password authentication is inherently less secure than SSH keys. Disable password authentication and use SSH key pairs instead.
Implement Fail2Ban
Install and configure Fail2Ban to automatically ban IP addresses that show suspicious behavior:
sudo apt update
sudo apt install fail2ban
Regular Updates
Keep your Ubuntu system and SSH software updated:
sudo apt update && sudo apt upgrade
Monitor SSH Logs
Regularly check your SSH logs for unusual activity:
sudo tail -f /var/log/auth.log
Disable Root Login
Edit /etc/ssh/sshd_config
and set:
PermitRootLogin no
How to Connect Using the New SSH Port
Once you’ve successfully changed your SSH port, here’s how to connect using various methods:
Command Line SSH:
ssh username@server_ip -p 2222
Using SSH Config File:
Create or edit ~/.ssh/config
on your local machine:
Host myserver
HostName server_ip
Port 2222
User username
Then connect simply with:
ssh myserver
PuTTY (Windows):
- Open PuTTY
- Enter your server’s IP address
- Change the port number from 22 to your new port
- Click “Open”
WinSCP/FileZilla:
Update the port number in your connection settings to match your new SSH port.
Advanced Configuration Tips
For users who want to go beyond basic port changes:
Multiple SSH Ports
You can configure SSH to listen on multiple ports by adding multiple Port directives:
Port 22
Port 2222
Port Forwarding
If you’re behind a router, don’t forget to update your port forwarding rules to forward the new port to your server.
IPv6 Considerations
Make sure your firewall rules include IPv6 if your server supports it:
sudo ufw allow 2222
(UFW automatically handles both IPv4 and IPv6)
Frequently Asked Questions
1. What happens if I choose a port that’s already in use?
If you select a port that’s already occupied by another service, the SSH daemon will fail to start. Always check port availability using netstat -tlnp | grep :PORT
before making changes. If SSH fails to start, restore your backup configuration and choose a different port.
2. Can I change the SSH port back to 22 if needed?
Absolutely! Simply edit /etc/ssh/sshd_config
, change the Port directive back to 22, update your firewall rules, and restart the SSH service. The process is identical to changing to a custom port, just in reverse.
3. Will changing the SSH port affect other services on my server?
No, changing the SSH port only affects SSH connections. Other services like web servers, databases, or email servers will continue running on their respective ports unchanged. However, make sure you’re not choosing a port that conflicts with existing services.
4. Do I need to inform users about the SSH port change?
Yes, anyone who connects to your server via SSH will need to know the new port number. Update your documentation, inform your team members, and consider using SSH config files to make connections easier for regular users.
5. Is changing the SSH port enough to secure my server?
While changing the SSH port significantly reduces automated attacks, it’s just one layer of security. You should also implement SSH key authentication, disable root login, use fail2ban, keep your system updated, and follow other security best practices for comprehensive protection.
Learn how to change default SSH port on Ubuntu with our step-by-step guide. Secure your server from automated attacks easily.