https://www.linuxbabe.com/ubuntu/two-factor-authentication-ssh-key-ubuntu

https://tron-natthakorn.medium.com/เพิ่มความปลอดภัยของ-ssh-root-account-บน-linux-ด้วย-google-authenticator-2fa-67bf3ddfe82

Script 2FA Debian12

nano setup-2fa.sh

#!/bin/bash

set -e

echo "==> ติดตั้ง libpam-google-authenticator"
sudo apt update
sudo apt install -y libpam-google-authenticator qrencode

echo "==> เพิ่มบรรทัด PAM SSH สำหรับ 2FA (เฉพาะ group 2fausers)"
PAM_FILE="/etc/pam.d/sshd"
if ! grep -q "pam_google_authenticator.so" "$PAM_FILE"; then
    sudo bash -c "echo 'auth required pam_google_authenticator.so' >> $PAM_FILE"
    echo "✓ PAM SSH ปรับเรียบร้อย"
else
    echo "✓ PAM SSH มีการตั้งค่าแล้ว"
fi

echo "==> ปรับ sshd_config ให้รองรับ 2FA"
SSHD_CONFIG="/etc/ssh/sshd_config"
sudo sed -i 's/^#*KbdInteractiveAuthentication.*/KbdInteractiveAuthentication yes/' "$SSHD_CONFIG"
sudo sed -i 's/^#*UsePAM.*/UsePAM yes/' "$SSHD_CONFIG"

echo "==> รีสตาร์ท SSH"
sudo systemctl restart ssh

echo ""
echo "==== ✅ เสร็จสิ้น ===="
echo "→ อย่าลืมสแกน QR Code หรือจด Secret Key ลงแอป Google Authenticator"
echo "→ จากนั้นเปิด SSH ใหม่เพื่อลองใช้งาน 2FA"

echo "==> สร้าง Google Authenticator สำหรับผู้ใช้ $USER"
google-authenticator -t -d -f -r 3 -R 30 -W

ตั้งค่า แบบ กำหนดเอง

sudo apt update
sudo apt install -y libpam-google-authenticator qrencode

sudo nano /etc/ssh/sshd_config
-> UsePAM yes
-> KbdInteractiveAuthentication yes

sudo nano /etc/pam.d/sshd
-> auth required pam_google_authenticator.so

##google gen จดหรือแสกนqr ไว้
google-authenticator -t -d -f -r 3 -R 30 -W

📦 วิธีใช้

  1. บันทึกสคริปต์ไว้เป็นไฟล์ เช่น setup-2fa.sh

  2. ให้สิทธิ์รัน:

    chmod +x setup-2fa.sh
    
  3. รันสคริปต์:

    ./setup-2fa.sh
    

✅ ขั้นตอนสร้าง User สิทธิ์ Root บน Debian 12

1. 🔐 สร้าง User ใหม่

sudo adduser username

เปลี่ยน username เป็นชื่อผู้ใช้ที่คุณต้องการ เช่น admin01

ระบบจะถาม:


2. ✅ เพิ่ม User เข้า group sudo