linux设置免密登陆

210 阅读2分钟

使用密码登陆总是存在着被暴力破解的密码的情况,这样很不安全。我之前有一台服务器一天被八千多个ip尝试暴力登陆。

于是我们使用ssh密钥来登陆,这样既安全也省事。

以下我们使用主机A来称呼你的跳板机,而主机B则是免密登陆的对象。

操作步骤

  • 在主机A中生成密钥对,执行命令ssh-keygen
root@aliyun:/var/run/dbus# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
/root/.ssh/id_rsa already exists.
Overwrite (y/n)? y
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:px5DgIDv1hQSxesLKblcBdYLRxdGSklRQ/PkWz8kOeQ root@aliyun
The key's randomart image is:
+---[RSA 2048]----+
| .o+==*X.. .     |
|. .=+=+ * o .    |
| ...=+o  o E .   |
|  . oo .  o =    |
| o =.   S..  o   |
|o =.o  . o    .  |
|.+.. .  +        |
|..  .  . o       |
|        .        |
+----[SHA256]-----+

在输入ssh-keygen之后提示Enter passphrase:,这个时候是让你输入密钥对的密码,如果你想对密钥对加密那就输入,如果输入了密码会导致之后即使设置了Pubkey登陆还是需要输入密钥对的密码,一般一路回车就好了。

  • 输入ssh-copy-id <yourhost>,将主机A中的密钥对发送到主机B

    注意:输入你的主机名,如下的vultr就是我的主机B,-p参数是因为我修改了端口为8848,如果是默认的话则不需要该参数

    root@aliyun:~/.ssh# ssh-copy-id root@vultr -p 8848
    /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
    /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
    /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
    root@vultr's password: 
    
    Number of key(s) added: 1
    
    Now try logging into the machine, with:   "ssh -p '8848' 'root@vultr'"
    and check to make sure that only the key(s) you wanted were added
    
  • 最后修改远程主机的sshd服务的配置文件,输入vim /etc/ssh/sshd_config

    需要设置允许密钥登陆,并取消密码登陆

    PubkeyAuthentication yes
    PasswordAuthentication no
    

    最后重启ssh服务,service ssh restart

​ 最后就可以尝试用跳板机免密登陆啦~