SSH(Secure SHELL)是一种开源且最受信任的网络协议,用于登录远程服务器以执行命令和程序。它还用于使用安全复制(SCP)命令和Rsync命令通过网络将文件从一台计算机传输到另一台计算机。
在本文中,我们将向您展示如何使用ssh密钥在基于RHEL的Linux发行版(如CentOS、Fedora、Rocky Linux和AlmaLinux)上设置无密码登录,以连接到远程Linux服务器,而无需输入密码。
使用带有SSH密钥的无密码登录将增加两台Linux服务器之间的信任,以便于文件同步或传输。
注意:每次执行ssh-keygen -t rsa 产生的私钥文件都会不同,如果文件~/.ssh/id_rsa存在,会提示是否覆盖该文件,此时可选择n不覆盖该文件而使用已有的id_rsa文件。
1.首先使用root用户(也可以是别的用户)登录Linux服务器,执行以下命令创建公钥,出现交互界面要求输入密码、密钥保存路径等,均按回车以默认值生成即可。
$ ssh-keygen -t rsaGenerating public/private rsa key pair.Enter file in which to save the key (/root/.ssh/id_rsa): [Press enter key]Enter passphrase (empty for no passphrase): [Press enter key]Enter same passphrase again: [Press enter key]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:jMRzwTev6W12jZq4m2QjwJLqGUoqPkQ6cz0EpVGe4pM root@x240The key's randomart image is:+---[RSA 2048]----+| .oo .. || .+ o ..o || o.o + .. o || o o.+ = . ||o Eoo + S o ||+..oo. . o ||.=o . ..+. o ||++ o +.++.o .||=.+ ==oo |+----[SHA256]-----+ 注意:您可以在ssh-keygen上指定一个选项,如大小和类型。您可以在ssh-keygen命令的手册页上找到更多信息。
From the man page of ssh-keygen :
-b bitsSpecifies the number of bits in the key to create. For RSA keys, the minimum size is 768 bits and the default is 2048 bits. Generally, 2048 bits is considered sufficient. DSA keys must be exactly 1024 bits as specified by FIPS186-2.-t typeSpecifies the type of key to create. The possible values are “rsa1” for protocol version 1 and “dsa”, “ecdsa” or “rsa” for protocol version 2.2.执行以上命令后,在用户的根目录下生成一个.ssh 的文件夹,我们进入该文件夹下面并查看有哪些内容。
$ cd /root/.ssh/$ ls -ltotal 12-rw------- 1 root root 1679 Aug 2 18:44 id_rsa //生成的私钥文件-rw-r--r-- 1 root root 391 Aug 2 18:44 id_rsa.pub //生成的公钥文件-rw-r--r-- 1 root root 176 Aug 2 12:28 known_hosts //保存本用户信任的用户公钥,用于其他用户免密登陆本用户时(用户)的身份验证$使用ssh-copy-id命令将刚才生成的公钥/root/.ssh/id_rsa.pub复制到目标主机。当提示输入远程用户的密码时,只需输入即可。
$ ssh-copy-id -i ~/.ssh/id_rsa.pub user@target-host手工复制方式,将本地的id_rsa.pub文件中的内容复制到目标主机的~/.ssh/authorized_keys文件中。
$ cat id_rsa.pub | ssh user@target-host "cat >> ~/.ssh/authorized_keys"测试你的密钥,你应该直接登录你的目标主机而不需要密码。
$ ssh user@target-host | 留言与评论(共有 0 条评论) “” |