Created
January 26, 2026 08:41
-
-
Save M507/ae84e155f268f7aa79c9175ca0cdafde to your computer and use it in GitHub Desktop.
enable-root-ssh.sh
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
| #!/usr/bin/env bash | |
| set -e | |
| # Re-run as root if not already | |
| if [[ $EUID -ne 0 ]]; then | |
| echo "[*] Re-running script as root..." | |
| exec sudo -E bash "$0" | |
| fi | |
| echo "[+] Running as root" | |
| # ---- 1. Set root password ---- | |
| echo "[*] Set root password" | |
| passwd root | |
| # ---- 2. Enable root SSH login ---- | |
| SSHD_CONFIG="/etc/ssh/sshd_config" | |
| echo "[*] Enabling root SSH access" | |
| # Backup sshd_config if not already backed up | |
| if [[ ! -f "${SSHD_CONFIG}.bak" ]]; then | |
| cp "$SSHD_CONFIG" "${SSHD_CONFIG}.bak" | |
| echo "[+] Backup created: ${SSHD_CONFIG}.bak" | |
| fi | |
| # Update or add PermitRootLogin yes | |
| if grep -q "^PermitRootLogin" "$SSHD_CONFIG"; then | |
| sed -i 's/^PermitRootLogin.*/PermitRootLogin yes/' "$SSHD_CONFIG" | |
| else | |
| echo "PermitRootLogin yes" >> "$SSHD_CONFIG" | |
| fi | |
| # Ensure password auth is enabled (needed since you're setting a password) | |
| if grep -q "^PasswordAuthentication" "$SSHD_CONFIG"; then | |
| sed -i 's/^PasswordAuthentication.*/PasswordAuthentication yes/' "$SSHD_CONFIG" | |
| else | |
| echo "PasswordAuthentication yes" >> "$SSHD_CONFIG" | |
| fi | |
| # ---- 3. Copy SSH keys from ubuntu user ---- | |
| UBUNTU_SSH_DIR="/home/ubuntu/.ssh" | |
| ROOT_SSH_DIR="/root/.ssh" | |
| if [[ -f "$UBUNTU_SSH_DIR/authorized_keys" ]]; then | |
| echo "[*] Copying ubuntu SSH keys to root" | |
| mkdir -p "$ROOT_SSH_DIR" | |
| touch "$ROOT_SSH_DIR/authorized_keys" | |
| cat "$UBUNTU_SSH_DIR/authorized_keys" >> "$ROOT_SSH_DIR/authorized_keys" | |
| chmod 700 "$ROOT_SSH_DIR" | |
| chmod 600 "$ROOT_SSH_DIR/authorized_keys" | |
| chown -R root:root "$ROOT_SSH_DIR" | |
| echo "[+] SSH keys copied successfully" | |
| else | |
| echo "[!] No authorized_keys found for ubuntu user, skipping key copy" | |
| fi | |
| # ---- 4. Restart SSH ---- | |
| echo "[*] Restarting SSH service" | |
| if systemctl list-units --type=service | grep -q ssh.service; then | |
| systemctl restart ssh | |
| else | |
| systemctl restart sshd | |
| fi | |
| echo "[+] SSH restarted successfully" | |
| echo "[✓] Root SSH access is now enabled" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment