#!/bin/bash # SSH Recovery Script # Run this if the main setup script broke SSH set -euo pipefail RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' NC='\033[0m' log() { echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')] $1${NC}" } warn() { echo -e "${YELLOW}[WARNING] $1${NC}" } error() { echo -e "${RED}[ERROR] $1${NC}" } # Check if running as root if [[ $EUID -ne 0 ]]; then error "This script must be run as root" exit 1 fi echo -e "${YELLOW}=== SSH Recovery Script ===${NC}" echo "This script will help recover from broken SSH configuration." echo "" # List available backups if ls /etc/ssh/sshd_config.backup.* 1> /dev/null 2>&1; then echo "Available SSH configuration backups:" ls -la /etc/ssh/sshd_config.backup.* echo "" read -p "Restore from backup? (Y/n): " restore_choice if [[ ! "$restore_choice" =~ ^[Nn]$ ]]; then # Get the most recent backup latest_backup=$(ls -t /etc/ssh/sshd_config.backup.* | head -1) log "Restoring SSH configuration from: $latest_backup" cp "$latest_backup" /etc/ssh/sshd_config log "SSH configuration restored" fi else warn "No SSH configuration backups found" echo "Restoring default SSH configuration..." # Create a basic working SSH config cat > /etc/ssh/sshd_config << 'EOF' # Minimal working SSH configuration Port 22 PermitRootLogin no PasswordAuthentication yes PubkeyAuthentication yes AuthorizedKeysFile .ssh/authorized_keys PermitEmptyPasswords no ChallengeResponseAuthentication no UsePAM yes X11Forwarding no PrintMotd no AcceptEnv LANG LC_* Subsystem sftp /usr/lib/openssh/sftp-server EOF log "Basic SSH configuration created" fi # Test configuration log "Testing SSH configuration..." if sshd -t; then log "SSH configuration is valid" # Restart SSH service log "Restarting SSH service..." if systemctl restart sshd; then log "SSH service restarted successfully" # Check if service is running if systemctl is-active --quiet sshd; then echo "" echo -e "${GREEN}✓ SSH service is now running${NC}" echo -e "${YELLOW}You should now be able to connect via SSH${NC}" echo "" echo "Test connection with:" echo "ssh user@$(hostname -I | awk '{print $1}')" else error "SSH service is not active" fi else error "Failed to restart SSH service" fi else error "SSH configuration is still invalid" echo "Manual intervention required." fi echo "" echo "Current SSH status:" systemctl status sshd --no-pager -l