Skip to content

Instantly share code, notes, and snippets.

@ncatallo
Created May 8, 2025 10:48
Show Gist options
  • Save ncatallo/506fa173a30ad93f9268bbd0949da413 to your computer and use it in GitHub Desktop.
Save ncatallo/506fa173a30ad93f9268bbd0949da413 to your computer and use it in GitHub Desktop.
This script setup ssh key to connect to server (to run on your local machine)
#!/bin/bash
# Default values
PORT=22
WITH_PASSPHRASE=false
# Parse CLI arguments
while [[ "$#" -gt 0 ]]; do
case $1 in
--server-name)
SERVER_NAME="$2"
shift 2
;;
--host)
HOST_NAME="$2"
shift 2
;;
--user)
USER="$2"
shift 2
;;
--port)
PORT="$2"
shift 2
;;
--with-passphrase)
WITH_PASSPHRASE=true
shift 1
;;
*)
echo "❌ Unknown option: $1"
exit 1
;;
esac
done
# Validate required fields
if [[ -z "$SERVER_NAME" || -z "$HOST_NAME" || -z "$USER" ]]; then
echo "❌ Usage: $0 --server-name NAME --host IP --user USER [--port 22] [--with-passphrase]"
exit 1
fi
# Define paths
SSH_DIR="$HOME/.ssh"
CONFIG_FILE="$SSH_DIR/config"
KEY_PATH="$SSH_DIR/id_${SERVER_NAME}"
# Ensure .ssh directory and config file exist
mkdir -p "$SSH_DIR"
touch "$CONFIG_FILE"
chmod 700 "$SSH_DIR"
chmod 600 "$CONFIG_FILE"
# Generate SSH key if it doesn't exist
if [[ -f "$KEY_PATH" ]]; then
echo "⚠️ SSH key $KEY_PATH already exists. Reusing it."
else
echo "🔐 Generating SSH key..."
if [ "$WITH_PASSPHRASE" = true ]; then
ssh-keygen -t ed25519 -f "$KEY_PATH"
else
ssh-keygen -t ed25519 -f "$KEY_PATH" -N ""
fi
fi
# Add entry to ~/.ssh/config if not already present
if ! grep -q "Host $SERVER_NAME" "$CONFIG_FILE"; then
echo "📝 Adding server config to ~/.ssh/config..."
cat >> "$CONFIG_FILE" <<EOF
Host $SERVER_NAME
HostName $HOST_NAME
User $USER
Port $PORT
IdentityFile $KEY_PATH
IdentitiesOnly yes
EOF
else
echo "✅ Server $SERVER_NAME is already in ~/.ssh/config"
fi
# Copy public key to remote server
echo "📤 Copying public key to $USER@$HOST_NAME..."
ssh-copy-id -i "${KEY_PATH}.pub" -p "$PORT" "$USER@$HOST_NAME"
echo "✅ Done! You can now connect with: ssh $SERVER_NAME"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment