Linux使用.pem文件实现免密登录

因项目需要将本机文件拷贝至远程机器,为了实现免密远程拷贝,根据接口文档描述需要pem文件,由此学习.pem的配置使用。

1.在远程机器生成.pem文件

生成密钥对:

$ ssh-keygen -t rsa -b 2048 -v

[root@iZ2zea30f9quwoa85fc9527 ~]# ssh-keygen -t rsa -b 2048 -v
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:BPwQAYFXSiCiHpISTSdmDB1qXQx8+JMozQY8WGRbdhE root@iZ2zea30f9quwoa85fc9527
The key's randomart image is:
+---[RSA 2048]----+
|BO%=@*E=         |
|+%*Xo=o.         |
|*o*o= .o.        |
|=..= + ..        |
| .o   . S        |
|                 |
|                 |
|                 |
|                 |
+----[SHA256]-----+
[root@iZ2zea30f9quwoa85fc9527 ~]# 

查看生成的密钥对:

$ ls ~/.ssh/

[root@iZ2zea30f9quwoa85fc9527 ~]# ls ~/.ssh/
id_rsa  id_rsa.pub
[root@iZ2zea30f9quwoa85fc9527 ~]# 

将私钥重命名至id_rsa.pem:

$ mv ~/.ssh/id_rsa ~/.ssh/id_rsa.pem

[root@iZ2zea30f9quwoa85fc9527 ~]# mv ~/.ssh/id_rsa ~/.ssh/id_rsa.pem
[root@iZ2zea30f9quwoa85fc9527 ~]# ls ~/.ssh/
id_rsa.pem  id_rsa.pub
[root@iZ2zea30f9quwoa85fc9527 ~]# 

修改~/.ssh/目录权限:

$ chmod 700 ~/.ssh/

将id_rsa.pub文件内容重定向至authorized_keys文件:

$ cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys

[root@iZ2zea30f9quwoa85fc9527 ~]# cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
[root@iZ2zea30f9quwoa85fc9527 ~]# ls ~/.ssh/
authorized_keys  id_rsa  id_rsa.pub
[root@iZ2zea30f9quwoa85fc9527 ~]# 

修改authorized_keys文件权限:

$ chmod 600 ~/.ssh/authorized_keys

2.修改远程服务器配置

使用编辑器(vim)打开配置文件

$ sudo vim /etc/ssh/sshd_config

修改完成后如下:

RSAAuthentication yes
PubkeyAuthentication yes

# The default is to check both .ssh/authorized_keys and .ssh/authorized_keys2
# but this is overridden so installations will only check .ssh/authorized_keys
AuthorizedKeysFile      %h/.ssh/authorized_keys

重启ssh服务:

$ sudo service sshd restart

3.本机免密登录远程机器

将id_rsa.pem文件拷贝至本机,免密登录:

$ ssh -i id_rsa.pem remote-username@remote-ip

例如:

$ ssh -i id_rsa.pem root@8.141.95.27

这里要着重的说一下 root@8.141.95.27 后面的地址问题,ip后面要跟着:

用户根目录 root@8.141.95.27:~/workspace/xx

存放系统产生的经常变化的文件目录 root@8.141.95.27:/var/xxx

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值