Last active
May 5, 2024 01:14
-
-
Save crawc/8c9d6672759f9a08af37297635361c6b to your computer and use it in GitHub Desktop.
This file contains 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 | |
# Script to reinstall and configure SSH for password authentication and root login | |
# Check if the script is run as root | |
if [ "$(id -u)" -ne 0 ]; then | |
echo "This script must be run as root. Please use sudo or log in as root." | |
exit 1 | |
fi | |
echo "Starting the SSH server reinstallation process..." | |
# Remove existing OpenSSH server and its configuration files | |
echo "Removing existing OpenSSH server..." | |
sudo apt purge -y openssh-server | |
sudo rm -rf /etc/ssh/ | |
echo "OpenSSH server removed." | |
# Reinstall OpenSSH server | |
echo "Reinstalling OpenSSH server..." | |
sudo apt install -y openssh-server | |
echo "OpenSSH server reinstalled." | |
# Path to the SSH configuration file | |
SSH_CONFIG="/etc/ssh/sshd_config" | |
# Make a backup of the new SSH configuration file | |
echo "Backing up the new SSH configuration file..." | |
sudo cp $SSH_CONFIG $SSH_CONFIG.backup | |
echo "Backup created." | |
# Display the sections of the file before modification | |
echo "Initial state of PasswordAuthentication and PermitRootLogin:" | |
sudo grep -E 'PasswordAuthentication|PermitRootLogin' $SSH_CONFIG | |
# Update Include directive, handle variations in spacing | |
echo "Updating SSH configuration to include specific files..." | |
sudo sed -i '/^# *Include \/etc\/ssh\/sshd_config.d\/\*.conf/s/^# *//' $SSH_CONFIG | |
# Enable PasswordAuthentication, handle variations in spacing and existing no/yes | |
echo "Enabling PasswordAuthentication..." | |
sudo sed -i '/^# *PasswordAuthentication no/s/^# *//' $SSH_CONFIG | |
sudo sed -i 's/^PasswordAuthentication no/PasswordAuthentication yes/' $SSH_CONFIG | |
sudo sed -i '/^# *PasswordAuthentication yes/s/^# *//' $SSH_CONFIG | |
# Permit root login, handle variations in spacing | |
echo "Enabling root login..." | |
sudo sed -i '/^# *PermitRootLogin prohibit-password/s/^# *//' $SSH_CONFIG | |
sudo sed -i 's/^PermitRootLogin prohibit-password/PermitRootLogin yes/' $SSH_CONFIG | |
sudo sed -i '/^# *PermitRootLogin yes/s/^# *//' $SSH_CONFIG | |
# Display the modified sections of the file | |
echo "Modified state of PasswordAuthentication and PermitRootLogin:" | |
sudo grep -E 'PasswordAuthentication|PermitRootLogin' $SSH_CONFIG | |
# Restart SSH service to apply changes | |
echo "Restarting SSH service to apply changes..." | |
sudo systemctl restart sshd | |
echo "SSH service restarted successfully." | |
echo "SSH configuration updated and service restarted successfully." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment