天天看點

配置 SSH 伺服器以及管理 SSH keys

Install SSH server

  • How to Enable SSH on Ubuntu 20.04

Install ssh:

sudo apt update
sudo apt install openssh-server
sudo systemctl status ssh
           

If the firewall on Ubuntu is enabled:

Enable and disable ssh:

sudo systemctl enable --now ssh
sudo systemctl disable --now ssh
           

Add users for SSH

  • Create a new SSH user on Ubuntu Server (不一定需要,預設所有users在開啟ssh service之後都可以連接配接)

Set up public key authentication for OpenSSH

  • Set up SSH public key authentication to connect to a remote system
  • Configure SSH key based secure authentication

兩種辦法。都注意隻上傳 public key (

.pub

字尾的檔案) 到伺服器,千萬别傳 private key。

  1. 使用

    ssh-copy-id

Generate a SSH key:

ssh-keygen -t rsa
           

Copy your public key to the SSH server and add it to

authorized_keys

automatically:

這樣就完成了~

  1. 手動上傳 public key

Generate a SSH key and copy it to the server manually:

ssh-keygen -t rsa
scp ~/.ssh/<your_public_key> <username>@<ip>
           

Log into the SSH server. If

.ssh/authorized_keys

file doesn’t exist, do these:

mkdir -p ~/.ssh
touch ~/.ssh/authorized_keys
           

Add your public key to

authorized_keys

and have a copy of the public key in

.ssh

directory:

cat ~/<your_public_key> >> ~/.ssh/authorized_keys
mv ~/id_rsa.pub ~/.ssh/
           

一些說明:

SSH keys are typically configured in an

authorized_keys

file in

.ssh

subdirectory in the user’s home directory (注意這裡,每個user的key存放在它自己的home目錄下的.ssh檔案夾中). Typically a system administrator would first create a key using

ssh-keygen

and then install it as an authorized key on a server using the

ssh-copy-id

tool. See also the dedicated page on configuring authorized keys for OpenSSH.

With OpenSSH, the authorized keys are by default configured in

.ssh/authorized_keys

in the user’s home directory.

Only the public key is copied to the server. The private key should never be copied to another machine.

Once the key has been copied, it is best to test it:

ssh -i ~/.ssh/<your_private_key> [email protected]

.

Appendix

其他參考資料:

  • SSH Key Management Overview & 6 Best Practices

繼續閱讀