SSH

远程连接

通常我们是通过SSH客户端来远程操作Linux服务器的,而Linux默认就内置了SSH服务程序,我们可以通过netstat -nltp来查看:
3.SSH - 图1
于是我们就可以在本地通过常用的SSH客户端工具SecureCRT进行登录连接,协议选择SSH,端口22,输入用户名和密码点击连接即可。

免密登录

Linux也提供了ssh客户端工具,以ssh命令的形式存在,最常使用的格式是:ssh [<user>@]<hostname>,但是这种登录方式每次都需要输入密码,而ssh还提供了另一种免密登录方式,其原理如下:
3.SSH - 图2
machine1要想免密登录machine2首先要通过ssh-keygen通过rsa算法生成一对非对称加密的秘钥对(将保存在/root/.ssh中):

1234567891011121314151617181920212223242526 [root@hadoop01 ~]# ssh-keygenGenerating 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:74:d1:f2:65:fc:d9:95:51:b9:a3:54:66:67:46:0a:ac root@hadoop01The key’s randomart image is:+—[ RSA 2048]——+| .o.. oB|| ..o.+B=|| . .+ o=+*|| . .E .. +o|| S . . .|| . || || || |+————————-+[root@hadoop01 ~]# ll .ssh/总用量 8-rw———-. 1 root root 1675 6月 6 09:44 id_rsa-rw-r—r—. 1 root root 395 6月 6 09:44 id_rsa.pub


其中id_rsa.pub称为公钥,id_rsa称为私钥,公钥用来加密,私钥用来解密。公钥用来复制到要登录的目标主机的受信任列表authorized_keys中,可以借助ssh-copy-id <hostname>来完成:

1234567891011 [root@hadoop01 ~]# ssh-copy-id 192.168.25.201The authenticity of host ‘192.168.25.201 (192.168.25.201)’ can’t be established.RSA key fingerprint is eb:89:4f:4e:f5:9d:00:d4:14:1c:8b:8d:93:0e:3c:00.Are you sure you want to continue connecting (yes/no)? yesWarning: Permanently added ‘192.168.25.201’ (RSA) to the list of known hosts.root@192.168.25.201’s password:Now try logging into the machine, with “ssh ‘192.168.25.201’”, and check in: .ssh/authorized_keysto make sure we haven’t added extra keys that you weren’t expecting.


查看192.168.25.201的受信任列表:

12 [root@mini01 ~]# cat .ssh/authorized_keysssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAr/2gtvBX87wo9iSW+yTwGwmVbOpMmWYrgj8Tbl9VsBv/vCd6ktOg5Gwppb9NkVa8lj3FkN0UOOe6/xI7dr3C4+5kxvoo6GIHy/9mO67Rndo1YAZZ7UlPaJb5Kb8rkDcwX/KeylPTnrclykaBM5YypZSTr+pqZpiYAmaozLnBtzQnWgX6ZK4ijcS+psSI+bAeXZmyjAdY8qQ7Ncv3Lgr/jENL34letB9c1wOnOGSf+GkcO6hL9+n8FwlC2bld91noR17W+YQvyhdXdbK+DGPSDqbsCzlQHFJsbttBlFQZk8ErOU5GlUCiFXZzWJ3ItSC0+q/+TylU1MOkM7Ejno1/fQ== root@hadoop01


其中的表项就是由id_rsa.pub中的内容和远程登录信息root@hadoop01组成。以后当hadoop01机器上的root用户远程登录到192.168.25.201时,201发现在自己的受信任列表中包含了root@hadoop01于是会用这个表项对应的公钥加密一个随机字符串发送到企图连接到201的机器上,如果该机器真的是hadoop01而不是伪装的,那么它就能用自己的私钥将密文解密并返给201201发现解密后的正确才会让其登录。因为每个主机的私钥唯一,因此只要自己不泄露,其他主机就无法伪装成hadoop01登录201

————————————————

原文链接:https://zhenganwen.top/posts/b7d1c81d/