Skip to content

Instantly share code, notes, and snippets.

@juliancruzsanchez
Last active December 28, 2024 12:10
Show Gist options
  • Save juliancruzsanchez/b5cacbde55ea1f70c3b1513d65fd95be to your computer and use it in GitHub Desktop.
Save juliancruzsanchez/b5cacbde55ea1f70c3b1513d65fd95be to your computer and use it in GitHub Desktop.
Disable SSH Password Programtically
#!/bin/bash
# Prompt the user for remote host information
read -p "Enter remote username: " remote_username
read -sp "Enter remote password: " remote_password
echo
read -p "Enter remote hostname or IP address: " remote_host
# Generate a random filename for the key pair
random_id=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 10 | head -n 1)
key_filename="id_rsa_$random_id"
# Generate a new SSH key pair with the random filename
ssh-keygen -t rsa -b 4096 -N "" -f ~/.ssh/"$key_filename"
# Get the public key
public_key=$(cat ~/.ssh/"$key_filename".pub)
# Copy the public key to the remote host using sshpass
sshpass -p "$remote_password" ssh -o StrictHostKeyChecking=no "$remote_username@$remote_host" "mkdir -p ~/.ssh && echo '$public_key' >> ~/.ssh/authorized_keys"
# Test the SSH connection
if ssh "$remote_username@$remote_host" "echo 'SSH connection successful!'"; then
echo "SSH key setup complete!"
# Disable password login on the remote host
sshpass -p "$remote_password" ssh -o StrictHostKeyChecking=no "$remote_username@$remote_host" "sudo sed -i 's/^PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config"
sshpass -p "$remote_password" ssh -o StrictHostKeyChecking=no "$remote_username@$remote_host" "sudo systemctl restart ssh"
echo "Password login disabled on the remote host."
else
echo "SSH connection failed. Key setup incomplete."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment