在通过SSH访问服务器时,使用SSH密钥进行认证是尤其重要的。这样做为服务器增加了额外的保护,确保只有那些拥有密钥的人才能访问服务器。
在本地机器上运行下面命令以生成SSH密钥:
ssh-keygen -t rsa
你会看到下面的输出,询问要将密钥写到哪一个文件里,并且设置一个密码:
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): my_key
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in my_key.
Your public key has been saved in my_key.pub.
The key fingerprint is:
SHA256:MqD/pzzTRsCjZb6mpfjyrr5v1pJLBcgprR5tjNoI20A
Enter file in which to save the key (/root/.ssh/id_rsa): my_key
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in my_key.
Your public key has been saved in my_key.pub.
The key fingerprint is:
SHA256:MqD/pzzTRsCjZb6mpfjyrr5v1pJLBcgprR5tjNoI20A
完成之后,就得到两个文件:
my_key</p> <p>my_key.pub
接下来把my_key.pub拷贝到~/.ssh/authorized_key中
cp my_key.pub ~/.ssh/authorized_keys
然后使用下面命令将密钥上传到服务器:
scp -P16543 authorized_keys user@yourserver-ip:/home/user/.ssh/
至此,你就可以从这台本地机器上无密码地访问服务器了。
关闭SSH的密码认证
既然已经有了SSH密钥,那么关闭SSH的密码认证就会更安全了。再次打开并编辑sshd_config,按如下设置:
ChallengeResponseAuthentication no
PasswordAuthentication no
UsePAM no
PasswordAuthentication no
UsePAM no