红联Linux门户
Linux帮助

关于ssh-keygen命令的介绍与用法

发布时间:2016-06-29 15:16:11来源:linux网站作者:坤哥玩CSDN

ssh-keygen 用于:生成、管理和转换认证密钥。


常用参数:

-t type:指定要生成的密钥类型,有rsa1(SSH1),dsa(SSH2),ecdsa(SSH2),rsa(SSH2)等类型,较为常用的是rsa类型

-C comment:提供一个新的注释

-b bits:指定要生成的密钥长度 (单位:bit),对于RSA类型的密钥,最小长度768bits,默认长度为2048bits。DSA密钥必须是1024bits

-f filename:指定生成的密钥文件名字


Linux下使用ssky-keygen无密码登录服务器步骤:

1.使用ssh-keygen在本机上生成密钥:

[Jiakun@Kunge ~]$ ssh-keygen -t rsa -C "kungeplay@gmail.com|blueskywww@126.com" 
Generating public/private rsa key pair. 
Enter file in which to save the key (/home/Jiakun/.ssh/id_rsa):[Enter key]   
/home/Jiakun/.ssh/id_rsa already exists. 
Overwrite (y/n)? y 
Enter passphrase (empty for no passphrase):[Enter key]   
Enter same passphrase again:[Enter key]   
Your identification has been saved in /home/Jiakun/.ssh/id_rsa. 
Your public key has been saved in /home/Jiakun/.ssh/id_rsa.pub. 
The key fingerprint is: 
ac:15:9d:97:2a:f3:43:ed:64:25:38:ad:54:d2:bd:c8 kungeplay@gmail.com|blueskywww@126.com

此时在本机上生成如下一个公钥和一个私钥文件:

[Jiakun@Kunge ~]$ ll ./.ssh/ 
总用量 12 
-rw-------. 1 Jiakun Jiakun 1675 5月  19 19:44 id_rsa 
-rw-r--r--. 1 Jiakun Jiakun  420 5月  19 19:44 id_rsa.pub 

注意公钥相当于锁,私钥相当于钥匙,我们这里相当于在客户端创建一对钥匙和锁,想要做到SSH免密码登录,就相当于我们将锁分发到服务端并装锁,然后客户端就可以利用这个钥匙开锁。


2.使用ssh-copy-id命令将本机上的公钥文件拷贝到服务器上(服务器用户名比如为liujiakun,IP地址为192.168.3.105):

[Jiakun@Kunge ~]$ ssh-copy-id -i ~/.ssh/id_rsa.pub liujiakun@192.168.3.105 
liujiakun@192.168.3.105's password:  
Now try logging into the machine, with "ssh 'liujiakun@192.168.3.105'", and check in: 
.ssh/authorized_keys 
to make sure we haven't added extra keys that you weren't expecting. 

若服务器端远程登录ssh的端口号被更改了(比如为3330),则命令应改为这样:

ssh-copy-id -i ~/.ssh/id_rsa.pub “-p 3330 liujiakun@192.168.3.105“


3.此时在本机上登录服务器会提示Agent admitted failure to sign using the key.并仍提示需要输入密码:

[Jiakun@Kunge ~]$ ssh liujiakun@192.168.3.105 
Agent admitted failure to sign using the key. 
liujiakun@192.168.3.105's password:  

在网上查询得知需要使用 ssh-add 指令将私钥 加进来:

[Jiakun@Kunge ~]$ ssh-add ~/.ssh/id_rsa
Identity added: /home/Jiakun/.ssh/id_rsa (/home/Jiakun/.ssh/id_rsa)
[Jiakun@Kunge ~]$ ssh 'liujiakun@192.168.3.105'
Last login: Tue May 19 20:32:32 2015 from 192.168.3.118
此时如上所示可以无密码登录进192.168.3.118服务器上。

可以在服务器上查询~/.ssh/目录下多了一个文件:authorized_keys:

[liujiakun@localhost ~]$ ll ./.ssh/ 
总用量 8 
-rw-------. 1 liujiakun liujiakun  420 5月  19 20:25 authorized_keys 
-rw-r--r--. 1 liujiakun liujiakun 1191 1月  11 19:03 known_hosts


本文永久更新地址:http://www.linuxdiyf.com/linux/21940.html