Skip to content

Instantly share code, notes, and snippets.

@devinci-it
Created May 18, 2024 22:23
Show Gist options
  • Select an option

  • Save devinci-it/1b4ea5042f30ea5deb521f404c603814 to your computer and use it in GitHub Desktop.

Select an option

Save devinci-it/1b4ea5042f30ea5deb521f404c603814 to your computer and use it in GitHub Desktop.
script snippet Script snippet to install OpenSSH server, configure it for key-based authentication, and add a public key for the specified user.
#!/bin/bash
# Update Ubuntu Packages
sudo apt update
sudo apt upgrade -y
# Install OpenSSH Server
sudo apt install openssh-server -y
# Start and Enable SSH Service
sudo systemctl start ssh
sudo systemctl enable ssh
# Configure SSH for Key-Based Authentication
sudo sed -i 's/#PubkeyAuthentication yes/PubkeyAuthentication yes/' /etc/ssh/sshd_config
sudo sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
sudo sed -i 's/#AuthorizedKeysFile/AuthorizedKeysFile/' /etc/ssh/sshd_config
sudo systemctl restart ssh
# Allow SSH Through Firewall
sudo ufw allow ssh
sudo ufw enable
# Add Public Key to the Authorized Keys
USER_HOME=$(eval echo ~${SUDO_USER})
mkdir -p $USER_HOME/.ssh
chmod 700 $USER_HOME/.ssh
# Replace 'your_public_key_here' with your actual public key
echo "your_public_key_here" | tee -a $USER_HOME/.ssh/authorized_keys
chmod 600 $USER_HOME/.ssh/authorized_keys
chown -R $SUDO_USER:$SUDO_USER $USER_HOME/.ssh
# Print Completion Message
echo "OpenSSH installation and configuration completed successfully."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment