ssh-wrap 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. #!/usr/bin/env bash
  2. # Usage: ./ssh-wrap user@host
  3. # Capture SSH output
  4. output=$(ssh "$@" 2>&1)
  5. # Print the SSH output so user sees what happened
  6. echo "$output"
  7. # Check if the known_hosts warning appears
  8. if echo "$output" | grep -q "REMOTE HOST IDENTIFICATION HAS CHANGED"; then
  9. echo "It appears the host key has changed or a man-in-the-middle attack is possible."
  10. # Extract the known_hosts file and line number from the "Offending RSA key in ..." line
  11. # The line format typically is: "Offending RSA key in /path/to/known_hosts:line"
  12. # We'll use awk to split by ':' and space to grab the file and line number
  13. if offending_info=$(echo "$output" | grep "Offending RSA key in"); then
  14. KNOWN_HOSTS_FILE=$(echo "$offending_info" | awk '{print $5}' | cut -d: -f1)
  15. LINE_NUMBER=$(echo "$offending_info" | awk -F: '{print $NF}')
  16. echo "Offending key detected in: $KNOWN_HOSTS_FILE on line: $LINE_NUMBER"
  17. read -p "Would you like to remove this offending key line and re-attempt the SSH connection? [y/N]: " RESPONSE
  18. if [[ "$RESPONSE" =~ ^[Yy]$ ]]; then
  19. # Backup known_hosts
  20. cp "$KNOWN_HOSTS_FILE" "$KNOWN_HOSTS_FILE.bak"
  21. # Remove offending line
  22. sed -i "${LINE_NUMBER}d" "$KNOWN_HOSTS_FILE"
  23. echo "Offending key removed. Retrying SSH connection..."
  24. ssh "$@"
  25. else
  26. echo "Key was not removed. Exiting."
  27. fi
  28. else
  29. echo "Could not extract offending key information. Remove it manually if needed."
  30. fi
  31. fi