คู่มือนี้แนะนำวิธีตั้งค่า SSH Key-based Authentication เพื่อเข้าสู่ Server Remote โดยไม่ต้องพิมพ์รหัสผ่านทุกครั้ง
ทำไมต้องใช้ SSH Key?
- ปลอดภัยกว่ารหัสผ่าน (Brute-force ไม่ได้)
- อัตโนมัติได้ (Script, Cron, CI/CD, Ansible)
- รองรับ Passphrase บน Key เอง (2FA แบบ Local)
- มาตรฐานอุตสาหกรรม
ขั้นตอนที่ 1: สร้าง Key Pair (Client)
# สร้าง Ed25519 (แนะนำ - เร็ว เล็ก ปลอดภัย)
ssh-keygen -t ed25519 -C "user@hostname"
# หรือ RSA 4096 (เข้ากันได้กว้าง)
ssh-keygen -t rsa -b 4096 -C "user@hostname"
# กด Enter ทั้ง 3 ครั้ง: File location, Passphrase, Confirm
# Passphrase = เพิ่มความปลอดภัย (แนะนำให้ตั้ง)
ขั้นตอนที่ 2: Copy Public Key ไป Server
วิธีที่ 1: ssh-copy-id (ง่ายที่สุด)
ssh-copy-id user@remoteserver.com
# หรือระบุ port/key
ssh-copy-id -p 2222 -i ~/.ssh/id_ed25519.pub user@remoteserver.com
วิธีที่ 2: Manual (ถ้าไม่มี ssh-copy-id)
# 1. Copy public key
scp ~/.ssh/id_ed25519.pub user@remoteserver.com:~/
# 2. SSH เข้า Server
ssh user@remoteserver.com
# 3. ติดตั้ง Key
mkdir -p ~/.ssh
chmod 700 ~/.ssh
cat ~/id_ed25519.pub >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
rm ~/id_ed25519.pub
ขั้นตอนที่ 3: ทดสอบ
ssh user@remoteserver.com
# ควรเข้าได้เลย (หรือถาม Passphrase ของ Key ถ้าตั้งไว้)
ตั้งค่า SSH Agent (ไม่ต้องพิมพ์ Passphrase ซ้ำ)
# เริ่ม Agent
eval $(ssh-agent -s)
# เพิ่ม Key
ssh-add ~/.ssh/id_ed25519
# ป้อน Passphrase 1 ครั้ง
# ตรวจสอบ
ssh-add -l
เพิ่มใน ~/.bashrc เพื่อเริ่มอัตโนมัติ
คำสั่ง SSH ที่มีประโยชน์
| คำสั่ง | คำอธิบาย |
|---|---|
ssh user@host "command" | รันคำสั่ง Remote แล้วกลับมา |
ssh -p 2222 user@host | ระบุ Port |
ssh -i ~/.ssh/key user@host | ระบุ Key File |
scp file user@host:/path | Copy ไฟล์ไป Server |
scp user@host:/path file | Copy ไฟล์จาก Server |
rsync -avz /src user@host:/dst | Sync โฟลเดอร์ (Resume, Compress) |