ssh 登录服务器时,有两种方式,一是密码登录,二是秘钥登录。
利用秘钥登录既可以实现ssh的免密登录
步骤
- 本地PC生成公钥,秘钥
- 部署公钥到服务器
- 本地PC免密登录到远程服务器
一、本地PC生成公钥,秘钥
首先查看id_rsa id_rsa.pub两个文件是否存在,windows目录是:C:\Users\username\.ssh下, linux目录是:$HOME/.ssh下。
如果文件不存在,则执行命令生成私钥和秘钥:
这里的-t是指定算法,可以指定的算法有四种 dsa | ecdsa | ed25519 | rsa。ssh指定rsa,一路回车即可。
ssh-keygen -t rsa -C "your_email@youremail.com"
此时即可生成id_rsa id_rsa.pub两个文件,其中id_rsa为私钥,妥善保管,不可泄露,id_rsa.pub可以任意公布。
效果如下:
tangs@ubuntu:~/.ssh$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/tangs/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/tangs/.ssh/id_rsa.
Your public key has been saved in /home/tangs/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:KYJO23+iTw/X7Stb57xl6p8SNjweyRI9SyhQs4dY4cQ tangs@ubuntu
The key's randomart image is:
+---[RSA 2048]----+
| o*. |
| .=E+ |
| ..+ .o |
| . o.o + |
| o . . S . = + |
| o o . . . o @ |
| o . o . . * * o|
| o.+. .o * +.|
| .ooo. .oooB+.|
+----[SHA256]-----+
二、部署公钥到服务器
- 简单粗暴的,首先检查远程服务器文件~/.ssh/authorized_keys是否存在,不存在则创建 ~/.ssh/authorized_keys,将本地的公钥id_rsa.pub里面的内容复制到远程服务器 ~/.ssh/authorized_keys ,保存即可
- 利用工具ssh-copy-id, 执行命令
ssh-copy-id -i /path/to/id_rsa.pub user@server.pc
, 他会自动完成步骤1的内容,即部署完成。
值得注意的是,authorized_keys 的权限应该设置为600,如果用方法1,记得修改一下权限。
三、本地PC免密登录到远程服务器
可以免密登录了。直接 ssh server.pc 即可。效果如下。
tangs@tangs ~
λ ssh local.pc
Welcome to Ubuntu 18.04.1 LTS (GNU/Linux 4.15.0-46-generic x86_64)
* Documentation: https://help.ubuntu.com
* Management: https://landscape.canonical.com
* Support: https://ubuntu.com/advantage
* Ubuntu's Kubernetes 1.14 distributions can bypass Docker and use containerd
directly, see https://bit.ly/ubuntu-containerd or try it now with
snap install microk8s --channel=1.14/beta --classic
* Canonical Livepatch is available for installation.
- Reduce system reboots and improve kernel security. Activate at:
https://ubuntu.com/livepatch
286 packages can be updated.
1 update is a security update.
No mail.
Last login: Wed Mar 13 23:31:00 2019 from 192.168.44.1
tangs@ubuntu:~$