.SSH 目录
一旦我们对电脑使用了ssh连接其他服务器,便会在家目录下创建:
drwx------ 2 mugpeng mugpeng 4096 2月 9 12:18 .ssh
drwx------ 4 appe staff 136B 11 1 10:52 .ssh
我们可以看看里面的信息:
$ cat .ssh/known_hosts
|1|6N9UrScm40+g5By/rTvGWd/5v6c=|aVHpghbvnOZv07BcnMp4QwENuvQ= ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBGbWUqBhOhMtm+H1FOhs5I0ZSvUxPEVb2l6Pby2ZotdRmWs3kLWP2qgA66K8aiq+efDdNv3D4AcewfprZDAbDYk=
当我们初次通过ssh 远程连接其他电脑或主机的时候,ssh 会将密钥和主机ip信息保存在该文件中,后续新连接就不会验证key了。
免密码登陆
对于经常访问的服务器来说,在自己的个人电脑上,每次登陆都需要使用密码,非常麻烦。
我们可以在自己安全性较高的电脑上,对服务器使用免密码登陆的操作:
ssh-keygen # 生成公钥、私钥
$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/appe/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /Users/appe/.ssh/id_rsa.
Your public key has been saved in /Users/appe/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:gkGoMe962vUjCjS9gwgF9CF0dbgsugIRqTpBJwp39wc appe@appedeair
The key's randomart image is:
+---[RSA 2048]----+
|+= +o... |
|*+*oo.o E |
|=B+o...0 . |
|*.o. + .. . |
|o*..+ . S. |
|B.+ .. . |
|++.,. |
|o+..o.. |
|ooo. ... |
+----[SHA256]-----+
这一步操作,会在.ssh 目录下生成用于加密文件:
$ ls
config id_rsa id_rsa.pub known_hosts
接下来,需要将生成的id_rsa.pub 文件传递到服务器的.ssh 目录下,可以使用命令完成:
$ ssh-copy-id -p 22 mugpeng@192.168.130.128 # 传输公钥给需要免密码登陆服务器
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/Users/appe/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/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
mugpeng@192.168.130.128's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh -p '22' 'mugpeng@192.168.130.128'"
and check to make sure that only the key(s) you wanted were added.
这时候,我们可以去服务器的.ssh 目录下查看一下:
~/.ssh$ ls
authorized_keys known_hosts
现在尝试一下重新登陆服务器:
ssh -p 22 mugpeng@192.168.130.128
Welcome to Ubuntu 20.04.1 LTS (GNU/Linux 5.8.0-41-generic x86_64)
* Documentation: https://help.ubuntu.com
* Management: https://landscape.canonical.com
* Support: https://ubuntu.com/advantage
243 updates can be installed immediately.
24 of these updates are security updates.
To see these additional updates run: apt list --upgradable
Your Hardware Enablement Stack (HWE) is supported until April 2025.
Last login: Tue Feb 9 18:42:14 2021 from 192.168.130.1
直接就登陆成功啦~
现在就可以不用密码使用scp 和ssh 命令了~
免密码登陆工作原理
了解一下。也不会多一块肉。
- 首先是生成公钥、私钥
这两个密钥中的数据,必须使用对应的钥匙才能解密——公钥文件需要私钥,私钥文件需要公钥。本地使用私钥,远程服务器使用公钥。
这种加密方式也叫非对称加密算法。
- 传输公钥到服务器
这样本地通过私钥加密的数据传输到服务器,就可以用服务器上保存的公钥解密;服务器回传给本地的数据使用公钥加密,本地直接使用保存的私钥解密,查看服务器回传的数据。