How to Change the Default SSH Port

Changing the default SSH port from 22 to a custom port is a simple yet effective security measure that significantly reduces automated attacks on your Linux server. This comprehensive guide walks you through the process of changing the SSH port on various Linux distributions, configuring firewalls, and implementing best practices for secure SSH port configuration.

Table of Contents

Prerequisites

Before changing your SSH port, ensure you have:

  • Linux server (Ubuntu, Debian, CentOS, Rocky Linux, or similar)
  • Root access or sudo privileges
  • Active SSH connection to the server
  • Access to server console via hosting provider panel (critical backup access)
  • Basic understanding of Linux command line
  • Firewall management knowledge (UFW, firewalld, or iptables)
  • For RHEL-based systems: Understanding of SELinux basics

Critical warning: Always maintain console access to your server before making SSH changes. If you lose SSH access and don't have console access, you could be locked out of your server.

Understanding Why to Change SSH Port

Security Benefits

1. Reduces automated attacks:

  • Bots and scripts scan for port 22 by default
  • Changing the port eliminates 99% of automated brute-force attempts
  • Significantly reduces server log clutter from failed login attempts

2. Security through obscurity:

  • Not a replacement for proper security measures
  • Adds an additional layer to defense-in-depth strategy
  • Makes targeted attacks slightly more difficult

3. Improved server performance:

  • Fewer automated login attempts reduce CPU and network usage
  • Cleaner authentication logs for easier monitoring
  • Reduced bandwidth consumption from port scanners

Limitations and Misconceptions

What changing SSH port does NOT do:

  • Does not protect against targeted attacks
  • Does not replace strong authentication (SSH keys, 2FA)
  • Does not eliminate the need for fail2ban or similar tools
  • Is not sufficient as the sole security measure

Important: Changing the SSH port is a complementary security measure, not a replacement for proper SSH hardening, strong authentication, and firewall configuration.

When to Change SSH Port

Recommended scenarios:

  • Public-facing servers with SSH exposed to internet
  • Servers experiencing high volumes of automated attacks
  • Compliance requirements for non-standard ports
  • Development servers shared among multiple users
  • Servers behind restrictive corporate firewalls

Not necessary:

  • Servers only accessible via VPN
  • Servers with IP whitelist firewall rules
  • Internal network-only servers
  • Containers or temporary instances

Step 1: Choose a New SSH Port Number

Port Selection Criteria

Valid port ranges:

  • 1-1023: System/privileged ports (require root)
  • 1024-49151: Registered ports (some assigned to services)
  • 49152-65535: Dynamic/private ports (recommended range)

Recommended SSH port choices:

  • 2222: Common alternative, easy to remember
  • 22000: Easy to remember, high-range
  • 50000-60000: Less commonly scanned range
  • Random high port: Use random port between 49152-65535

Ports to avoid:

# Check if port is already in use
sudo ss -tlnp | grep :PORT_NUMBER
sudo netstat -tlnp | grep :PORT_NUMBER

# Common ports to avoid:
# 80, 443 (HTTP/HTTPS)
# 3306 (MySQL)
# 5432 (PostgreSQL)
# 6379 (Redis)
# 8080, 8443 (Alternative HTTP/HTTPS)
# 3389 (RDP)
# 21, 22, 23, 25 (FTP, SSH, Telnet, SMTP)

Generate random port number:

# Generate random port in safe range
shuf -i 49152-65535 -n 1

# Or use this method
echo $((RANDOM + 49152))

Example: Check if port 2222 is available:

# Check if anything is listening on port 2222
sudo ss -tlnp | grep :2222

# If no output, port is available
# Test connectivity to port (should fail if not in use)
telnet localhost 2222
nc -zv localhost 2222

For this guide, we'll use port 2222 as an example. Replace with your chosen port throughout.

Step 2: Backup SSH Configuration

Before making changes, always backup the original SSH configuration.

