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:
- Replace
<username>and<hostname>with your SSH username and hostname respectively. - Save the script to a file, for example,
ssh_debug.sh. - Make the script executable:
chmod +x ssh_debug.sh - Run the script:
sudo ./ssh_debug.sh
This script performs the following steps:
- Logs the current date and time.
- Checks the SSH server configuration file (
/etc/ssh/sshd_config). - Checks the UFW status and rules to ensure port 22 is allowed.
- Checks the SSH client configuration file (
~/.ssh/config). - Tests the SSH connection.
- Checks network settings by pinging the remote server and the gateway.
- Checks if the SSH service is running.
All output and log messages are saved to /var/log/ssh_connection_debug.log for further analysis.