前言
這篇的需求來自於,因為我在遠端的樹莓派使用了幾個 port 建立的幾個網頁,
但畢竟我不常在樹莓派上面開發,因此會想要把遠端的 port 拉至 local 的 port 來顯示,
簡單舉例,就是把遠端的 Port 8888,拉至 local 電腦的 Port 8888 一樣能夠顯示出對應的網頁。
常見的 8888 應用於 jupyter notebook,我們可以透過這方式建立一個 remote 可使用的 jupyter notebook。
這篇紀錄我達成這個需求的方式。
這篇文的前一篇文章,有講到重複的許多觀念,可參考:
https://wongwongnotes-github-io.pages.dev/linux/ssh-config-ssh-authorized_keys/
ssh config 進階設定
在前一篇文章中,我們已經有提到如何修改一些 ssh config 的內容,
這邊我們也可以剛好來整理一下,
Host rpi
HostName localhost
User pi
Port 9002
IdentityFile ~/.ssh/id_rsa
LocalForward 5000 127.0.0.1:5000
LocalForward 5001 127.0.0.1:5001
LocalForward 5002 127.0.0.1:5002
我們可以觀察一下這份 config 的內容,
- Host rpi:我取的暱稱,方便我 ssh rpi 即可連線
- HostName localhost:因為我是使用 anydesk 建立連線,我要連線的 port 為 9002 (對應遠端的 ssh port 22)
- User pi:使用者名稱 pi
- Port 9002:在 anydesk 中設定我要連線的 port 為 9002 (對應遠端的 ssh port 22)
- IdentityFile ~/.ssh/id_rsa:透過 authorized_keys 的公私鑰,達到免密碼登入
- LocalForward 5000 127.0.0.1:5000:port forwarding (5000 -> localhost:5000)
- LocalForward 5001 127.0.0.1:5001:port forwarding (5001 -> localhost:5001)
- LocalForward 5002 127.0.0.1:5002:port forwarding (5002 -> localhost:5002)
快速建立遠端金鑰
- 注意:下面指令是建立在遠端 ~/.ssh/authorized_keys 不存在的時候才可以使用!!!
scp id_rsa.pub rpi:~/.ssh/authorized_keys # 個人筆記使用,不懂在幹嘛請別亂用,會出事
請注意如果該檔案已經存在,檔案會被覆寫掉!!!
稍微說明一下上面在做什麼事情,
我們透過 scp 把 id_rsa.pub (這是公鑰),傳到遠端 rpi 主機的 ~/.ssh/authorized_keys 這個路徑與檔案。
scp error
scp: xxxxxx : No such file or directory
個人常見的可能原因,遠端的資料夾路徑沒有被完整的建立。
例如:想要傳到遠端的路徑 ~/folder/file.txt
但在遠端的資料夾,「~/」 底下並不存在「folder」這個資料夾就會跳錯。
Reference
- How to add local forward setting to my ssh config file?
- 20. 增進 SSH 使用效率 - ssh_config
- 【VScode】透過建立 ssh authorized_keys 讓 VScode 繞過輸入 ssh 密碼 or 達成 ssh 免密碼登入
- 【Linux】在 terminal 中尋找 username, hostname 作為 ssh 連線的方式 (以連線到 raspberrypi 為例)
- [教學] 產生SSH Key並且透過KEY進行免密碼登入
- 使用VSCode Remote透過 SSH 進行遠端開發
- Remote SSH: Tips and Tricks
- How do I find my username and servername for windows SSH server
- Configuring SSH Public Key Authentication on Windows