Skip to main content

SSH Connection Closed by Unknown Port 65535

Here is a Bash script that checks for various issues related to the "SSH connection closed by unknown port 65535" error on a Raspberry Pi system with UFW (Uncomplicated Firewall). The script will log all the steps and their results to a log file for debugging purposes.


#!/bin/bash

# Define the log file
LOG_FILE="/var/log/ssh_connection_debug.log"

# Function to log messages
log_message() {
echo "$(date +'%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}

# Check SSH server configuration
log_message "Checking SSH server configuration..."
if [ -f /etc/ssh/sshd_config ]; then
sudo cat /etc/ssh/sshd_config | tee -a "$LOG_FILE"
else
log_message "SSH server configuration file not found."
fi

# Check UFW status and rules
log_message "Checking UFW status and rules..."
sudo ufw status | tee -a "$LOG_FILE"

# Check if SSH port (22) is allowed in UFW
log_message "Checking if SSH port (22) is allowed in UFW..."
sudo ufw status | grep "22/tcp" | tee -a "$LOG_FILE"
if [ $? -ne 0 ]; then
log_message "SSH port (22) is not allowed in UFW. Allowing it now..."
sudo ufw allow 22/tcp | tee -a "$LOG_FILE"
sudo ufw reload | tee -a "$LOG_FILE"
else
log_message "SSH port (22) is already allowed in UFW."
fi

# Check SSH client configuration
log_message "Checking SSH client configuration..."
if [ -f ~/.ssh/config ]; then
cat ~/.ssh/config | tee -a "$LOG_FILE"
else
log_message "SSH client configuration file not found."
fi

# Test SSH connection
log_message "Testing SSH connection..."
ssh -v <username>@<hostname> | tee -a "$LOG_FILE"

# Check network settings
log_message "Checking network settings..."
log_message "Pinging remote server..."
ping -c 4 <hostname> | tee -a "$LOG_FILE"

log_message "Pinging gateway..."
ping -c 4 $(ip route | grep default | awk '{print $3}') | tee -a "$LOG_FILE"

# Check if SSH service is running
log_message "Checking if SSH service is running..."
sudo systemctl status ssh | tee -a "$LOG_FILE"

# Finished
log_message "Finished troubleshooting SSH connection issues."

Instructions:

  1. Replace <username> and <hostname> with your SSH username and hostname respectively.
  2. Save the script to a file, for example, ssh_debug.sh.
  3. Make the script executable:
    chmod +x ssh_debug.sh
  4. Run the script:
    sudo ./ssh_debug.sh

This script performs the following steps:

  1. Logs the current date and time.
  2. Checks the SSH server configuration file (/etc/ssh/sshd_config).
  3. Checks the UFW status and rules to ensure port 22 is allowed.
  4. Checks the SSH client configuration file (~/.ssh/config).
  5. Tests the SSH connection.
  6. Checks network settings by pinging the remote server and the gateway.
  7. Checks if the SSH service is running.

All output and log messages are saved to /var/log/ssh_connection_debug.log for further analysis.