DEV Community

Weerasak Chongnguluam
Weerasak Chongnguluam

Posted on

6

ใช้ SSH config ช่วยจำ option เวลาจะ remote ด้วย SSH

SSH config ช่วยให้เรา config option ของแต่ละ host เอาไว้หลายๆอันได้ ทำให้ตอนเรียก ssh ใส่แค่ชื่อ hostname ใน config ก็พอแล้ว

เวลาใช้ ssh เพื่อ remote เครื่องอื่น ปกติแล้วจะสั่งประมาณนี้

ssh user@hostname
Enter fullscreen mode Exit fullscreen mode

หรือถ้ามี port ที่ต่างจาก ssh ปกติ (22) ก็ใส่ option สำหรับ port เพิ่มคือ

ssh -p 2222 user@hostname
Enter fullscreen mode Exit fullscreen mode

หรือถ้ามี IdentityFile ด้วย ก็ต้องเพิ่ม option ไปอีกแบบนี้

ssh -i identity.key -p 2222 user@hostname
Enter fullscreen mode Exit fullscreen mode

ตัวอย่างเช่นผมจะ ssh เข้า Ubuntu ที่ลงไว้ใน Virtual Box โดยใช้ vagrant ปกติแล้วจะสั่ง vagrant ssh ก็ได้ แต่ถ้าจะสั่งด้วย ssh เองโดยตรงจะต้องสั่งประมาณนี้

ssh -i ~/vagrants/ubuntu/.vagrant/machines/default/virtualbox/private_key -p 2222 vagrant@127.0.0.1
Enter fullscreen mode Exit fullscreen mode

ทีนี้ถ้าเราจะใช้ SSH config ช่วยเราก็สร้างไฟล์ config ที่ $HOME/.ssh/config

จากนั้นกำหนดค่าแบบนี้

Host ubuntu-vagrant
  HostName 127.0.0.1
  IdentityFile ~/vagrants/ubuntu/.vagrant/machines/default/virtualbox/private_key
  Port 2222
  User vagrant
Enter fullscreen mode Exit fullscreen mode

ลักษณะ config file ของ SSH ก็มี key เช่น Host, HostName, IdentityFile, Port และ User แล้วเว้นวรรคด้วย 1 ช่องว่าง ตามด้วยค่าที่กำหนดให้ key นั้นๆ

แล้วก็มีการใช้ indentation เพื่อบอกว่าค่านั้นเป็น key/value ย่อยๆของ key หลักอีกที

จากตัวอย่างผมกำหนด Host คือ ubuntu-vagrant แล้วก็กำหนดค่า HostName เป็น IP หรือ Domain name ของ Host ที่เราต้องการต่อ แล้วก็ค่า IdentityFile ไปที่ path ของ private key ของ vagrant ที่กำหนดให้กับ VM ที่ต้องการ remote ตามด้วยค่า Port 2222 แล้วก็​ User คือ username ในทีนี้คือ vagrant

เสร็จแล้วหลังจากนั้นเวลาเราต้องการ connect ไปที่ Ubuntu ใน VM ก็แค่สั่ง

ssh ubuntu-vagrant
Enter fullscreen mode Exit fullscreen mode

เท่านี้ก็ได้แล้ว

ssh config

Top comments (1)

Collapse
 
doittikorn profile image
Ittikorn Chawkamud

เพิ่งรู้เลยครับว่าตั้ง config ssh อย่างงี้ได้ด้วยขอบคุณครับ

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay