如何在Linux上设置SSH密码以进行无密码登录(转)

ssh(secure shell)广泛用于远程登录Linux服务器。当我们使用ssh登录到远程系统时,它会提示输入密码,然后只允许我们登录到服务器。有时我们需要配置应用程序或脚本(主要是shell脚本),以便在对远程系统执行ssh之后自动化要执行的任务。但是,如果我们没有配置基于密钥的ssh,脚本将在每次运行时提示输入密码,这时我们需要手动输入密码。为了解决这个问题,我们可以选择使用公钥/私钥概念。其中远程服务器允许其他系统基于密钥进行ssh。

步骤1:生成ssh密钥对

首先,需要生成一个密钥对(rsa或dsa),可以使用“-t”命令行开关指定选项rsa或dsa密钥。如果不传递-t参数,它将默认创建RSA密钥。

1

$ ssh-keygen -t rsa

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

Generating public/private rsa key pair.

Enter file in which to save the key (/home/rahul/.ssh/id_rsa):

Created directory '/home/rahul/.ssh'.

Enter passphrase (empty for no passphrase):

Enter same passphrase again:

Your identification has been saved in /home/rahul/.ssh/id_rsa.

Your public key has been saved in /home/rahul/.ssh/id_rsa.pub.

The key fingerprint is:

SHA256:GZQ3tJffEUimdMZHIG3LcpvdkOaogwXBtWeaM2ejzYY rahul@tecadmin

The key's randomart image is:

+---[RSA 2048]----+

|       ..+oo+*+o |

|       .+ +o** ..|

|        .oooB oo |

|        .o B =+..|

|        S.= *+=.o|

|          .X.+...|

|         oE.+    |

|        . o.     |

|           .     |

+----[SHA256]-----+

上面的命令将在〜/ .ssh目录中创建两个文件,如下所示。

1、〜/ .ssh / id_rsa [私钥]

2、〜/ .ssh / id_rsa.pub [公钥]

步骤2:将公钥复制到远程系统

让我们将系统的公钥复制到远程系统〜/ .ssh / authorized_key的密钥文件中。我们可以手动或使用ssh-copy-id命令行工具执行此操作。

1

$ ssh-copy-id -i ~/.ssh/id_rsa.pub 192.168.10.20

输出:

1

2

3

4

5

21

root@192.168.10.20's password:

Now try logging into the machine, with "ssh '192.168.10.20'", and check in:

  .ssh/authorized_keys

to make sure we haven't added extra keys that you weren't expecting.

它将提示输入远程系统的密码。输入远程机器密码并按Enter。

步骤3:验证没有密码的SSH

现在我们已经完成了所有工作,只需尝试对远程系统进行ssh。你将在不输入密码的情况下登录远程系统。

1

$ ssh root@192.168.10.20

上面的命令不会提示输入登录密码。在任何情况下,如果ssh命令提示输入密码,则意味着你的设置没有正确配置,请重试所有步骤。

原文地址:https://www.cnblogs.com/shixiuxian/p/10535189.html