# Backup SSH configuration with timestamp
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup.$(date +%Y%m%d_%H%M%S)

# Verify backup was created
ls -lh /etc/ssh/sshd_config.backup.*

# Alternative: Create backup directory
sudo mkdir -p /root/backups/ssh
sudo cp /etc/ssh/sshd_config /root/backups/ssh/sshd_config.$(date +%Y%m%d_%H%M%S)

View current SSH configuration:

# Display current SSH port setting
grep -i "^Port" /etc/ssh/sshd_config

# If commented out, SSH is using default port 22
# View all active (uncommented) settings
grep -v "^#" /etc/ssh/sshd_config | grep -v "^$"

Document current configuration:

# Create configuration documentation
cat > /tmp/ssh-config-pre-change.txt << EOF
SSH Configuration Before Port Change
Date: $(date)
Server: $(hostname)
Current Port: $(grep -i "^Port" /etc/ssh/sshd_config || echo "22 (default)")
Listening: $(sudo ss -tlnp | grep sshd)
EOF

cat /tmp/ssh-config-pre-change.txt

Step 3: Configure New SSH Port

Edit SSH Daemon Configuration

# Edit SSH configuration file
sudo nano /etc/ssh/sshd_config

# Or use vi/vim
sudo vi /etc/ssh/sshd_config

Find and modify the Port directive:

