设置多台机器linux服务器ssh相互无密码访问

时间:2023-03-08 16:42:39
设置多台机器linux服务器ssh相互无密码访问

在每台服务器上都执行ssh-keygen -t rsa生成密钥对:

$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/tscms/.ssh/id_rsa):
Created directory '/home/tscms/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/tscms/.ssh/id_rsa.
Your public key has been saved in /home/tscms/.ssh/id_rsa.pub.

 

在每台服务器上生成密钥对后,将公钥复制到需要无密码登陆的服务器上 

举例如10.1.15.128,10.1.15.42,10.1.15.41这三台服务器需要做相互免密码登陆,在每台服务器生成密钥对后,

在每台服务器上执行ssh-copy-id命令,将公钥复制到其它两台服务器上(此处以10.1.15.128为例,用户为root,其它两台步骤相同)

$ ssh-copy-id -i  ~/.ssh/id_rsa.pub root@10.1.15.41
The authenticity of host '10.1.15.41 (10.1.15.41)' can't be established.
RSA key fingerprint is 7c:95:ec:4f:77:07:0a:26:df:0d:8a:31:89:31:d7:da.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '10.1.15.41' (RSA) to the list of known hosts.
reverse mapping checking getaddrinfo for bogon [10.1.15.41] failed - POSSIBLE BREAK-IN ATTEMPT!
tscms@10.1.15.41's password:
Now try logging into the machine, with "ssh 'tscms@10.1.15.41'", and check in: .ssh/authorized_keys to make sure we haven't added extra keys that you weren't expecting.
$ ssh-copy-id -i  ~/.ssh/id_rsa.pub root@10.1.15.42
……

Linux系统里缺省都包含一个名为ssh-copy-id的工具:

# type ssh-copy-id
ssh-copy-id is /usr/bin/ssh-copy-id

你用cat或者more命令看一下就知道ssh-copy-id本身其实就是一个shell脚本,用法很简单:

# ssh-copy-id -i ~/.ssh/id_rsa.pub username@server_IP

ssh-copy-id有一个很要命的问题,那就是缺省它仅仅支持SSH运行在22端口的情况,不过实际上出于安全的需要,

我们往往都会更改服务器的SSH端口,比如说改成10022端口,这时候你运行ssh-copy-id就会报错了

解决办法:

# vi ~/.ssh/config

加上内容:

Host server
Hostname ip
Port 10022

你也可以单独只加入Port一行配置,那样就是一个全局配置,保存后再运行ssh-copy-id命令就不会报错了。

补充:如果端口不是22,不修改config文件,按如下方式也可以:

ssh-copy-id -i ~/.ssh/id_rsa.pub  “-p 10022  username@server_IP”

解决常见错误

reverse mapping checking getaddrinfo for bogon [10.1.15.42] failed - POSSIBLE BREAK-IN ATTEMPT!

原因:ssh 登录的时候会做一系列安全检查,其中有一项是 主机名与ip地址是否能解析,如果解析不了就会报这个错误。

如果你有dns服务器 ,在服务器上做解析也行。总之,ping主机名必须解析到对应的ip地址,

解决方法一:在/etc/hosts 文件加上对方的主机名 ip地址,可以ping通主机名即可。
解决方法二:/etc/ssh/ssh_config /etc/ssh/sshd_config 修改这两个配置文件
GSSAPIAuthentication yes 改成 GSSAPIAuthentication no