sudo bash <<'BASH'
set -Eeuo pipefail
echo "===== 1. FIX SSH DIRECTORY ====="
install -d -o root -g root -m 0755 /run/sshd
install -d -m 0755 /etc/tmpfiles.d
cat > /etc/tmpfiles.d/sshd-custom.conf <<'EOF'
d /run/sshd 0755 root root -
EOF
systemd-tmpfiles --create /etc/tmpfiles.d/sshd-custom.conf
echo "===== 2. VALIDATE SSH ====="
/usr/sbin/sshd -t
echo "SSH configuration OK"
echo "===== 3. SSH UNITS ====="
for unit in ssh.socket ssh.service sshd.service; do
echo "--- $unit ---"
systemctl is-enabled "$unit" 2>/dev/null || true
systemctl is-active "$unit" 2>/dev/null || true
done
echo "===== 4. VERIFY AUTOSTART ====="
SSH_OK=0
for unit in ssh.socket ssh.service sshd.service; do
if systemctl is-enabled --quiet "$unit"; then
if ! systemctl is-active --quiet "$unit"; then
systemctl start "$unit" || true
fi
if systemctl is-active --quiet "$unit"; then
echo "Verified active and enabled: $unit"
SSH_OK=1
break
fi
fi
done
echo "===== 5. CHECK SSH LISTENER ====="
ss -lntp | grep -E '(:22[[:space:]])' || true
if [[ "$SSH_OK" -ne 1 ]] ||
! ss -H -ltn | awk '$4 ~ /:22$/ {found=1} END {exit !found}'; then
echo "ERROR: SSH autostart or port 22 not verified."
echo "Reboot cancelled to protect remote access."
exit 1
fi
echo "===== 6. FINAL CHECK ====="
hostnamectl --static
dpkg --audit
uptime -s
echo "===== 7. REBOOT ====="
shutdown -r +1 "Ubuntu maintenance completed"
echo "SUCCESS: reboot scheduled in 1 minute"
BASH