首页 > 技术文章 > 使用秘钥ssh登录远程服务器

sunshine-long 2018-04-15 10:46 原文

一、使用公钥远程登录ssh服务器方式

1.1 在客户端使用ssh-keygen  生成密匙

 1 steven:~ admin$ ssh-keygen           //客户端生成秘钥
 2 Generating public/private rsa key pair.
 3 Enter file in which to save the key (/Users/admin/.ssh/id_rsa): 
 4 Enter passphrase (empty for no passphrase):      //直接回车 不输入密码
 5 Enter same passphrase again:                            //回车
 6 Your identification has been saved in /Users/admin/.ssh/id_rsa.
 7 Your public key has been saved in /Users/admin/.ssh/id_rsa.pub.
 8 The key fingerprint is:
 9 SHA256:SB3UMdOY71AEGnsjlLRPMkdxCTjrUR07pXbUAkBQ9I8 admin@steven.local
10 The key's randomart image is:
11 +---[RSA 2048]----+
12 |       oBO&%=+o. |
13 |       o+B====. .|
14 |      . O+=o* .. |
15 |     . .oO.o.=   |
16 |      ..S..oE .  |
17 |        .   .    |
18 |                 |
19 |                 |
20 |                 |
21 +----[SHA256]-----+
22

steven:.ssh admin$ ls /Users/admin/.ssh/

id_dsa id_dsa.pub id_rsa id_rsa.pub known_hosts  .pub的就是公钥的文件

1.2 发布公钥,使用ssh-copy-id 命令将客户端生成的公钥发布到服务器地址上,并使用-i参数指定公钥的存放位置。

steven:.ssh admin$ ssh-copy-id -i /Users/admin/.ssh/id_rsa.pub root@120.0.1.300 -p**0,有端口号的要指定端口号

 1 steven:.ssh admin$ ssh-copy-id -i /Users/admin/.ssh/id_rsa.pub root@***.*.*.**4 -p3***
 2 /usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/Users/admin/.ssh/id_rsa.pub"
 3 /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
 4 /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
 5 root@*.*.**.*'s password: 
 6 
 7 Number of key(s) added:        1
 8 
 9 Now try logging into the machine, with:   "ssh -p '***' 'root@***'"
10 and check to make sure that only the key(s) you wanted were added.

1.3 登录服务器

steven:~ admin$ ssh root@**.**.** -p**
Last login: Fri Nov  2 22:13:41 2018 from 10.0.5.172
警告⚠️ 你所有的操作将被记录
[root@localhost ~]#       //登录成功
//配对成功后,服务器生成文件/root/.ssh/authorized_keys,如果是普通用户,则在/home/用户名/.ssh/authorized_keys里面.
[root@localhost .ssh]# cat /root/.ssh/authorized_keys

 

推荐阅读