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。
- 使用
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:
这样就完成了~
- 手动上传 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