[root@m01 ~]# ssh-keygen
Generating public/private rsa key pair.
Enter fileinwhich to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
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:OKxLhAZ0qD/LXHzGUByirfRI5k1YRCCMT8lK8sLIk10 root@m01
The key's randomart image is:
+---[RSA 2048]----+
|+oo*=... ||+=== Eo ||O=O +. ||=@oO...|| oB.+o+ S || .o.o.+. || o +oo || +. .||.|
+----[SHA256]-----+
3)客户端将公钥发送至要免密登录的服务器
1> 手动复制公钥
1.查看公钥
[root@m01 ~]# cat .ssh/id_rsa.pub2.在其他服务器创建文件,将内容粘贴进去
[root@nfs ~]# mkdir .ssh[root@nfs ~]# vim .ssh/authorized_keys3.授权文件
[root@nfs ~]# chmod 700 .ssh/[root@nfs ~]# chmod 600 .ssh/authorized_keys4.测试连接
#首次连接需要记录服务器信息到 .ssh/known_hosts[root@m01 ~]# ssh 172.16.1.31
The authenticity of host'172.16.1.31 (172.16.1.31)' can't be established.
ECDSA key fingerprint is SHA256:sYhpMuszVGaHSeWKyLXMGQQ72f/6KxyExWabnY/cz6w.
ECDSA key fingerprint is MD5:bc:9c:0b:45:b5:27:71:cd:da:02:68:c0:48:71:9d:69.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '172.16.1.31' (ECDSA) to the list of known hosts.
Last login: Tue Nov 2410:37:03 2020 from 172.16.1.7
#再一次连接[root@m01 ~]# ssh 172.16.1.31
Last login: Tue Nov 2411:00:39 2020 from 172.16.1.61
2> 使用命令推送公钥
#推送公钥到 172.16.1.7[root@m01 ~]# ssh-copy-id -i .ssh/id_rsa.pub root@172.16.1.7
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: ".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
root@172.16.1.7's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@172.16.1.7'"
and check to make sure that only the key(s) you wanted were added.
#连接测试[root@m01 ~]# ssh 172.16.1.7
Last login: Tue Nov 24 09:02:26 2020 from 10.0.0.1
[root@m01 ~]# vim /etc/ssh/sshd_config#修改ssh服务的端口
Port 1748#禁止使用root登录服务器
PermitRootLogin no
#禁止使用密码登录服务器
PasswordAuthentication no
UseDNS no # 禁止ssh进行dns反向解析,影响ssh连接效率参数
GSSAPIAuthentication no # 禁止GSS认证,减少连接时产生的延迟
七、扩展
1.免交互expect
1)安装expect
[root@m01 ~]# yum install -y expect
2)编写expect脚本
[root@m01 ~]# vim xuanjian.exp#!/usr/bin/expectsetip10.0.0.51
set pass 123456settimeout30
spawn ssh root@$ipexpect{"(yes/no)"{send "yes\r"; exp_continue}"password:"{send "$pass\r"}}expect"root@*"{send "df -h\r"}expect"root@*"{send "exit\r"}expect eof