💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
**公钥登录**:用户将自己的公钥储存在远程主机上。登录的时候,远程主机会向用户发送一段随机字符串,用户用自己的私钥加密后,再发回来。远程主机用储存的公钥进行解密,解密成功则可以直接登录,不需要再输入密码。 **1、在实现公钥免密登录之前需要先创建公钥和私钥** 可以使用此命令来创建 `ssh-keygen -t [rsa|dsa]`,如无指定 -t 默认使用dsa加密方式,此命令将会生成公钥文件和私钥文件 id_rsa,id_rsa.pub或id\_dsa,id\_dsa.pub。其中.pub是公钥文件 ``` [root@izwz91quxhnlkan8kjak5hz /]# ssh-keygen Generating public/private rsa key pair. Enter file in which to save the key (/root/.ssh/id_rsa): 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:75vvEgUH3OgAdk7ZdIOKS/wz55f5tFfAkK0+WnJaElY root@izwz91quxhnlkan8kjak5hz The key's randomart image is: +---[RSA 2048]----+ | o.o=o=oo | | . +o *.E.. | | . ..+ + + | | + . + o o | | . oS. + . | | . +.= * .| | =.X +. .| | .=.+. ..| | +*o.o. | +----[SHA256]-----+ [root@izwz91quxhnlkan8kjak5hz /]# ls ~/.ssh/ authorized_keys id_rsa id_rsa.pub known_hosts ``` **2、把本地主机的公钥复制到远程主机的authorized_keys文件上:ssh-copy-id** > ssh-copy-id [option] [user@]hostname > option: > * -i 指定公钥文件 > * -f 强制模式:不检查远程服务器上是否存在密钥。这意味着它不需要私钥。当然,这会导致在远程系统上安装多个密钥副本 > * -p 指定远程主机端口 ``` [root@izwz91quxhnlkan8kjak5hz .ssh]# ssh-copy-id -p 33 182.16.20.194 /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 ``` **3、authorized\_keys文件说明** 该文件存储的是远程登录的用户公钥,ssh-copy-id命令就是将公钥追加到远程主机的authorized\_keys文件里。里面记录了ssh的加密方式以及公钥字符串。<br> 至此,公钥免密配置就完成了,再次使用`ssh -p 33 root@182.16.20.194`命令登录就不需要输入密码。 **4、拓展说明** * 设置authorized\_keys文件权限为600,.ssh目录权限为700 * 其他方式为远程主机添加本地主机的公钥: * 第一步:使用此命令将公钥发送到远程主机:scp id_rsa.pub root@182.16.20.194:/root/.ssh * 第二步:在远程主机上创建authorized_keys文件,并设置权限 * 第三步:将公钥写入authorized_keys:cat id_rsa.pub >> authorized_keys(>>为追加内容,> 会覆盖原内容)