因项目需要将本机文件拷贝至远程机器,为了实现免密远程拷贝,根据接口文档描述需要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