Troubleshooting SSH Port Change Issues in Almalinux9

Abstract: Resolve lost SSH connectivity on AlmaLinux 9 after changing the port by synchronizing sshd, SELinux, and firewall configurations.

Created: 2026-08-11 by
Changing the SSH port on AlmaLinux 9 often results in lost connectivity because the firewall, SELinux policies, and the sshd service configuration are not updated in unison. This guide resolves these issues by ensuring all three components align with your new port number.

Update the SSH Daemon Configuration

The first step is to inform the Secure Shell daemon (sshd) that it should listen on a non-standard port. By default, sshd listens on port 22. You must edit the main configuration file located at /etc/ssh/sshd_config. Open this file using your preferred text editor, such as nano or vim, and locate the line that specifies the port. It may be commented out with a hash symbol (#). Remove the hash and change the value to your desired port, for example, Port 2222. Ensure you choose a port above 1024 to avoid conflicts with system services. After making this change, save the file and exit the editor. Do not restart the service yet, as the firewall rules still block traffic on the new port.

Configure SELinux Policies

AlmaLinux 9 uses SELinux (Security-Enhanced Linux) to enforce security policies. If you change the SSH port without updating SELinux, the service will fail to start or connect because it lacks permission to bind to the new port. You can verify the current context of SSH ports using the command semanage port -l | grep ssh. To add a new port to the allowed list, use the semanage utility. For example, if you chose port 2222, run:
sudo semanage port -a -t ssh_port_t -p tcp 2222
If the port already exists in the policy but with a different type, you may need to modify it instead using -m. Always verify the change was applied by running the semanage port -l command again. This step is critical; skipping it is the most common reason for "Connection Refused" errors after changing the port.

Adjust Firewall Rules

The next layer of protection is the firewall. AlmaLinux 9 typically uses firewalld by default. You must open the new port in the firewall configuration. Use the firewall-cmd tool to add the port to the public zone. Run the following command to add the port permanently:
sudo firewall-cmd --permanent --add-port=2222/tcp
After adding the port, reload the firewall to apply the changes immediately:
sudo firewall-cmd --reload
If you are using legacy iptables instead of firewalld, you would need to edit the /etc/sysconfig/iptables file directly or use iptables-save and iptables-restore. However, on modern AlmaLinux systems, firewalld is the standard. You can verify that the port is open by checking the firewall status:
sudo firewall-cmd --list-all
Look for your new port in the ports: section of the output. Note that if you previously had port 22 open, you might want to remove it from the firewall once you confirm the new port works, though keeping both open temporarily aids in troubleshooting.

Restart Services and Test Connectivity

Now that the configuration files, SELinux policies, and firewall rules are aligned, you can restart the SSH service. Use the following command:
sudo systemctl restart sshd
Check the status to ensure there are no errors:
systemctl status sshd
Before disconnecting your current session, test the new connection from a terminal window. Try connecting to the server using the new port:
ssh -p 2222 username@your_server_ip
If you can successfully log in, the configuration is correct. If the connection fails, check the journal logs for specific error messages using journalctl -u sshd. Common issues include typos in the port number or incorrect SELinux contexts. Once verified, you can close your current session.

Prevent Lockout During Remote Changes

A significant risk when changing SSH ports remotely is losing access if something goes wrong. To mitigate this, always maintain an active console session or use a tool like tmux or screen before restarting the service. Alternatively, configure a second SSH instance listening on port 22 alongside your new port during the transition period. Edit /etc/ssh/sshd_config.d/ or create a drop-in configuration file to allow dual listening. Once you have confirmed stable access via the new port for several days, you can disable port 22 entirely for enhanced security. This approach ensures you never lock yourself out of your server due to misconfiguration. For more advanced network routing scenarios, you might also consider Forwarding www traffic through a remote computer if you are integrating this SSH setup into a broader proxy architecture.

Frequently Asked Questions

Why does my SSH connection timeout even after opening the port?

This usually indicates that SELinux is blocking the service rather than the firewall. Verify that your new port is listed in the SELinux policy using semanage port -l. If it is missing, add it as described in the SELinux section. Additionally, ensure that no other firewall appliance between your client and server is blocking the traffic.

Can I keep port 22 open while testing the new port?

Yes, you can configure sshd to listen on multiple ports simultaneously. Add additional Port lines in /etc/ssh/sshd_config for each port you wish to support. Remember to update both the firewall and SELinux policies for every new port added. This is the safest way to migrate without risking immediate lockout.

How do I revert the changes if I get locked out?

If you lose SSH access, you must use the provider's console or VNC interface to log in. From there, edit /etc/ssh/sshd_config to restore the original port 22 setting. Also, ensure SELinux and firewall rules are corrected. Restarting the sshd service will then restore standard access.

Does changing the SSH port improve security?

It reduces automated bot attacks significantly since most scanners target port 22 by default. However, it is not a substitute for strong authentication methods like SSH keys or fail2ban. Port obfuscation is a defense-in-depth strategy, not a complete security solution.

What if I am using iptables instead of firewalld?

You must manually add a rule to accept TCP traffic on your new port. Use iptables -I INPUT -p tcp --dport NEW_PORT -j ACCEPT and then save the rules with iptables-save. Unlike firewalld, iptables changes are not persistent across reboots unless explicitly saved.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More