Blog Post

ssh key 的建立 ( PC )

首先在 windows 上建立 key

# open the terminal in windows and type the command as below
# 在 windows 上打看終端機( Window 鍵 + R 然後輸入 cmd ), 然後輸入以下指令
ssh-keygen

# 接下來系統會問你一些問題
# 問題 1: 你的 key 擺放位置, 如果你有一個以上的 key 請使用不同的檔案名稱
# 問題 2: 使用 key 時是否要用密碼保護, 如果不要就直接按 enter
# 問題 3: 同上, 只是要你再確定一次

# change to the .ssh directory
# 變更目錄到 .ssh 下面
cd .ssh

# copy the content of the public key
# 複製公鑰的內容, 使用 type 指令可以把內容顯示在畫面上
# 要將公鑰放上去 server 有很多種方法, 這邊僅說明最簡單易懂的複製貼上步驟
type id_rsa.pub

再連上去 Linux server 設定

# 以下操作是在切換為 root 的帳號下進行
# 可用下方指令切換為 root
sudo su -

# add new account
# 新㽪一個帳號, 建立的當下會問你要設定的密碼與帳號相關資料, 可一律以 enter 帶過 
adduser newcute

# setup password, 請忽略
# 建立(修改)密碼, 可以忽略
passwd newcute

# assign the user group ( permission ), 請先忽略
# 將 newcute 加入到某一個群組, 可以忽略
usermod -a -G wheel newcute

# change user to the new one, important
# 將帳號切換至 newcute
su newcute

# change directory to the home
# 切換到 newcute 帳號的家目錄
cd

# make the require directory
# 建立所需要的目錄
mkdir .ssh

# change directory
# 切換到該目錄之下
cd .ssh

# create an authorized_keys file:
# 建立所需檔案, 有兩種方式都可以使用
nano authorized_keys
# or
vi authorized_keys

# paste the whole public key content
# do this in the nano or vi UI
# 將剛剛在 windows 複製的內容貼到 authorized_keys 內容後進行存檔退出

# change the file permission for ssh
# 修改目錄與檔案的權限
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

# Edit configuration, 
# 修改 ssh 的服務設定檔案
vi /etc/ssh/sshd_config

# 將以下內容修改打開, 要注意是否正確為 on 與 yes, 如果是被 mark 掉記得將前面的 # 符號刪除
#################### 
PasswordAuthentication no
PubkeyAuthentication yes

# restart the ssh service
# 重新啟動 sshd 服務
service sshd restart

# ==== 以上已完成所有工作, 可以進行測試了 ====
# NOW you can try it!!!!
# << 方法 1 >> 指定 key file
ssh -i keyname newcute@127.0.0.1
# or
# << 方法 2 >> 如果你只有一組 key 的話就不用特別指定, 他會採用預設唯一的
ssh newcute@127.0.0.1

透過 Windows 的 Powshell 設定

# 記得要將 檔案位置與 server 相關資訊做適當的變更以符合你的環境

cat ~/.ssh/id_rsa_cute301.pub | ssh -p2222 cute301@127.0.0.1 "mkdir -p ~/.ssh && touch ~/.ssh/authorized_keys && chmod -R go= ~/.ssh && cat >> ~/.ssh/authorized_keys"

相關參考資料
https://www.footmark.com.tw/news/linux/centos/windows-ssh-nopassword-linux/

另一個參考資料

chmod 參考資料
https://weikaiwei.com/linux/chmod-commands/