Created
November 28, 2024 17:13
-
-
Save amcchord/92b49773ed79ee819eddc71e04f2fa9f to your computer and use it in GitHub Desktop.
This little script automates setting up an SSH keypair
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Handy script for doing the keypair dance | |
# Exit on any error | |
set -e | |
# Function to display usage | |
usage() { | |
echo "Usage: $0 <remote_user> <remote_host>" | |
echo "Example: $0 john example.com" | |
exit 1 | |
} | |
# Function to check if SSH key already exists | |
check_ssh_key() { | |
if [[ -f ~/.ssh/id_rsa && -f ~/.ssh/id_rsa.pub ]]; then | |
return 0 | |
else | |
return 1 | |
fi | |
} | |
# Function to validate SSH connection | |
validate_ssh() { | |
local user=$1 | |
local host=$2 | |
if ! ssh -o BatchMode=yes -o ConnectTimeout=5 "${user}@${host}" exit 2>/dev/null; then | |
return 1 | |
fi | |
return 0 | |
} | |
# Check arguments | |
if [[ $# -ne 2 ]]; then | |
usage | |
fi | |
REMOTE_USER="$1" | |
REMOTE_HOST="$2" | |
# Create .ssh directory if it doesn't exist | |
mkdir -p ~/.ssh | |
chmod 700 ~/.ssh | |
# Generate SSH key if it doesn't exist | |
if ! check_ssh_key; then | |
echo "Generating new SSH key pair..." | |
ssh-keygen -t rsa -b 4096 -f ~/.ssh/id_rsa -N "" | |
if [[ $? -ne 0 ]]; then | |
echo "Error: Failed to generate SSH key pair" | |
exit 1 | |
fi | |
else | |
echo "SSH key pair already exists, continuing..." | |
fi | |
# Check if we can already connect without password | |
if validate_ssh "$REMOTE_USER" "$REMOTE_HOST"; then | |
echo "SSH key already set up and working!" | |
exit 0 | |
fi | |
# Copy SSH key | |
echo "Copying SSH key to remote host..." | |
echo "You will be prompted for the password twice:" | |
echo "1. First to create the .ssh directory (if it doesn't exist)" | |
echo "2. Then to copy the SSH key" | |
# Create remote .ssh directory and set permissions | |
ssh "$REMOTE_USER@$REMOTE_HOST" ' | |
mkdir -p ~/.ssh | |
chmod 700 ~/.ssh | |
' | |
# Use ssh-copy-id to copy the key | |
ssh-copy-id -i ~/.ssh/id_rsa.pub "$REMOTE_USER@$REMOTE_HOST" | |
if [[ $? -ne 0 ]]; then | |
echo "Error: Failed to copy SSH key" | |
exit 1 | |
fi | |
# Verify the setup | |
echo "Verifying SSH key setup..." | |
if validate_ssh "$REMOTE_USER" "$REMOTE_HOST"; then | |
echo "Success! SSH key has been set up correctly." | |
echo "You can now SSH to ${REMOTE_USER}@${REMOTE_HOST} without a password." | |
else | |
echo "Error: SSH key setup verification failed" | |
exit 1 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment