This Document is actively being developed as a part of ongoing AlmaLinux learning efforts. Chapters will be added periodically.
This is the multi-page printable view of this section. Click here to print.
NTP / SSH Settings
- 1: How to Configure an NTP Server on AlmaLinux
- 2: How to Configure an NTP Client on AlmaLinux
- 3: How to Set Up Password Authentication for SSH Server on AlmaLinux
- 4: File Transfer with SSH on AlmaLinux
- 5: How to SSH File Transfer from Windows to AlmaLinux
- 6: How to Set Up SSH Key Pair Authentication on AlmaLinux
- 7: How to Set Up SFTP-only with Chroot on AlmaLinux
- 8: How to Use SSH-Agent on AlmaLinux
- 9: How to Use SSHPass on AlmaLinux
- 10: How to Use SSHFS on AlmaLinux
- 11: How to Use Port Forwarding on AlmaLinux
- 12: How to Use Parallel SSH on AlmaLinux
1 - How to Configure an NTP Server on AlmaLinux
Accurate timekeeping on servers is crucial for ensuring consistent logging, security protocols, and system operations. AlmaLinux, a robust and enterprise-grade Linux distribution, relies on Chrony as its default Network Time Protocol (NTP) implementation. This guide will walk you through configuring an NTP server on AlmaLinux step by step.
1. What is NTP, and Why is it Important?
Network Time Protocol (NTP) synchronizes system clocks over a network. Accurate time synchronization is essential for:
- Coordinating events across distributed systems.
- Avoiding issues with log timestamps.
- Maintaining secure communication protocols.
2. Prerequisites
Before you begin, ensure:
- A fresh AlmaLinux installation with sudo privileges.
- Firewall configuration is active and manageable.
- The Chrony package is installed. Chrony is ideal for systems with intermittent connections due to its faster synchronization and better accuracy.
3. Steps to Configure an NTP Server
Step 1: Update Your System
Start by updating the system to ensure all packages are up to date:
sudo dnf update -y
Step 2: Install Chrony
Install Chrony, the default NTP daemon for AlmaLinux:
sudo dnf install chrony -y
Verify the installation:
chronyd -v
Step 3: Configure Chrony
Edit the Chrony configuration file to set up your NTP server:
sudo nano /etc/chrony.conf
Make the following changes:
Comment out the default NTP pool by adding
#
:#pool 2.almalinux.pool.ntp.org iburst
Add custom NTP servers near your location:
server 0.pool.ntp.org iburst server 1.pool.ntp.org iburst server 2.pool.ntp.org iburst server 3.pool.ntp.org iburst
Allow NTP requests from your local network:
allow 192.168.1.0/24
(Optional) Enable the server to act as a fallback source:
local stratum 10
Save and exit the file.
Step 4: Start and Enable Chrony
Start the Chrony service and enable it to start on boot:
sudo systemctl start chronyd
sudo systemctl enable chronyd
Check the service status:
sudo systemctl status chronyd
Step 5: Adjust Firewall Settings
To allow NTP traffic through the firewall, open port 123/UDP:
sudo firewall-cmd --permanent --add-service=ntp
sudo firewall-cmd --reload
Step 6: Verify Configuration
Use Chrony commands to ensure your server is configured correctly:
View the active time sources:
chronyc sources
Check synchronization status:
chronyc tracking
4. Testing the NTP Server
To confirm that other systems can sync with your NTP server:
Set up a client system with Chrony installed.
Edit the client’s
/etc/chrony.conf
file, pointing it to your NTP server’s IP address:server <NTP-server-IP>
Restart the Chrony service:
sudo systemctl restart chronyd
Verify time synchronization on the client:
chronyc sources
5. Troubleshooting Tips
Chrony not starting:
Check logs for details:journalctl -xe | grep chronyd
Firewall blocking traffic:
Ensure port 123/UDP is open and correctly configured.Clients not syncing:
Verify theallow
directive in the server’s Chrony configuration and confirm network connectivity.
Conclusion
Configuring an NTP server on AlmaLinux using Chrony is straightforward. With these steps, you can maintain precise time synchronization across your network, ensuring smooth operations and enhanced security. Whether you’re running a small network or an enterprise environment, this setup will provide the reliable timekeeping needed for modern systems.
2 - How to Configure an NTP Client on AlmaLinux
In modern computing environments, maintaining precise system time is critical. From security protocols to log accuracy, every aspect of your system depends on accurate synchronization. In this guide, we will walk through the process of configuring an NTP (Network Time Protocol) client on AlmaLinux, ensuring your system is in sync with a reliable time server.
What is NTP?
NTP is a protocol used to synchronize the clocks of computers to a reference time source, like an atomic clock or a stratum-1 NTP server. Configuring your AlmaLinux system as an NTP client enables it to maintain accurate time by querying a specified NTP server.
Prerequisites
Before diving into the configuration process, ensure the following:
- AlmaLinux is installed and up-to-date.
- You have sudo privileges on the system.
- Your server has network access to an NTP server, either a public server or one in your local network.
Step 1: Update Your System
Begin by updating your AlmaLinux system to ensure all installed packages are current:
sudo dnf update -y
Step 2: Install Chrony
AlmaLinux uses Chrony as its default NTP implementation. Chrony is efficient, fast, and particularly suitable for systems with intermittent connections.
To install Chrony, run:
sudo dnf install chrony -y
Verify the installation by checking the version:
chronyd -v
Step 3: Configure Chrony as an NTP Client
Chrony’s main configuration file is located at /etc/chrony.conf
. Open this file with your preferred text editor:
sudo nano /etc/chrony.conf
Key Configurations
Specify the NTP Servers
By default, Chrony includes public NTP pool servers. Replace or append your desired NTP servers:server 0.pool.ntp.org iburst server 1.pool.ntp.org iburst server 2.pool.ntp.org iburst server 3.pool.ntp.org iburst
The
iburst
option ensures faster initial synchronization.Set Time Zone (Optional)
Ensure your system time zone is correct:timedatectl set-timezone <your-time-zone>
Replace
<your-time-zone>
with your region, such asAmerica/New_York
.Optional: Add Local Server
If you have an NTP server in your network, replace the pool servers with your server’s IP:server 192.168.1.100 iburst
Other Useful Parameters
Minimizing jitter: Adjust poll intervals to reduce variations:
maxpoll 10 minpoll 6
Enabling NTP authentication (for secure environments):
keyfile /etc/chrony.keys
Configure keys for your setup.
Save and exit the editor.
Step 4: Start and Enable Chrony Service
Start the Chrony service to activate the configuration:
sudo systemctl start chronyd
Enable the service to start at boot:
sudo systemctl enable chronyd
Check the service status to ensure it’s running:
sudo systemctl status chronyd
Step 5: Test NTP Synchronization
Verify that your client is correctly synchronizing with the configured NTP servers.
Check Time Sources:
chronyc sources
This command will display a list of NTP servers and their synchronization status:
MS Name/IP address Stratum Poll Reach LastRx Last sample =============================================================================== ^* 0.pool.ntp.org 2 6 37 8 -0.543ms +/- 1.234ms
^*
indicates the server is the current synchronization source.Reach
shows the number of recent responses (value up to 377 indicates stable communication).
Track Synchronization Progress:
chronyc tracking
This provides detailed information about synchronization, including the server’s stratum, offset, and drift.
Sync Time Manually: If immediate synchronization is needed:
sudo chronyc -a makestep
Step 6: Configure Firewall (If Applicable)
If your server runs a firewall, ensure it allows NTP traffic through port 123 (UDP):
sudo firewall-cmd --permanent --add-service=ntp
sudo firewall-cmd --reload
Step 7: Automate Time Sync with Boot
Ensure your AlmaLinux client synchronizes time automatically after boot. Run:
sudo timedatectl set-ntp true
Troubleshooting Common Issues
No Time Sync:
- Check the network connection to the NTP server.
- Verify
/etc/chrony.conf
for correct server addresses.
Chrony Service Fails to Start:
Inspect logs for errors:
journalctl -xe | grep chronyd
Client Can’t Reach NTP Server:
- Ensure port 123/UDP is open on the server-side firewall.
- Verify the client has access to the server via
ping <server-ip>
.
Offset Too High:
Force synchronization:
sudo chronyc -a burst
Conclusion
Configuring an NTP client on AlmaLinux using Chrony ensures that your system maintains accurate time synchronization. Following this guide, you’ve installed Chrony, configured it to use reliable NTP servers, and verified its functionality. Whether you’re working in a small network or a larger infrastructure, precise timekeeping is now one less thing to worry about!
For additional customization or troubleshooting, refer to Chrony documentation.
3 - How to Set Up Password Authentication for SSH Server on AlmaLinux
SSH (Secure Shell) is a foundational tool for securely accessing and managing remote servers. While public key authentication is recommended for enhanced security, password authentication is a straightforward and commonly used method for SSH access, especially for smaller deployments or testing environments. This guide will show you how to set up password authentication for your SSH server on AlmaLinux.
1. What is Password Authentication in SSH?
Password authentication allows users to access an SSH server by entering a username and password. It’s simpler than key-based authentication but can be less secure if not configured properly. Strengthening your password policies and enabling other security measures can mitigate risks.
2. Prerequisites
Before setting up password authentication:
- Ensure AlmaLinux is installed and up-to-date.
- Have administrative access (root or a user with
sudo
privileges). - Open access to your SSH server’s default port (22) or the custom port being used.
3. Step-by-Step Guide to Enable Password Authentication
Step 1: Install the OpenSSH Server
If SSH isn’t already installed, you can install it using the package manager:
sudo dnf install openssh-server -y
Start and enable the SSH service:
sudo systemctl start sshd
sudo systemctl enable sshd
Check the SSH service status to ensure it’s running:
sudo systemctl status sshd
Step 2: Configure SSH to Allow Password Authentication
The SSH server configuration file is located at /etc/ssh/sshd_config
. Edit this file to enable password authentication:
sudo nano /etc/ssh/sshd_config
Look for the following lines in the file:
#PasswordAuthentication yes
Uncomment the line and ensure it reads:
PasswordAuthentication yes
Also, ensure the ChallengeResponseAuthentication
is set to no
to avoid conflicts:
ChallengeResponseAuthentication no
If the PermitRootLogin
setting is present, it’s recommended to disable root login for security reasons:
PermitRootLogin no
Save and close the file.
Step 3: Restart the SSH Service
After modifying the configuration file, restart the SSH service to apply the changes:
sudo systemctl restart sshd
4. Verifying Password Authentication
Step 1: Test SSH Login
From a remote system, try logging into your server using SSH:
ssh username@server-ip
When prompted, enter your password. If the configuration is correct, you should be able to log in.
Step 2: Debugging Login Issues
If the login fails:
Confirm that the username and password are correct.
Check for errors in the SSH logs on the server:
sudo journalctl -u sshd
Verify the firewall settings to ensure port 22 (or your custom port) is open.
5. Securing Password Authentication
While password authentication is convenient, it’s inherently less secure than key-based authentication. Follow these best practices to improve its security:
1. Use Strong Passwords
Encourage users to set strong passwords that combine letters, numbers, and special characters. Consider installing a password quality checker:
sudo dnf install cracklib-dicts
2. Limit Login Attempts
Install and configure tools like Fail2Ban to block repeated failed login attempts:
sudo dnf install fail2ban -y
Configure a basic SSH filter in /etc/fail2ban/jail.local
:
[sshd]
enabled = true
maxretry = 5
bantime = 3600
Restart the Fail2Ban service:
sudo systemctl restart fail2ban
3. Change the Default SSH Port
Using a non-standard port for SSH can reduce automated attacks:
Edit the SSH configuration file:
sudo nano /etc/ssh/sshd_config
Change the port:
Port 2222
Update the firewall to allow the new port:
sudo firewall-cmd --permanent --add-port=2222/tcp sudo firewall-cmd --reload
4. Allow Access Only from Specific IPs
Restrict SSH access to known IP ranges using firewall rules:
sudo firewall-cmd --add-rich-rule='rule family="ipv4" source address="192.168.1.100" service name="ssh" accept' --permanent
sudo firewall-cmd --reload
5. Enable Two-Factor Authentication (Optional)
For added security, configure two-factor authentication (2FA) using a tool like Google Authenticator:
sudo dnf install google-authenticator -y
6. Troubleshooting Common Issues
SSH Service Not Running:
Check the service status:sudo systemctl status sshd
Authentication Fails:
Verify the settings in/etc/ssh/sshd_config
and ensure there are no typos.Firewall Blocking SSH:
Ensure the firewall allows SSH traffic:sudo firewall-cmd --permanent --add-service=ssh sudo firewall-cmd --reload
Connection Timeout:
Test network connectivity to the server usingping
ortelnet
.
Conclusion
Setting up password authentication for an SSH server on AlmaLinux is straightforward and provides a simple method for secure remote access. While convenient, it’s crucial to pair it with strong security measures like limiting login attempts, using strong passwords, and enabling two-factor authentication where possible. By following the steps and best practices outlined in this guide, you can confidently configure and secure your SSH server.
4 - File Transfer with SSH on AlmaLinux
Transferring files securely between systems is a critical task for developers, system administrators, and IT professionals. SSH (Secure Shell) provides a secure and efficient way to transfer files using protocols like SCP (Secure Copy Protocol) and SFTP (SSH File Transfer Protocol). This guide will walk you through how to use SSH for file transfers on AlmaLinux, detailing the setup, commands, and best practices.
1. What is SSH and How Does it Facilitate File Transfer?
SSH is a cryptographic protocol that secures communication over an unsecured network. Along with its primary use for remote system access, SSH supports file transfers through:
- SCP (Secure Copy Protocol): A straightforward way to transfer files securely between systems.
- SFTP (SSH File Transfer Protocol): A more feature-rich file transfer protocol built into SSH.
Both methods encrypt the data during transfer, ensuring confidentiality and integrity.
2. Prerequisites for SSH File Transfers
Before transferring files:
Ensure that OpenSSH Server is installed and running on the remote AlmaLinux system:
sudo dnf install openssh-server -y sudo systemctl start sshd sudo systemctl enable sshd
The SSH client must be installed on the local system (most Linux distributions include this by default).
The systems must have network connectivity and firewall access for SSH (default port: 22).
3. Using SCP for File Transfers
What is SCP?
SCP is a command-line tool that allows secure file copying between local and remote systems. It uses the SSH protocol to encrypt both the data and authentication.
Basic SCP Syntax
The basic structure of the SCP command is:
scp [options] source destination
Examples of SCP Commands
Copy a File from Local to Remote:
scp file.txt username@remote-ip:/remote/path/
file.txt
: The local file to transfer.username
: SSH user on the remote system.remote-ip
: IP address or hostname of the remote system./remote/path/
: Destination directory on the remote system.
Copy a File from Remote to Local:
scp username@remote-ip:/remote/path/file.txt /local/path/
Copy a Directory Recursively: Use the
-r
flag to copy directories:scp -r /local/directory username@remote-ip:/remote/path/
Using a Custom SSH Port: If the remote system uses a non-standard SSH port (e.g., 2222):
scp -P 2222 file.txt username@remote-ip:/remote/path/
4. Using SFTP for File Transfers
What is SFTP?
SFTP provides a secure method to transfer files, similar to FTP, but encrypted with SSH. It allows browsing remote directories, resuming transfers, and changing file permissions.
Starting an SFTP Session
Connect to a remote system using:
sftp username@remote-ip
Once connected, you can use various commands within the SFTP prompt:
Common SFTP Commands
List Files:
ls
Navigate Directories:
Change local directory:
lcd /local/path/
Change remote directory:
cd /remote/path/
Upload Files:
put localfile.txt /remote/path/
Download Files:
get /remote/path/file.txt /local/path/
Download/Upload Directories: Use the
-r
flag withget
orput
to transfer directories.Exit SFTP:
exit
5. Automating File Transfers with SSH Keys
For frequent file transfers, you can configure password-less authentication using SSH keys. This eliminates the need to enter a password for every transfer.
Generate an SSH Key Pair
On the local system, generate a key pair:
ssh-keygen
Save the key pair to the default location (~/.ssh/id_rsa
).
Copy the Public Key to the Remote System
Transfer the public key to the remote system:
ssh-copy-id username@remote-ip
Now, you can use SCP or SFTP without entering a password.
6. Securing SSH File Transfers
To ensure secure file transfers:
Use Strong Passwords or SSH Keys: Passwords should be complex, and SSH keys are a preferred alternative.
Restrict SSH Access: Limit SSH to specific IP addresses using firewall rules.
sudo firewall-cmd --add-rich-rule='rule family="ipv4" source address="192.168.1.100" service name="ssh" accept' --permanent sudo firewall-cmd --reload
Change the Default SSH Port: Modify the SSH port in
/etc/ssh/sshd_config
to reduce exposure to automated attacks.
7. Advanced SSH File Transfer Techniques
Compress Files During Transfer: Use the
-C
flag with SCP to compress files during transfer:scp -C largefile.tar.gz username@remote-ip:/remote/path/
Batch File Transfers with Rsync: For advanced synchronization and large file transfers, use rsync over SSH:
rsync -avz -e "ssh -p 22" /local/path/ username@remote-ip:/remote/path/
Limit Transfer Speed: Use the
-l
flag with SCP to control bandwidth:scp -l 1000 file.txt username@remote-ip:/remote/path/
8. Troubleshooting SSH File Transfers
Authentication Failures:
- Verify the username and IP address.
- Ensure the SSH key is added using
ssh-add
if using key-based authentication.
Connection Timeout:
- Test connectivity with
ping
ortelnet
. - Check the firewall settings on the remote system.
- Test connectivity with
Permission Issues: Ensure the user has write permissions on the destination directory.
Conclusion
File transfers using SSH on AlmaLinux are secure, efficient, and versatile. Whether you prefer the simplicity of SCP or the advanced features of SFTP, mastering these tools can significantly streamline your workflows. By following this guide and implementing security best practices, you can confidently transfer files between systems with ease.
5 - How to SSH File Transfer from Windows to AlmaLinux
Securely transferring files between a Windows machine and an AlmaLinux server can be accomplished using SSH (Secure Shell). SSH provides an encrypted connection to ensure data integrity and security. Windows users can utilize tools like WinSCP, PuTTY, or native PowerShell commands to perform file transfers. This guide walks through several methods for SSH file transfer from Windows to AlmaLinux.
1. Prerequisites
Before initiating file transfers:
AlmaLinux Server:
Ensure the SSH server (
sshd
) is installed and running:sudo dnf install openssh-server -y sudo systemctl start sshd sudo systemctl enable sshd
Confirm that SSH is accessible:
ssh username@server-ip
Windows System:
- Install a tool for SSH file transfers, such as WinSCP or PuTTY (both free).
- Ensure the AlmaLinux server’s IP address or hostname is reachable from Windows.
Network Configuration:
Open port 22 (default SSH port) on the AlmaLinux server firewall:
sudo firewall-cmd --permanent --add-service=ssh sudo firewall-cmd --reload
2. Method 1: Using WinSCP
Step 1: Install WinSCP
- Download WinSCP from the official website.
- Install it on your Windows system.
Step 2: Connect to AlmaLinux
Open WinSCP and create a new session:
- File Protocol: SFTP (or SCP).
- Host Name: AlmaLinux server’s IP address or hostname.
- Port Number: 22 (default SSH port).
- User Name: Your AlmaLinux username.
- Password: Your password or SSH key (if configured).
Click Login to establish the connection.
Step 3: Transfer Files
- Upload Files: Drag and drop files from the left panel (Windows) to the right panel (AlmaLinux).
- Download Files: Drag files from the AlmaLinux panel to your local Windows directory.
- Change Permissions: Right-click a file on the server to modify permissions.
Additional Features
- Synchronize directories for batch file transfers.
- Configure saved sessions for quick access.
3. Method 2: Using PuTTY (PSCP)
PuTTY’s SCP client (pscp
) enables command-line file transfers.
Step 1: Download PuTTY Tools
- Download PuTTY from the official site.
- Ensure the pscp.exe file is added to your system’s PATH environment variable for easy command-line access.
Step 2: Use PSCP to Transfer Files
Open the Windows Command Prompt or PowerShell.
To copy a file from Windows to AlmaLinux:
pscp C:\path\to\file.txt username@server-ip:/remote/directory/
To copy a file from AlmaLinux to Windows:
pscp username@server-ip:/remote/directory/file.txt C:\local\path\
Advantages
- Lightweight and fast for single-file transfers.
- Integrates well with scripts for automation.
4. Method 3: Native PowerShell SCP
Windows 10 and later versions include an OpenSSH client, allowing SCP commands directly in PowerShell.
Step 1: Verify OpenSSH Client Installation
Open PowerShell and run:
ssh
If SSH commands are unavailable, install the OpenSSH client:
- Go to Settings > Apps > Optional Features.
- Search for OpenSSH Client and install it.
Step 2: Use SCP for File Transfers
To upload a file to AlmaLinux:
scp C:\path\to\file.txt username@server-ip:/remote/directory/
To download a file from AlmaLinux:
scp username@server-ip:/remote/directory/file.txt C:\local\path\
Advantages
- No additional software required.
- Familiar syntax for users of Unix-based systems.
5. Method 4: Using FileZilla
FileZilla is a graphical SFTP client supporting SSH file transfers.
Step 1: Install FileZilla**
- Download FileZilla from the official website.
- Install it on your Windows system.
Step 2: Configure the Connection**
Open FileZilla and go to File > Site Manager.
Create a new site with the following details:
- Protocol: SFTP - SSH File Transfer Protocol.
- Host: AlmaLinux server’s IP address.
- Port: 22.
- Logon Type: Normal or Key File.
- User: AlmaLinux username.
- Password: Password or path to your private SSH key.
Click Connect to access your AlmaLinux server.
Step 3: Transfer Files
- Use the drag-and-drop interface to transfer files between Windows and AlmaLinux.
- Monitor transfer progress in the FileZilla transfer queue.
6. Best Practices for Secure File Transfers
Use Strong Passwords: Ensure all accounts use complex, unique passwords.
Enable SSH Key Authentication: Replace password-based authentication with SSH keys for enhanced security.
Limit SSH Access: Restrict SSH access to specific IP addresses.
sudo firewall-cmd --add-rich-rule='rule family="ipv4" source address="192.168.1.100" service name="ssh" accept' --permanent sudo firewall-cmd --reload
Change the Default SSH Port: Reduce exposure to brute-force attacks by using a non-standard port.
7. Troubleshooting Common Issues
Connection Timeout:
- Verify network connectivity with
ping server-ip
. - Check that port 22 is open on the server firewall.
- Verify network connectivity with
Authentication Failures:
- Ensure the correct username and password are used.
- If using keys, confirm the key pair matches and permissions are set properly.
Transfer Interruptions:
Use
rsync
for large files to resume transfers automatically:rsync -avz -e ssh C:\path\to\file.txt username@server-ip:/remote/directory/
Conclusion
Transferring files between Windows and AlmaLinux using SSH ensures secure and efficient communication. With tools like WinSCP, PuTTY, FileZilla, or native SCP commands, you can choose a method that best suits your workflow. By following the steps and best practices outlined in this guide, you’ll be able to perform secure file transfers confidently.
6 - How to Set Up SSH Key Pair Authentication on AlmaLinux
Secure Shell (SSH) is an indispensable tool for secure remote server management. While password-based authentication is straightforward, it has inherent vulnerabilities. SSH key pair authentication provides a more secure and convenient alternative. This guide will walk you through setting up SSH key pair authentication on AlmaLinux, improving your server’s security while simplifying your login process.
1. What is SSH Key Pair Authentication?
SSH key pair authentication replaces traditional password-based login with cryptographic keys. It involves two keys:
- Public Key: Stored on the server and shared with others.
- Private Key: Kept securely on the client system. Never share this key.
The client proves its identity by using the private key, and the server validates it against the stored public key. This method offers:
- Stronger security compared to passwords.
- Resistance to brute-force attacks.
- The ability to disable password logins entirely.
2. Prerequisites
Before configuring SSH key authentication:
- A running AlmaLinux server with SSH enabled.
- Administrative access to the server (root or sudo user).
- SSH installed on the client system (Linux, macOS, or Windows with OpenSSH or tools like PuTTY).
3. Step-by-Step Guide to Setting Up SSH Key Pair Authentication
Step 1: Generate an SSH Key Pair
On your local machine, generate an SSH key pair using the following command:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
-t rsa
: Specifies the RSA algorithm.-b 4096
: Generates a 4096-bit key for enhanced security.-C "your_email@example.com"
: Adds a comment to the key (optional).
Follow the prompts:
- Specify a file to save the key pair (default:
~/.ssh/id_rsa
). - (Optional) Set a passphrase for added security. Press Enter to skip.
This creates two files:
- Private Key:
~/.ssh/id_rsa
(keep this secure). - Public Key:
~/.ssh/id_rsa.pub
(shareable).
Step 2: Copy the Public Key to the AlmaLinux Server
To transfer the public key to the server, use:
ssh-copy-id username@server-ip
Replace:
username
with your AlmaLinux username.server-ip
with your server’s IP address.
This command:
- Appends the public key to the
~/.ssh/authorized_keys
file on the server. - Sets the correct permissions for the
.ssh
directory and theauthorized_keys
file.
Alternatively, manually copy the key:
Display the public key:
cat ~/.ssh/id_rsa.pub
On the server, paste it into the
~/.ssh/authorized_keys
file:echo "your-public-key-content" >> ~/.ssh/authorized_keys
Step 3: Configure Permissions on the Server
Ensure the correct permissions for the .ssh
directory and the authorized_keys
file:
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
Step 4: Test the Key-Based Authentication
From your local machine, connect to the server using:
ssh username@server-ip
If configured correctly, you won’t be prompted for a password. If a passphrase was set during key generation, you’ll be asked to enter it.
4. Enhancing Security with SSH Keys
1. Disable Password Authentication
Once key-based authentication works, disable password login to prevent brute-force attacks:
Open the SSH configuration file on the server:
sudo nano /etc/ssh/sshd_config
Find and set the following options:
PasswordAuthentication no ChallengeResponseAuthentication no
Restart the SSH service:
sudo systemctl restart sshd
2. Use SSH Agent for Key Management
To avoid repeatedly entering your passphrase, use the SSH agent:
ssh-add ~/.ssh/id_rsa
The agent stores the private key in memory, allowing seamless connections during your session.
3. Restrict Access to Specific IPs
Restrict SSH access to trusted IPs using the firewall:
sudo firewall-cmd --add-rich-rule='rule family="ipv4" source address="192.168.1.100" service name="ssh" accept' --permanent
sudo firewall-cmd --reload
4. Configure Two-Factor Authentication (Optional)
For added security, set up two-factor authentication (2FA) with SSH key-based login.
5. Troubleshooting Common Issues
Key-Based Authentication Fails:
- Verify the public key is correctly added to
~/.ssh/authorized_keys
. - Check permissions on the
.ssh
directory andauthorized_keys
file.
- Verify the public key is correctly added to
Connection Refused:
Ensure the SSH service is running:
sudo systemctl status sshd
Check the firewall rules to allow SSH.
Passphrase Issues:
Use the SSH agent to cache the passphrase:
ssh-add
Debugging: Use the
-v
option for verbose output:ssh -v username@server-ip
6. Benefits of SSH Key Authentication
- Enhanced Security: Stronger than passwords and resistant to brute-force attacks.
- Convenience: Once set up, logging in is quick and seamless.
- Scalability: Ideal for managing multiple servers with centralized keys.
Conclusion
SSH key pair authentication is a must-have for anyone managing servers on AlmaLinux. It not only enhances security but also simplifies the login process, saving time and effort. By following this guide, you can confidently transition from password-based authentication to a more secure and efficient SSH key-based setup.
Let me know if you need help with additional configurations or troubleshooting!
7 - How to Set Up SFTP-only with Chroot on AlmaLinux
Secure File Transfer Protocol (SFTP) is a secure way to transfer files over a network, leveraging SSH for encryption and authentication. Setting up an SFTP-only environment with Chroot enhances security by restricting users to specific directories and preventing them from accessing sensitive areas of the server. This guide will walk you through configuring SFTP-only access with Chroot on AlmaLinux, ensuring a secure and isolated file transfer environment.
1. What is SFTP and Chroot?
SFTP
SFTP is a secure file transfer protocol that uses SSH to encrypt communications. Unlike FTP, which transfers data in plaintext, SFTP ensures that files and credentials are protected during transmission.
Chroot
Chroot, short for “change root,” confines a user or process to a specific directory, creating a “jail” environment. When a user logs in, they can only access their designated directory and its subdirectories, effectively isolating them from the rest of the system.
2. Prerequisites
Before setting up SFTP with Chroot, ensure the following:
- AlmaLinux Server: A running instance with administrative privileges.
- OpenSSH Installed: Verify that the SSH server is installed and running:
sudo dnf install openssh-server -y sudo systemctl start sshd sudo systemctl enable sshd
- User Accounts: Create or identify users who will have SFTP access.
3. Step-by-Step Setup
Step 1: Install and Configure SSH
Ensure OpenSSH is installed and up-to-date:
sudo dnf update -y
sudo dnf install openssh-server -y
Step 2: Create the SFTP Group
Create a dedicated group for SFTP users:
sudo groupadd sftpusers
Step 3: Create SFTP-Only Users
Create a user and assign them to the SFTP group:
sudo useradd -m -s /sbin/nologin -G sftpusers sftpuser
-m
: Creates a home directory for the user.-s /sbin/nologin
: Prevents SSH shell access.-G sftpusers
: Adds the user to the SFTP group.
Set a password for the user:
sudo passwd sftpuser
Step 4: Configure the SSH Server for SFTP
Edit the SSH server configuration file:
sudo nano /etc/ssh/sshd_config
Add or modify the following lines at the end of the file:
# SFTP-only Configuration
Match Group sftpusers
ChrootDirectory %h
ForceCommand internal-sftp
AllowTcpForwarding no
X11Forwarding no
Match Group sftpusers
: Applies the rules to the SFTP group.ChrootDirectory %h
: Restricts users to their home directory (%h
represents the user’s home directory).ForceCommand internal-sftp
: Restricts users to SFTP-only access.AllowTcpForwarding no
andX11Forwarding no
: Disable unnecessary features for added security.
Save and close the file.
Step 5: Set Permissions on User Directories
Set the ownership and permissions for the Chroot environment:
sudo chown root:root /home/sftpuser
sudo chmod 755 /home/sftpuser
Create a subdirectory for file storage:
sudo mkdir /home/sftpuser/uploads
sudo chown sftpuser:sftpusers /home/sftpuser/uploads
This ensures that the user can upload files only within the designated uploads
directory.
Step 6: Restart the SSH Service
Apply the changes by restarting the SSH service:
sudo systemctl restart sshd
4. Testing the Configuration
Connect via SFTP: From a client machine, connect to the server using an SFTP client:
sftp sftpuser@server-ip
Verify Access Restrictions:
- Ensure the user can only access the
uploads
directory and cannot navigate outside their Chroot environment. - Attempting SSH shell access should result in a “permission denied” error.
- Ensure the user can only access the
5. Advanced Configurations
1. Limit File Upload Sizes
To limit upload sizes, modify the user’s shell limits:
sudo nano /etc/security/limits.conf
Add the following lines:
sftpuser hard fsize 10485760 # 10MB limit
2. Enable Logging for SFTP Sessions
Enable logging to track user activities:
- Edit the SSH configuration file to include:
Subsystem sftp /usr/libexec/openssh/sftp-server -l INFO
- Restart SSH:
sudo systemctl restart sshd
Logs will be available in /var/log/secure
.
6. Troubleshooting Common Issues
SFTP Login Fails:
- Verify the user’s home directory ownership:
sudo chown root:root /home/sftpuser
- Check for typos in
/etc/ssh/sshd_config
.
- Verify the user’s home directory ownership:
Permission Denied for File Uploads: Ensure the
uploads
directory is writable by the user:sudo chmod 755 /home/sftpuser/uploads sudo chown sftpuser:sftpusers /home/sftpuser/uploads
ChrootDirectory Error: Verify that the Chroot directory permissions meet SSH requirements:
sudo chmod 755 /home/sftpuser sudo chown root:root /home/sftpuser
7. Security Best Practices
- Restrict User Access: Ensure users are confined to their designated directories and have minimal permissions.
- Enable Two-Factor Authentication (2FA): Add an extra layer of security by enabling 2FA for SFTP users.
- Monitor Logs Regularly:
Review
/var/log/secure
for suspicious activities. - Use a Non-Standard SSH Port:
Change the default SSH port in
/etc/ssh/sshd_config
to reduce automated attacks:Port 2222
Conclusion
Configuring SFTP-only access with Chroot on AlmaLinux is a powerful way to secure your server and ensure users can only access their designated directories. By following this guide, you can set up a robust file transfer environment that prioritizes security and usability. Implementing advanced configurations and adhering to security best practices will further enhance your server’s protection.
8 - How to Use SSH-Agent on AlmaLinux
SSH-Agent is a powerful tool that simplifies secure access to remote systems by managing your SSH keys effectively. If you’re using AlmaLinux, a popular CentOS alternative with a focus on stability and enterprise readiness, setting up and using SSH-Agent can significantly enhance your workflow. In this guide, we’ll walk you through the steps to install, configure, and use SSH-Agent on AlmaLinux.
What Is SSH-Agent?
SSH-Agent is a background program that holds your private SSH keys in memory, so you don’t need to repeatedly enter your passphrase when connecting to remote servers. This utility is especially beneficial for system administrators, developers, and anyone managing multiple SSH connections daily.
Some key benefits include:
- Convenience: Automates authentication without compromising security.
- Security: Keeps private keys encrypted in memory rather than exposed on disk.
- Efficiency: Speeds up workflows, particularly when using automation tools or managing multiple servers.
Step-by-Step Guide to Using SSH-Agent on AlmaLinux
Below, we’ll guide you through the process of setting up and using SSH-Agent on AlmaLinux, ensuring your setup is secure and efficient.
1. Install SSH and Check Dependencies
Most AlmaLinux installations come with SSH pre-installed. However, it’s good practice to verify its presence and update it if necessary.
Check if SSH is installed:
ssh -V
This command should return the version of OpenSSH installed. If not, install the SSH package:
sudo dnf install openssh-clients
Ensure AlmaLinux is up-to-date: Regular updates ensure security and compatibility.
sudo dnf update
2. Generate an SSH Key (If You Don’t Have One)
Before using SSH-Agent, you’ll need a private-public key pair. If you already have one, you can skip this step.
Create a new SSH key pair:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
This command generates a 4096-bit RSA key. You can substitute
"your_email@example.com"
with your email address for identification.Follow the prompts:
- Specify a file to save the key (or press Enter for the default location,
~/.ssh/id_rsa
). - Enter a strong passphrase when prompted.
- Specify a file to save the key (or press Enter for the default location,
Check your keys: Verify the keys are in the default directory:
ls ~/.ssh
3. Start and Add Keys to SSH-Agent
Now that your keys are ready, you can initialize SSH-Agent and load your keys.
Start SSH-Agent: In most cases, SSH-Agent is started automatically. To manually start it:
eval "$(ssh-agent -s)"
This command will output the process ID of the running SSH-Agent.
Add your private key to SSH-Agent:
ssh-add ~/.ssh/id_rsa
Enter your passphrase when prompted. SSH-Agent will now store your decrypted private key in memory.
Verify keys added: Use the following command to confirm your keys are loaded:
ssh-add -l
4. Configure Automatic SSH-Agent Startup
To avoid manually starting SSH-Agent each time, you can configure it to launch automatically upon login.
Modify your shell configuration file: Depending on your shell (e.g., Bash), edit the corresponding configuration file (
~/.bashrc
,~/.zshrc
, etc.):nano ~/.bashrc
Add the following lines:
# Start SSH-Agent if not running if [ -z "$SSH_AUTH_SOCK" ]; then eval "$(ssh-agent -s)" fi
Reload the shell configuration:
source ~/.bashrc
This setup ensures SSH-Agent is always available without manual intervention.
5. Use SSH-Agent with Remote Connections
With SSH-Agent running, you can connect to remote servers seamlessly.
Ensure your public key is added to the remote server: Copy your public key (
~/.ssh/id_rsa.pub
) to the remote server:ssh-copy-id user@remote-server
Replace
user@remote-server
with the appropriate username and server address.Connect to the server:
ssh user@remote-server
SSH-Agent handles the authentication using the loaded keys.
6. Security Best Practices
While SSH-Agent is convenient, maintaining a secure setup is crucial.
Use strong passphrases: Always protect your private key with a passphrase.
Set key expiration: Use
ssh-add -t
to set a timeout for your keys:ssh-add -t 3600 ~/.ssh/id_rsa
This example unloads the key after one hour.
Limit agent forwarding: Avoid agent forwarding (
-A
flag) unless absolutely necessary, as it can expose your keys to compromised servers.
Troubleshooting SSH-Agent on AlmaLinux
Issue 1: SSH-Agent not running
Ensure the agent is started with:
eval "$(ssh-agent -s)"
Issue 2: Keys not persisting after reboot
- Check your
~/.bashrc
or equivalent configuration file for the correct startup commands.
Issue 3: Permission denied errors
Ensure correct permissions for your
~/.ssh
directory:chmod 700 ~/.ssh chmod 600 ~/.ssh/id_rsa
Conclusion
SSH-Agent is a must-have utility for managing SSH keys efficiently, and its integration with AlmaLinux is straightforward. By following the steps in this guide, you can streamline secure connections, automate authentication, and enhance your productivity. Whether you’re managing servers or developing applications, SSH-Agent ensures a secure and hassle-free experience on AlmaLinux.
9 - How to Use SSHPass on AlmaLinux
SSH is a cornerstone of secure communication for Linux users, enabling encrypted access to remote systems. However, there are scenarios where automated scripts require password-based SSH logins without manual intervention. SSHPass is a utility designed for such cases, allowing users to pass passwords directly through a command-line interface.
In this guide, we’ll explore how to install, configure, and use SSHPass on AlmaLinux, a robust enterprise Linux distribution based on CentOS.
What Is SSHPass?
SSHPass is a simple, lightweight tool that enables password-based SSH logins from the command line, bypassing the need to manually input a password. This utility is especially useful for:
- Automation: Running scripts that require SSH or SCP commands without user input.
- Legacy systems: Interfacing with systems that only support password authentication.
However, SSHPass should be used cautiously, as storing passwords in scripts or commands can expose security vulnerabilities.
Why Use SSHPass?
SSHPass is ideal for:
- Automating repetitive SSH tasks: Avoid manually entering passwords for each connection.
- Legacy setups: Working with servers that lack public-key authentication.
- Quick testing: Streamlining temporary setups or environments.
That said, it’s always recommended to prioritize key-based authentication over password-based methods wherever possible.
Step-by-Step Guide to Using SSHPass on AlmaLinux
Prerequisites
Before starting, ensure:
- AlmaLinux is installed and updated.
- You have administrative privileges (
sudo
access). - You have SSH access to the target system.
1. Installing SSHPass on AlmaLinux
SSHPass is not included in AlmaLinux’s default repositories due to security considerations. However, it can be installed from alternative repositories or by compiling from source.
Option 1: Install from the EPEL Repository
Enable EPEL (Extra Packages for Enterprise Linux):
sudo dnf install epel-release
Install SSHPass:
sudo dnf install sshpass
Option 2: Compile from Source
If SSHPass is unavailable in your configured repositories:
Install build tools:
sudo dnf groupinstall "Development Tools" sudo dnf install wget
Download the source code:
wget https://sourceforge.net/projects/sshpass/files/latest/download -O sshpass.tar.gz
Extract the archive:
tar -xvzf sshpass.tar.gz cd sshpass-*
Compile and install SSHPass:
./configure make sudo make install
Verify the installation by running:
sshpass -V
2. Basic Usage of SSHPass
SSHPass requires the password to be passed as part of the command. Below are common use cases.
Example 1: Basic SSH Connection
To connect to a remote server using a password:
sshpass -p 'your_password' ssh user@remote-server
Replace:
your_password
with the remote server’s password.user@remote-server
with the appropriate username and hostname/IP.
Example 2: Using SCP for File Transfers
SSHPass simplifies file transfers via SCP:
sshpass -p 'your_password' scp local_file user@remote-server:/remote/directory/
Example 3: Reading Passwords from a File
For enhanced security, avoid directly typing passwords in the command line. Store the password in a file:
Create a file with the password:
echo "your_password" > password.txt
Use SSHPass to read the password:
sshpass -f password.txt ssh user@remote-server
Ensure the password file is secure:
chmod 600 password.txt
3. Automating SSH Tasks with SSHPass
SSHPass is particularly useful for automating tasks in scripts. Here’s an example:
Example: Automate Remote Commands
Create a script to execute commands on a remote server:
#!/bin/bash
PASSWORD="your_password"
REMOTE_USER="user"
REMOTE_SERVER="remote-server"
COMMAND="ls -la"
sshpass -p "$PASSWORD" ssh "$REMOTE_USER@$REMOTE_SERVER" "$COMMAND"
Save the script and execute it:
bash automate_ssh.sh
4. Security Considerations
While SSHPass is convenient, it comes with inherent security risks. Follow these best practices to mitigate risks:
- Avoid hardcoding passwords: Use environment variables or secure storage solutions.
- Limit permissions: Restrict access to scripts or files containing sensitive data.
- Use key-based authentication: Whenever possible, switch to SSH key pairs for a more secure and scalable solution.
- Secure password files: Use restrictive permissions (
chmod 600
) to protect password files.
5. Troubleshooting SSHPass
Issue 1: “Permission denied”
Ensure the remote server allows password authentication. Edit the SSH server configuration (
/etc/ssh/sshd_config
) if needed:PasswordAuthentication yes
Restart the SSH service:
sudo systemctl restart sshd
Issue 2: SSHPass not found
- Confirm SSHPass is installed correctly. Reinstall or compile from source if necessary.
Issue 3: Security warnings
- SSHPass may trigger warnings related to insecure password handling. These can be ignored if security practices are followed.
Alternative Tools to SSHPass
For more secure or feature-rich alternatives:
- Expect: Automates interactions with command-line programs.
- Ansible: Automates configuration management and SSH tasks at scale.
- Keychain: Manages SSH keys securely.
Conclusion
SSHPass is a versatile tool for scenarios where password-based SSH access is unavoidable, such as automation tasks or legacy systems. With this guide, you can confidently install and use SSHPass on AlmaLinux while adhering to security best practices.
While SSHPass offers convenience, always aim to transition to more secure authentication methods, such as SSH keys, to protect your systems and data in the long run.
Feel free to share your use cases or additional tips in the comments below! Happy automating!
10 - How to Use SSHFS on AlmaLinux
Secure Shell Filesystem (SSHFS) is a powerful utility that enables users to mount and interact with remote file systems securely over an SSH connection. With SSHFS, you can treat a remote file system as if it were local, allowing seamless access to files and directories on remote servers. This functionality is particularly useful for system administrators, developers, and anyone working with distributed systems.
In this guide, we’ll walk you through the steps to install, configure, and use SSHFS on AlmaLinux, a stable and secure Linux distribution built for enterprise environments.
What Is SSHFS?
SSHFS is a FUSE (Filesystem in Userspace) implementation that leverages the SSH protocol to mount remote file systems. It provides a secure and convenient way to interact with files on a remote server, making it a great tool for tasks such as:
- File Management: Simplify remote file access without needing SCP or FTP transfers.
- Collaboration: Share directories across systems in real-time.
- Development: Edit and test files directly on remote servers.
Why Use SSHFS?
SSHFS offers several advantages:
- Ease of Use: Minimal setup and no need for additional server-side software beyond SSH.
- Security: Built on the robust encryption of SSH.
- Convenience: Provides a local-like file system interface for remote resources.
- Portability: Works across various Linux distributions and other operating systems.
Step-by-Step Guide to Using SSHFS on AlmaLinux
Prerequisites
Before you start:
Ensure AlmaLinux is installed and updated:
sudo dnf update
Have SSH access to a remote server.
Install required dependencies (explained below).
1. Install SSHFS on AlmaLinux
SSHFS is part of the fuse-sshfs
package, which is available in the default AlmaLinux repositories.
Install the SSHFS package:
sudo dnf install fuse-sshfs
Verify the installation: Check the installed version:
sshfs --version
This command should return the installed version, confirming SSHFS is ready for use.
2. Create a Mount Point for the Remote File System
A mount point is a local directory where the remote file system will appear.
Create a directory: Choose a location for the mount point. For example:
mkdir ~/remote-files
This directory will act as the access point for the remote file system.
3. Mount the Remote File System
Once SSHFS is installed, you can mount the remote file system using a simple command.
Basic Mount Command
Use the following syntax:
sshfs user@remote-server:/remote/directory ~/remote-files
Replace:
user
with your SSH username.remote-server
with the hostname or IP address of the server./remote/directory
with the path to the directory you want to mount.~/remote-files
with your local mount point.
Example: If your username is
admin
, the remote server’s IP is192.168.1.10
, and you want to mount/var/www
, the command would be:sshfs admin@192.168.1.10:/var/www ~/remote-files
Verify the mount: After running the command, list the contents of the local mount point:
ls ~/remote-files
You should see the contents of the remote directory.
4. Mount with Additional Options
SSHFS supports various options to customize the behavior of the mounted file system.
Example: Mount with Specific Permissions
To specify file and directory permissions, use:
sshfs -o uid=$(id -u) -o gid=$(id -g) user@remote-server:/remote/directory ~/remote-files
Example: Enable Caching
For better performance, enable caching with:
sshfs -o cache=yes user@remote-server:/remote/directory ~/remote-files
Example: Use a Specific SSH Key
If your SSH connection requires a custom private key:
sshfs -o IdentityFile=/path/to/private-key user@remote-server:/remote/directory ~/remote-files
5. Unmount the File System
When you’re done working with the remote file system, unmount it to release the connection.
Unmount the file system:
fusermount -u ~/remote-files
Verify unmounting: Check the mount point to ensure it’s empty:
ls ~/remote-files
6. Automate Mounting with fstab
For frequent use, you can automate the mounting process by adding the configuration to /etc/fstab
.
Step 1: Edit the fstab File
Open
/etc/fstab
in a text editor:sudo nano /etc/fstab
Add the following line:
user@remote-server:/remote/directory ~/remote-files fuse.sshfs defaults 0 0
Adjust the parameters for your setup.
Step 2: Test the Configuration
Unmount the file system if it’s already mounted:
fusermount -u ~/remote-files
Re-mount using
mount
:sudo mount -a
7. Troubleshooting Common Issues
Issue 1: “Permission Denied”
- Cause: SSH key authentication or password issues.
- Solution: Verify your SSH credentials and server permissions. Ensure password authentication is enabled on the server (
PasswordAuthentication yes
in/etc/ssh/sshd_config
).
Issue 2: “Transport Endpoint is Not Connected”
Cause: Network interruption or server timeout.
Solution: Unmount the file system and remount it:
fusermount -u ~/remote-files sshfs user@remote-server:/remote/directory ~/remote-files
Issue 3: “SSHFS Command Not Found”
Cause: SSHFS is not installed.
Solution: Reinstall SSHFS:
sudo dnf install fuse-sshfs
Benefits of Using SSHFS on AlmaLinux
- Security: SSHFS inherits the encryption and authentication features of SSH, ensuring safe file transfers.
- Ease of Access: No additional server-side setup is required beyond SSH.
- Integration: Works seamlessly with other Linux tools and file managers.
Conclusion
SSHFS is an excellent tool for securely accessing and managing remote file systems on AlmaLinux. By following this guide, you can install, configure, and use SSHFS effectively for your tasks. Whether you’re managing remote servers, collaborating with teams, or streamlining your development environment, SSHFS provides a reliable and secure solution.
If you have any tips or experiences with SSHFS, feel free to share them in the comments below. Happy mounting!
11 - How to Use Port Forwarding on AlmaLinux
Port forwarding is an essential networking technique that redirects network traffic from one port or address to another. It allows users to access services on a private network from an external network, enhancing connectivity and enabling secure remote access. For AlmaLinux users, understanding and implementing port forwarding can streamline tasks such as accessing a remote server, running a web application, or securely transferring files.
In this guide, we’ll explore the concept of port forwarding, its use cases, and how to configure it on AlmaLinux.
What Is Port Forwarding?
Port forwarding redirects incoming traffic on a specific port to another port or IP address. This technique is commonly used to:
- Expose services: Make an internal service accessible from the internet.
- Improve security: Restrict access to specific IPs or routes.
- Support NAT environments: Allow external users to reach internal servers behind a router.
Types of Port Forwarding
- Local Port Forwarding: Redirects traffic from a local port to a remote server.
- Remote Port Forwarding: Redirects traffic from a remote server to a local machine.
- Dynamic Port Forwarding: Creates a SOCKS proxy for flexible routing through an intermediary server.
Prerequisites for Port Forwarding on AlmaLinux
Before configuring port forwarding, ensure:
- Administrator privileges: You’ll need root or
sudo
access. - SSH installed: For secure port forwarding via SSH.
- Firewall configuration: AlmaLinux uses
firewalld
by default, so ensure you have access to manage it.
1. Local Port Forwarding
Local port forwarding redirects traffic from your local machine to a remote server. This is useful for accessing services on a remote server through an SSH tunnel.
Example Use Case: Access a Remote Web Server Locally
Run the SSH command:
ssh -L 8080:remote-server:80 user@remote-server
Explanation:
-L
: Specifies local port forwarding.8080
: The local port on your machine.remote-server
: The target server’s hostname or IP address.80
: The remote port (e.g., HTTP).user
: The SSH username.
Access the service: Open a web browser and navigate to
http://localhost:8080
. Traffic will be forwarded to the remote server on port 80.
2. Remote Port Forwarding
Remote port forwarding allows a remote server to access your local services. This is helpful when you need to expose a local application to an external network.
Example Use Case: Expose a Local Web Server to a Remote User
Run the SSH command:
ssh -R 9090:localhost:3000 user@remote-server
Explanation:
-R
: Specifies remote port forwarding.9090
: The remote server’s port.localhost:3000
: The local service you want to expose (e.g., a web server on port 3000).user
: The SSH username.
Access the service: Users on the remote server can access the service by navigating to
http://remote-server:9090
.
3. Dynamic Port Forwarding
Dynamic port forwarding creates a SOCKS proxy that routes traffic through an intermediary server. This is ideal for secure browsing or bypassing network restrictions.
Example Use Case: Create a SOCKS Proxy
Run the SSH command:
ssh -D 1080 user@remote-server
Explanation:
-D
: Specifies dynamic port forwarding.1080
: The local port for the SOCKS proxy.user
: The SSH username.
Configure your browser or application: Set the SOCKS proxy to
localhost:1080
.
4. Port Forwarding with Firewalld
If you’re not using SSH or need persistent port forwarding, you can configure it with AlmaLinux’s firewalld
.
Example: Forward Port 8080 to Port 80
Enable port forwarding in
firewalld
:sudo firewall-cmd --add-forward-port=port=8080:proto=tcp:toport=80
Make the rule persistent:
sudo firewall-cmd --runtime-to-permanent
Verify the configuration:
sudo firewall-cmd --list-forward-ports
5. Port Forwarding with iptables
For advanced users, iptables
provides granular control over port forwarding rules.
Example: Forward Traffic on Port 8080 to 80
Add an
iptables
rule:sudo iptables -t nat -A PREROUTING -p tcp --dport 8080 -j REDIRECT --to-port 80
Save the rule: To make the rule persistent across reboots, install
iptables-services
:sudo dnf install iptables-services sudo service iptables save
6. Testing Port Forwarding
After configuring port forwarding, test the setup to ensure it works as expected.
Check open ports: Use
netstat
orss
to verify listening ports:ss -tuln
Test connectivity: Use
telnet
orcurl
to test the forwarded ports:curl http://localhost:8080
Security Considerations for Port Forwarding
While port forwarding is a powerful tool, it comes with potential risks. Follow these best practices:
- Restrict access: Limit forwarding to specific IP addresses or ranges.
- Use encryption: Always use SSH for secure forwarding.
- Close unused ports: Regularly audit and close unnecessary ports to minimize attack surfaces.
- Monitor traffic: Use monitoring tools like
tcpdump
orWireshark
to track forwarded traffic.
Troubleshooting Common Issues
Issue 1: “Permission Denied”
- Ensure the user has the necessary SSH permissions and that the target port is open on the remote server.
Issue 2: Port Already in Use
Check for conflicting services using the port:
sudo ss -tuln | grep 8080
Stop the conflicting service or use a different port.
Issue 3: Firewall Blocking Traffic
Verify firewall rules on both local and remote systems:
sudo firewall-cmd --list-all
Real-World Applications of Port Forwarding
- Web Development:
- Test web applications locally while exposing them to collaborators remotely.
- Database Access:
- Connect to a remote database securely without exposing it to the public internet.
- Remote Desktop:
- Access a remote desktop environment via SSH tunnels.
- Gaming Servers:
- Host game servers behind a NAT firewall and make them accessible externally.
Conclusion
Port forwarding is an invaluable tool for anyone working with networks or servers. Whether you’re using it for development, troubleshooting, or managing remote systems, AlmaLinux provides the flexibility and tools to configure port forwarding efficiently.
By following this guide, you can implement and secure port forwarding to suit your specific needs. If you’ve found this post helpful or have additional tips, feel free to share them in the comments below. Happy networking!
12 - How to Use Parallel SSH on AlmaLinux
Managing multiple servers simultaneously can be a daunting task, especially when executing repetitive commands or deploying updates. Parallel SSH (PSSH) is a powerful tool that simplifies this process by enabling you to run commands on multiple remote systems concurrently. If you’re using AlmaLinux, a secure and enterprise-grade Linux distribution, learning to use Parallel SSH can greatly enhance your efficiency and productivity.
In this guide, we’ll explore what Parallel SSH is, its benefits, and how to install and use it effectively on AlmaLinux.
What Is Parallel SSH?
Parallel SSH is a command-line tool that allows users to execute commands, copy files, and manage multiple servers simultaneously. It is part of the PSSH suite, which includes additional utilities like:
pssh
: Run commands in parallel on multiple servers.pscp
: Copy files to multiple servers.pslurp
: Fetch files from multiple servers.pnuke
: Kill processes on multiple servers.
Benefits of Using Parallel SSH
PSSH is particularly useful in scenarios like:
- System Administration: Automate administrative tasks across multiple servers.
- DevOps: Streamline deployment processes for applications or updates.
- Cluster Management: Manage high-performance computing (HPC) clusters.
- Consistency: Ensure the same command or script runs uniformly across all servers.
Prerequisites
Before diving into Parallel SSH, ensure the following:
AlmaLinux is installed and updated:
sudo dnf update
You have SSH access to all target servers.
Passwordless SSH authentication is set up for seamless connectivity.
Step-by-Step Guide to Using Parallel SSH on AlmaLinux
1. Install Parallel SSH
Parallel SSH is not included in the default AlmaLinux repositories, but you can install it using Python’s package manager, pip
.
Step 1: Install Python and Pip
Ensure Python is installed:
sudo dnf install python3 python3-pip
Verify the installation:
python3 --version pip3 --version
Step 2: Install PSSH
Install Parallel SSH via
pip
:pip3 install parallel-ssh
Verify the installation:
pssh --version
2. Set Up Passwordless SSH Authentication
Passwordless SSH authentication is crucial for PSSH to work seamlessly.
Generate an SSH key pair:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
Copy the public key to each target server:
ssh-copy-id user@remote-server
Replace
user@remote-server
with the appropriate username and hostname/IP for each server.Test the connection:
ssh user@remote-server
Ensure no password is required for login.
3. Create a Hosts File
Parallel SSH requires a list of target servers, provided in a hosts file.
Create the hosts file:
nano ~/hosts.txt
Add server details: Add one server per line in the following format:
user@server1 user@server2 user@server3
Save the file and exit.
4. Run Commands Using PSSH
With the hosts file ready, you can start using PSSH to run commands across multiple servers.
Example 1: Execute a Simple Command
Run the uptime
command on all servers:
pssh -h ~/hosts.txt -i "uptime"
Explanation:
-h
: Specifies the hosts file.-i
: Outputs results interactively.
Example 2: Run a Command as Root
If the command requires sudo
, use the -A
option to enable interactive password prompts:
pssh -h ~/hosts.txt -A -i "sudo apt update"
Example 3: Use a Custom SSH Key
Specify a custom SSH key with the -x
option:
pssh -h ~/hosts.txt -x "-i /path/to/private-key" -i "uptime"
5. Transfer Files Using PSSH
Parallel SCP (PSCP) allows you to copy files to multiple servers simultaneously.
Example: Copy a File to All Servers
pscp -h ~/hosts.txt local-file /remote/destination/path
Explanation:
local-file
: Path to the file on your local machine./remote/destination/path
: Destination path on the remote servers.
Example: Retrieve Files from All Servers
Use pslurp
to download files:
pslurp -h ~/hosts.txt /remote/source/path local-destination/
6. Advanced Options and Use Cases
Run Commands with a Timeout
Set a timeout to terminate long-running commands:
pssh -h ~/hosts.txt -t 30 -i "ping -c 4 google.com"
Parallel Execution Limit
Limit the number of simultaneous connections:
pssh -h ~/hosts.txt -p 5 -i "uptime"
This example processes only five servers at a time.
Log Command Output
Save the output of each server to a log file:
pssh -h ~/hosts.txt -o /path/to/logs "df -h"
7. Best Practices for Using Parallel SSH
To maximize the effectiveness of PSSH:
- Use descriptive host files: Maintain separate host files for different server groups.
- Test commands: Run commands on a single server before executing them across all systems.
- Monitor output: Use the logging feature to debug errors.
- Ensure uptime: Verify all target servers are online before running commands.
8. Troubleshooting Common Issues
Issue 1: “Permission Denied”
- Cause: SSH keys are not set up correctly.
- Solution: Reconfigure passwordless SSH authentication.
Issue 2: “Command Not Found”
- Cause: Target servers lack the required command or software.
- Solution: Ensure the command is available on all servers.
Issue 3: “Connection Refused”
Cause: Firewall or network issues.
Solution: Verify SSH access and ensure the
sshd
service is running:sudo systemctl status sshd
Real-World Applications of Parallel SSH
- System Updates:
- Simultaneously update all servers in a cluster.
- Application Deployment:
- Deploy code or restart services across multiple servers.
- Data Collection:
- Fetch logs or performance metrics from distributed systems.
- Testing Environments:
- Apply configuration changes to multiple test servers.
Conclusion
Parallel SSH is an indispensable tool for managing multiple servers efficiently. By enabling command execution, file transfers, and process management across systems simultaneously, PSSH simplifies complex administrative tasks. AlmaLinux users, especially system administrators and DevOps professionals, can greatly benefit from incorporating PSSH into their workflows.
With this guide, you’re equipped to install, configure, and use Parallel SSH on AlmaLinux. Whether you’re updating servers, deploying applications, or managing clusters, PSSH offers a powerful, scalable solution to streamline your operations.
If you’ve used Parallel SSH or have additional tips, feel free to share them in the comments below. Happy automating!