原因

通过密码进行ssh连接存在被暴力破解的可能,但在禁用密码登录+修改22端口+禁用root登录之后,可以将被暴力破解的概率降到最低,且通过private_key登录服务器更适合shell操作

生成公钥,私钥

下面以ubuntu18.04为例

#( 09/27/[email protected]:30上午 )( [email protected] ):~/Desktop
   ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/lestat/.ssh/id_rsa): /home/lestat/.ssh/vps
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/lestat/.ssh/vps.
Your public key has been saved in /home/lestat/.ssh/vps.pub.
The key fingerprint is:
SHA256:rcD6QAPXaRrDfNMR1MdQu/s4TvEtOlumK3AUcdzrUaM [email protected]
The key's randomart image is:
+---[RSA 2048]----+
|       .+oo*o.   |
|   o . o .o.+....|
|  . * * .  o. .o.|
|   o B . ..  Eo  |
|    + o S.. o. . |
|   . o ....  +.. |
|    o   .o  o = .|
|     o    ..oB . |
|      .    oB=.  |
+----[SHA256]-----+

建议在passphrase处设置密码,防止key被盗用!!!
以上提示说明生成成功
接下来加入到authorized_keys

#( 09/27/[email protected]:31上午 )( [email protected] ):~/Desktop
   cat ~/.ssh/vps.pub >> authorized_keys

更新权限

sudo chmod 600 authorized_keys && sudo chmod 700 ~/.ssh

更新配置文件

sudo vim /etc/ssh/sshd_config

修改以下配置项

PubkeyAuthentication yes

重启sshd服务

sudo service sshd restart

至此完成了服务端配置,将服务端的~/.ssh/vps(private_key)复制到需要远程连接服务器的本地机,注意:此处private_key文件必须设置为400权限使用ssh命令即可完成连接

ssh -i /path/to/private_key -p PORT [email protected]

为了方便,可以加入别名

to-my-vps='ssh -i /path/to/private_key -p PORT [email protected]'

也可以直接写入到~/.bashrc文件或其包含的~/.bash_aliases文件,如下

alias to-my-vps='ssh -i /path/to/private_key -p PORT [email protected]'

注意,如果是使用了zsh,则编辑对应的.zshrc文件