# แนะนำแนวทางการใช้ ssh-key แทนการใส่รหัสผ่านทุกครั้งที่เชื่อมต่อ ssh

## ที่มา

สำหรับคนที่จำเป็นต้องใช้ ssh สำหรับ remote ไปที่เครื่อง server แล้วไม่อยากที่จะต้องคอยใส่รหัสผ่านทุกครั้งไป สามารถใช้วิธีนี้ในการสร้างคีย์ แล้วเอา public key ไปไว้ที่เครื่อง Server ได้ง่ายๆ ดังนี้

## 1\. ที่เครื่องเรา (ssh client) ให้สร้าง key โดยใช้คำสั่ง

```bash
ssh-keygen -t rsa
```

หลังจากนั้นจะมีขึ้นถามว่าจะให้เก็บ key ไว้ที่ไหน และจะใช้ passphrase เป็นคำว่าอะไร กดใส่ไปจนเสร็จ

```bash
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/myname/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again:
```

หลังจากสร้างคีย์เสร็จแล้วจะขึ้นข้อความประมาณนี้

```bash
Your identification has been saved in /Users/myname/.ssh/id_rsa
Your public key has been saved in /Users/myname/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:/MysHA256fInGeRprINt9AiUJZl36KBGXXH2RcTudl9 myname@mycom.local
The key's randomart image is:
+---[RSA 3072]----+
|     . HI .....  |
|       ^       ^ |
|      .......... |
|       ......... |
|        ........ |
|       .   .     |
|        .   .    |
|         .   .   |
|          .   .  |
+----[SHA256]-----+
```

## 2\. หลังจากได้คีย์มาแล้ว ขั้นต่อไปเป็นการนำ public key ไปใส่ที่เครื่อง Server ปลายทาง โดยใชคำสั่งดังนี้

```bash
ssh-copy-id myname@mydestinationservername.com
```

โดยจะมีหน้าจอขึ้นเพื่อให้ถามรหัสผ่านสำหรับใช้ในการ Remote เข้าเครื่อง Server ก็ให้ใส่ไป โดยจะมีหน้าจอขึ้นมาประมาณนี้

```bash
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/Users/myname/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
myname@mydestinationservername.com's password: 

Number of key(s) added:        1

Now try logging into the machine, with:   "ssh 'myname@mydestinationservername.com'"
and check to make sure that only the key(s) you wanted were added.
```

แต่ถ้าไม่สำเร็จ ให้ใช้วิธีนำไฟล์ public key ไปวางที่ `~/.ssh/authorized_keys` (แต่ถ้าสำเร็จก็ไม่ต้องทำขั้นตอนนี้)

## 3\. ทดสอบ Remote ดู จะต้องไม่ขึ้นถามรหัสผ่าน

```bash
ssh myname@mydestinationservername.com
```

เช่น ขึ้น prompt ประมาณนี้ ก็สามารถใช้งานต่อได้เลย

```bash
[myname@mydestinationservername.com ~]$
```

หวังว่าบทความนี้จะเป็นประโยชน์กับคนที่เจอปัญหาอย่างเดียวกันนะครับ
