https://www.linuxbabe.com/ubuntu/two-factor-authentication-ssh-key-ubuntu
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
บันทึกสคริปต์ไว้เป็นไฟล์ เช่น setup-2fa.sh
ให้สิทธิ์รัน:
chmod +x setup-2fa.sh
รันสคริปต์:
./setup-2fa.sh
sudo adduser username
เปลี่ยน username เป็นชื่อผู้ใช้ที่คุณต้องการ เช่น admin01
ระบบจะถาม:
sudo