Look for this line (may be commented with #):

#Port 22

Option 1: Single port configuration (recommended after testing)

Change to your new port:

Port 2222

Option 2: Dual port configuration (recommended during transition)

Listen on both old and new ports temporarily:

Port 22
Port 2222

Why dual port configuration?

  • Allows testing new port without losing access on port 22
  • Provides fallback if new port has issues
  • Enables gradual transition for multiple users
  • Can be reverted easily if problems occur

Additional recommended SSH hardening settings:

While editing, consider these security improvements:

# Disable root login
PermitRootLogin no

# Disable password authentication (use SSH keys)
PasswordAuthentication no

# Disable empty passwords
PermitEmptyPasswords no

# Limit authentication attempts
MaxAuthTries 3

# Set login grace time
LoginGraceTime 30

# Disable X11 forwarding if not needed
X11Forwarding no

# Use only strong ciphers
Ciphers [email protected],[email protected],[email protected],aes256-ctr,aes192-ctr,aes128-ctr

# Use strong MACs
MACs [email protected],[email protected]

# Use strong key exchange algorithms
KexAlgorithms curve25519-sha256,[email protected],diffie-hellman-group-exchange-sha256

Save and exit the file:

  • nano: Press Ctrl+X, then Y, then Enter
  • vi/vim: Press Esc, type :wq, press Enter

Test SSH configuration syntax:

# Verify configuration has no syntax errors
sudo sshd -t

# If errors are shown, fix them before proceeding
# No output means configuration is valid

View configuration changes:

# Compare with backup
diff /etc/ssh/sshd_config.backup.* /etc/ssh/sshd_config

# Display port configuration
grep -i "^Port" /etc/ssh/sshd_config

Step 4: Configure Firewall for New Port

Before restarting SSH, configure your firewall to allow the new port.

UFW Firewall (Ubuntu/Debian)

# Check UFW status
sudo ufw status

# Allow new SSH port
sudo ufw allow 2222/tcp comment 'SSH custom port'

# Verify rule was added
sudo ufw status numbered

# Optional: Allow from specific IP only
sudo ufw allow from 203.0.113.50 to any port 2222 proto tcp

# Reload UFW
sudo ufw reload

Firewalld (CentOS/Rocky Linux/RHEL)

# Check firewalld status
sudo firewall-cmd --state

# Add new SSH port permanently
sudo firewall-cmd --permanent --add-port=2222/tcp

# Or create custom service definition
sudo firewall-cmd --permanent --new-service=ssh-custom
sudo firewall-cmd --permanent --service=ssh-custom --set-description="SSH on custom port"
sudo firewall-cmd --permanent --service=ssh-custom --add-port=2222/tcp
sudo firewall-cmd --permanent --add-service=ssh-custom

# Reload firewall
sudo firewall-cmd --reload

# Verify rules
sudo firewall-cmd --list-all
sudo firewall-cmd --list-ports

Iptables (Direct Configuration)

# Allow new SSH port
sudo iptables -A INPUT -p tcp --dport 2222 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
sudo iptables -A OUTPUT -p tcp --sport 2222 -m conntrack --ctstate ESTABLISHED -j ACCEPT

# Save iptables rules (Ubuntu/Debian)
sudo netfilter-persistent save
# Or
sudo iptables-save | sudo tee /etc/iptables/rules.v4

# Save iptables rules (CentOS/Rocky Linux)
sudo service iptables save
# Or
sudo iptables-save | sudo tee /etc/sysconfig/iptables

# View rules
sudo iptables -L -n -v | grep 2222

Cloud Provider Firewalls

Don't forget external firewalls:

If using cloud providers (AWS, DigitalOcean, GCP, Azure, etc.), also configure their security groups/firewall:

AWS Security Groups:

  • Add inbound rule: TCP port 2222 from your IP or 0.0.0.0/0

DigitalOcean Cloud Firewalls:

  • Add inbound rule: TCP port 2222

Google Cloud Platform:

  • Create firewall rule allowing TCP:2222

Azure Network Security Groups:

  • Add inbound security rule for port 2222

Step 5: Configure SELinux (RHEL-based Systems)

On CentOS, Rocky Linux, AlmaLinux, and RHEL, SELinux must be configured to allow SSH on the new port.

Check SELinux Status

# Check if SELinux is enforcing
sestatus
getenforce

# View current SSH ports allowed by SELinux
sudo semanage port -l | grep ssh
# Default output includes: ssh_port_t tcp 22

Add New Port to SELinux

# Install SELinux management tools if not present
sudo dnf install policycoreutils-python-utils -y

# Add new SSH port to SELinux policy
sudo semanage port -a -t ssh_port_t -p tcp 2222

# Verify port was added
sudo semanage port -l | grep ssh
# Should now show: ssh_port_t tcp 22, 2222

If port is already defined for another service:

# This error may occur:
# ValueError: Port tcp/2222 already defined

# Check what service uses the port
sudo semanage port -l | grep 2222

# If you need to reassign the port
sudo semanage port -m -t ssh_port_t -p tcp 2222

Alternative: Temporarily set SELinux to permissive (not recommended):

# Only for troubleshooting - not for production
sudo setenforce 0

# After fixing issues, return to enforcing
sudo setenforce 1

Verify SELinux Configuration

# Check for SELinux denials
sudo ausearch -m AVC -ts recent | grep sshd

# If denials exist, generate policy
sudo ausearch -m AVC -ts recent | grep sshd | audit2allow -M ssh_custom_port
sudo semodule -i ssh_custom_port.pp

Step 6: Restart SSH Service

Now restart the SSH service to apply the new port configuration.

Critical: Do not close your current SSH session until you've verified the new port works.

# Test configuration one more time
sudo sshd -t

# Restart SSH service (systemd systems)
sudo systemctl restart sshd

# Verify SSH service is running
sudo systemctl status sshd

# Alternative restart methods (older systems)
sudo service sshd restart
sudo /etc/init.d/ssh restart

Check if SSH is listening on new port:

# Verify SSH is listening on new port
sudo ss -tlnp | grep sshd
sudo netstat -tlnp | grep sshd

# Should show lines like:
# tcp    0    0 0.0.0.0:22    0.0.0.0:*    LISTEN    1234/sshd
# tcp    0    0 0.0.0.0:2222  0.0.0.0:*    LISTEN    1234/sshd

View SSH service logs:

# Check for errors in SSH logs
sudo journalctl -u sshd -n 50 --no-pager

# Or view auth log
sudo tail -f /var/log/auth.log  # Ubuntu/Debian
sudo tail -f /var/log/secure    # CentOS/Rocky

Step 7: Test New SSH Port

Critical: Test the new port in a separate terminal session before closing your current connection.

Test from Local Machine

Open a new terminal window on your local machine:

# Test SSH connection on new port
ssh -p 2222 username@your_server_ip

# Verbose mode for troubleshooting
ssh -v -p 2222 username@your_server_ip

# Test with timeout
timeout 10 ssh -p 2222 username@your_server_ip

If connection succeeds:

You should be able to log in normally. Keep both sessions open (old and new) for now.

If connection fails:

Do NOT close your original SSH session. Troubleshoot using the steps in the Troubleshooting section below.

Test Port Connectivity

# Test if port is reachable (from local machine)
nc -zv your_server_ip 2222
telnet your_server_ip 2222

# Test from server itself
nc -zv localhost 2222
telnet localhost 2222

# Check if port is open (from external service)
# Use online port checker: https://www.yougetsignal.com/tools/open-ports/

Verify Both Ports Work (if using dual configuration)

# Test old port (port 22)
ssh -p 22 username@your_server_ip

# Test new port (port 2222)
ssh -p 2222 username@your_server_ip

# Both should work if you configured dual ports

Step 8: Update Client SSH Configuration

Make connecting to your server convenient by updating your SSH client configuration.

Linux/macOS SSH Config

# Edit SSH config file
nano ~/.ssh/config

# Add or modify server entry:
Host myserver
    HostName your_server_ip
    User username
    Port 2222
    IdentityFile ~/.ssh/id_ed25519
    ServerAliveInterval 60
    ServerAliveCountMax 3

# Or for specific domain
Host example.com
    Port 2222
    User admin

# Or for all servers (use cautiously)
Host *
    Port 2222

Now you can connect simply with:

ssh myserver
# Instead of: ssh -p 2222 username@your_server_ip

Set proper permissions:

# SSH config must have correct permissions
chmod 600 ~/.ssh/config

Update Automation Scripts

Update any scripts or automation that connects via SSH:

# In scripts, update SSH commands:
# Old:
ssh user@host 'command'

# New:
ssh -p 2222 user@host 'command'

# Or for scp:
scp -P 2222 file.txt user@host:/path/

# Or for rsync:
rsync -avz -e "ssh -p 2222" /local/ user@host:/remote/

Update SSH Keys and Agents

# Add host key for new port
ssh-keyscan -p 2222 your_server_ip >> ~/.ssh/known_hosts

# Or remove old host key and add new on first connection
ssh-keygen -R your_server_ip
ssh -p 2222 username@your_server_ip

Step 9: Close Old SSH Port

After confirming the new port works reliably for several days, close the old port.

Update SSH Configuration

# Edit SSH config
sudo nano /etc/ssh/sshd_config

# Remove or comment out old port:
# Port 22  <- Comment or remove this line
Port 2222

# Save and test
sudo sshd -t

# Restart SSH
sudo systemctl restart sshd

Remove Old Port from Firewall

UFW:

# Remove old SSH rule (be careful!)
sudo ufw delete allow 22/tcp

# Or disable only from specific source
sudo ufw status numbered
sudo ufw delete [rule_number]

# Verify
sudo ufw status

Firewalld:

# Remove old SSH service
sudo firewall-cmd --permanent --remove-service=ssh

# Or remove port
sudo firewall-cmd --permanent --remove-port=22/tcp

# Reload
sudo firewall-cmd --reload

# Verify
sudo firewall-cmd --list-all

Iptables:

# Remove old SSH rules
sudo iptables -D INPUT -p tcp --dport 22 -j ACCEPT

# Save rules
sudo netfilter-persistent save

Verify Old Port is Closed

# Check SSH is not listening on port 22
sudo ss -tlnp | grep :22

# Test connection (should fail)
ssh -p 22 username@your_server_ip
# Should timeout or be refused

Verification

Comprehensive Verification Checklist

# 1. Verify SSH is listening on new port
sudo ss -tlnp | grep sshd

# 2. Verify firewall allows new port
sudo ufw status | grep 2222  # Ubuntu/Debian
sudo firewall-cmd --list-ports  # CentOS/Rocky

# 3. Verify SELinux allows new port (RHEL-based)
sudo semanage port -l | grep ssh

# 4. Test connection from external source
ssh -p 2222 username@your_server_ip

# 5. Check SSH service status
sudo systemctl status sshd

# 6. Review SSH logs for errors
sudo journalctl -u sshd -n 50 --no-pager

# 7. Verify old port is closed (after transition)
sudo ss -tlnp | grep :22
nc -zv your_server_ip 22  # Should fail

# 8. Check for active SSH connections
sudo ss -tnp | grep sshd
w

# 9. Verify authentication works
ssh -p 2222 username@your_server_ip 'whoami'

# 10. Check fail2ban configuration (if installed)
sudo fail2ban-client status sshd

Create Verification Script

# Create verification script
cat << 'EOF' | sudo tee /usr/local/bin/verify-ssh-port.sh
#!/bin/bash

echo "=== SSH Port Configuration Verification ==="
echo ""

echo "SSH Service Status:"
systemctl status sshd | grep Active

echo ""
echo "Listening Ports:"
ss -tlnp | grep sshd

echo ""
echo "SSH Port Configuration:"
grep -i "^Port" /etc/ssh/sshd_config

echo ""
echo "Firewall Rules:"
if command -v ufw &> /dev/null; then
    ufw status | grep -E "22|2222"
elif command -v firewall-cmd &> /dev/null; then
    firewall-cmd --list-ports | grep -E "22|2222"
fi

echo ""
if command -v getenforce &> /dev/null; then
    echo "SELinux SSH Ports:"
    semanage port -l | grep ssh
fi

echo ""
echo "Active SSH Connections:"
ss -tnp | grep sshd | grep ESTAB

EOF

sudo chmod +x /usr/local/bin/verify-ssh-port.sh
sudo /usr/local/bin/verify-ssh-port.sh

Troubleshooting

Cannot Connect to New Port

Problem: SSH connection times out or is refused on new port.

Solution checklist:

# 1. Verify SSH is listening on the port
sudo ss -tlnp | grep sshd
sudo netstat -tlnp | grep sshd

# 2. Check SSH service is running
sudo systemctl status sshd

# 3. Verify SSH configuration
sudo sshd -t
grep -i "^Port" /etc/ssh/sshd_config

# 4. Check firewall allows port
sudo ufw status | grep 2222
sudo firewall-cmd --list-ports

# 5. Check SELinux (RHEL-based)
sudo semanage port -l | grep ssh
sudo ausearch -m AVC -c sshd

# 6. Test local connectivity
nc -zv localhost 2222
telnet localhost 2222

# 7. Check cloud provider security groups
# Review AWS/GCP/Azure firewall rules

# 8. Review logs
sudo journalctl -u sshd -n 100 --no-pager
sudo tail -100 /var/log/auth.log

SELinux Blocking SSH (RHEL-based)

Problem: Connection refused due to SELinux policy.

Solution:

# Check for SELinux denials
sudo ausearch -m AVC -c sshd -ts recent

# Add port to SELinux policy
sudo semanage port -a -t ssh_port_t -p tcp 2222

# Generate custom policy if needed
sudo ausearch -m AVC -c sshd | audit2allow -M ssh_custom
sudo semodule -i ssh_custom.pp

# Verify port is allowed
sudo semanage port -l | grep ssh

# Check SELinux mode
getenforce

# View detailed SELinux alerts
sudo sealert -a /var/log/audit/audit.log

Locked Out After Closing Port 22

Problem: Closed port 22 too early and now cannot connect.

Solution:

  1. Access via console (hosting provider panel):
# Connect via console
# Check SSH status
sudo systemctl status sshd

# Edit SSH config to add port 22 back
sudo nano /etc/ssh/sshd_config

# Add:
Port 22
Port 2222

# Restart SSH
sudo systemctl restart sshd

# Allow port 22 in firewall
sudo ufw allow 22/tcp
sudo firewall-cmd --add-port=22/tcp

# Test connection on port 22
  1. Prevention: Always use dual-port configuration initially

Firewall Not Allowing New Port

Problem: Firewall blocks new SSH port despite rules.

Solution:

# UFW troubleshooting
sudo ufw status verbose
sudo ufw show added
sudo ufw reload

# Add rule if missing
sudo ufw allow 2222/tcp

# Check rule order
sudo ufw status numbered

# Firewalld troubleshooting
sudo firewall-cmd --state
sudo firewall-cmd --list-all
sudo firewall-cmd --reload

# Add port if missing
sudo firewall-cmd --permanent --add-port=2222/tcp
sudo firewall-cmd --reload

# Check iptables directly
sudo iptables -L INPUT -n -v | grep 2222
sudo ip6tables -L INPUT -n -v | grep 2222

SSH Service Won't Start

Problem: SSH service fails to start after configuration change.

Solution:

# Check for configuration errors
sudo sshd -t

# View detailed error messages
sudo systemctl status sshd -l
sudo journalctl -u sshd -n 50 --no-pager

# Common issues:
# - Syntax error in sshd_config
# - Port already in use
# - Permission issues

# Check if port is already in use
sudo ss -tlnp | grep :2222
sudo fuser 2222/tcp

# Kill process using port
sudo fuser -k 2222/tcp

# Restore backup if needed
sudo cp /etc/ssh/sshd_config.backup.* /etc/ssh/sshd_config
sudo systemctl restart sshd

Connection Drops Immediately

Problem: Connection established but drops immediately.

Solution:

# Connect with verbose output
ssh -vvv -p 2222 username@your_server_ip

# Check for authentication issues
sudo tail -f /var/log/auth.log

# Verify user permissions
id username
sudo grep username /etc/passwd

# Check SSH key permissions
ls -la ~/.ssh/
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

# Verify SELinux contexts (RHEL-based)
ls -Z ~/.ssh/
restorecon -Rv ~/.ssh

Best Practices

Security Recommendations

  1. Use high-numbered ports (49152-65535) to avoid common scans

  2. Combine with other security measures:

    • SSH key authentication (disable passwords)
    • Fail2ban for intrusion prevention
    • Firewall rules limiting access by IP
    • Two-factor authentication (2FA)
    • Regular security audits
  3. Monitor authentication logs:

# Create monitoring alias
echo "alias ssh-logs='sudo tail -f /var/log/auth.log | grep sshd'" >> ~/.bashrc
source ~/.bashrc

# Run monitoring
ssh-logs
  1. Document port changes:
# Create documentation file
cat > /root/ssh-port-info.txt << EOF
SSH Port Configuration
Date Changed: $(date)
New Port: 2222
Changed By: $(whoami)
Reason: Security hardening - reduce automated attacks
Firewall Updated: Yes
SELinux Updated: Yes (RHEL-based)
Client Configs Updated: Yes
EOF
  1. Use port knocking for additional security:
# Install knockd
sudo apt install knockd  # Ubuntu/Debian
sudo dnf install knockd  # CentOS/Rocky

# Configure knock sequence
sudo nano /etc/knockd.conf

Operational Best Practices

  1. Maintain dual-port access initially (22 and custom port)
  2. Test thoroughly before removing port 22
  3. Update all team members before closing old port
  4. Document in runbooks and procedures
  5. Update monitoring systems to check new port
  6. Configure backup access methods (console, VPN)
  7. Schedule change during maintenance window

Automation and Monitoring

# Create SSH port monitor script
cat << 'EOF' | sudo tee /usr/local/bin/monitor-ssh-port.sh
#!/bin/bash

PORT=2222
LOG_FILE="/var/log/ssh-port-monitor.log"

if ! ss -tln | grep -q ":$PORT "; then
    echo "$(date): SSH not listening on port $PORT" >> "$LOG_FILE"
    systemctl restart sshd
    echo "$(date): SSH service restarted" >> "$LOG_FILE"
fi

# Check for excessive failed attempts
FAILED=$(grep "Failed password" /var/log/auth.log | grep "port $PORT" | tail -100 | wc -l)
if [ $FAILED -gt 50 ]; then
    echo "$(date): High number of failed attempts: $FAILED" >> "$LOG_FILE"
fi

EOF

sudo chmod +x /usr/local/bin/monitor-ssh-port.sh

# Add to crontab for periodic monitoring
(crontab -l 2>/dev/null; echo "*/5 * * * * /usr/local/bin/monitor-ssh-port.sh") | crontab -

Multi-Server Management

When managing multiple servers:

# Create SSH config with custom ports
cat >> ~/.ssh/config << EOF

Host server1
    HostName 192.0.2.10
    Port 2222
    User admin

Host server2
    HostName 192.0.2.11
    Port 50000
    User root

Host server3
    HostName 192.0.2.12
    Port 22022
    User deploy

# Pattern matching for all servers
Host server*
    ServerAliveInterval 60
    ServerAliveCountMax 3
    IdentityFile ~/.ssh/id_ed25519

EOF

# Use ansible for bulk port changes
# Create playbook: change-ssh-port.yml

Reverting Changes

If you need to revert to port 22:

# Restore backup configuration
sudo cp /etc/ssh/sshd_config.backup.* /etc/ssh/sshd_config

# Or edit manually
sudo nano /etc/ssh/sshd_config
# Change: Port 2222 → Port 22

# Test and restart
sudo sshd -t
sudo systemctl restart sshd

# Update firewall
sudo ufw allow 22/tcp
sudo firewall-cmd --add-service=ssh

# Remove custom port from SELinux (RHEL-based)
sudo semanage port -d -t ssh_port_t -p tcp 2222

Conclusion

Changing the default SSH port from 22 to a custom port is a simple security enhancement that significantly reduces automated attacks and improves your server's security posture. While it's not a silver bullet, it's an effective component of a defense-in-depth security strategy.

Key achievements:

  • SSH port successfully changed from 22 to custom port
  • Firewall configured to allow new SSH port
  • SELinux configured (RHEL-based systems)
  • Client SSH configurations updated
  • Connection tested and verified
  • Old port closed after successful transition

Important reminders:

  • Port changes alone don't replace proper SSH hardening
  • Always maintain console access before making changes
  • Test thoroughly before closing port 22
  • Document changes for team members and future reference
  • Monitor logs for issues after the change

Next security steps:

  • Implement SSH key authentication (disable passwords)
  • Configure Fail2Ban for intrusion prevention
  • Set up two-factor authentication (2FA)
  • Implement IP whitelisting if possible
  • Regular security audits and log monitoring

By following this guide, you've implemented an important security layer that will dramatically reduce the noise from automated attacks and make your server slightly harder to target.

Additional Resources

Related Guides

  • How to Connect to Your Server via SSH
  • Initial Security Configuration on Ubuntu/Debian
  • Initial Security Configuration on CentOS/Rocky Linux
  • Fail2Ban Configuration for Brute Force Protection
  • SSH Key Management: Generation and Best Practices
  • Firewall Configuration with firewalld (CentOS/Rocky)
  • Linux Server Hardening: Complete Guide