Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> สมาร์ทโฟน >> Linux

วิธี SSH ไป Server Remote ไม่ต้องพิมพ์รหัสผ่าน (SSH Key)

คู่มือนี้แนะนำวิธีตั้งค่า 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 ที่มีประโยชน์

Hardening SSH Server (/etc/ssh/sshd_config)


# ปิด Password Authentication (บังคับ Key Only)
PasswordAuthentication no
PubkeyAuthentication yes

# ปิด Root Login
PermitRootLogin no

# จำกัด User/Group
AllowUsers user1 user2
# AllowGroups sshusers

# Idle Timeout
ClientAliveInterval 300
ClientAliveCountMax 2

รีสตาร์ท: systemctl restart sshd

Troubleshooting

  • Permission: chmod 700 ~/.ssh; chmod 600 ~/.ssh/authorized_keys
  • SELinux: restorecon -Rv ~/.ssh
  • Debug: ssh -vvv user@host

SSH Key คือมาตรฐานการเข้าถึง Server อย่างปลอดภัย ควรตั้งค่าให้ทุก Server ที่จัดการ

คำสั่งคำอธิบาย
ssh user@host "command"รันคำสั่ง Remote แล้วกลับมา
ssh -p 2222 user@hostระบุ Port
ssh -i ~/.ssh/key user@hostระบุ Key File
scp file user@host:/pathCopy ไฟล์ไป Server
scp user@host:/path fileCopy ไฟล์จาก Server
rsync -avz /src user@host:/dstSync โฟลเดอร์ (Resume, Compress)