ssh实现通过跳转机无密码登陆多台机器


目的:在一个机房里,有多个服务器,让其中一台(S1)作为对外登陆的跳转机,这台机器可以通过外网远程登录;要登陆其他的机器,只能先登陆S1,然后进行连接登陆,此时的连接登陆是不需要密码的,并且所有机器之间可以无密码跳转,传输文件也不需要密码。


环境:ubunut系统。


步骤1,配置ssh:

    ssh默认端口是22,安全考虑,这里都改为6000。S1服务器的ssh监听0.0.0.0 ,其他的所有机器的sshd监听本机的内网地址。

配置如下:

S1:

~vim /etc/ssh/sshd_config 

# Package generated configuration file
# See the sshd_config(5) manpage for details

# What ports, IPs and protocols we listen for
Port 6000
# Use these options to restrict which interfaces/protocols sshd will bind to
#ListenAddress ::
#ListenAddress 0.0.0.0
...
PermitRootLogin yes
...

    其他机器

vim /etc/ssh/sshd_config 
# Package generated configuration file
# See the sshd_config(5) manpage for details

# What ports, IPs and protocols we listen for
#Port 22
Port 6000
# Use these options to restrict which interfaces/protocols sshd will bind to
#ListenAddress ::
#ListenAddress 0.0.0.0
ListenAddress 192.168.1.1    #本机的内网地址
...
PermitRootLogin yes
...

然后重启ssh服务,注意重启后其他机器不能通过外网地址重新登陆。


步骤2:

    在S1上制造密钥文件,会产生一个.ssh目录

root@ubuntu:~# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which 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:
48:a8:92:4b:19:c0:73:c9:91:a3:34:c7:f6:ff:cb:49 root@ubuntu
The key's randomart p_w_picpath is:
+--[ RSA 2048]----+
|o o.+            |
|.= X .           |
|..B + .          |
| oo. o .         |
|oo.   o S        |
|.o     .         |
|.       .E       |
|        o..      |
|         +.      |
+-----------------+
root@ubuntu:~# ll .ssh/
total 16
drwx------ 2 root root 4096 Jun  6 16:55 ./
drwx------ 8 root root 4096 Jun  6 16:55 ../
-rw------- 1 root root 1679 Jun  6 16:55 id_rsa
-rw-r--r-- 1 root root  393 Jun  6 16:55 id_rsa.pub

    S1机器上在.ssh目录下创建一个config文件:

vim .ssh/config

ControlMaster auto
ControlPath /tmp/ssh_mux_%h_%p_%r
ControlPersist 1h
StrictHostKeyChecking no
SendEnv LANG LC_*
GSSAPIAuthentication no
GSSAPIDelegateCredentials no

Host S1    #主机名
HostName 192.168.1.1    #内网IP
User root
Port 6000

Host S2
HostName 192.168.1.2
User root
Port 6000

Host S3
HostName 192.168.1.3
User root
Port 6000

#依次添加机器

    在S1机器上创建authorized_keys文件并将.ssh目录拷贝到其他机器上,这一步是最关键的一步。

#cd .ssh
#cp id_rsa.pub authorized_keys
#chmod 600 authorized_keys
#cd
#scp -r -p 6000 .ssh root@192.168.1.2:/root/    ##将.ssh目录复制到其他服务器的root目录下


配置结束,这样在S1上就可以无需输入密码登陆其他机器,所有机器之间都可以相互登陆、传输文件。输入ssh命令,双击tab建会显示所有的机器


总结:只有一个登陆接口,其他的机器很安全,并且个机器之间登陆、传输文件非常方便。但是如果S1被黑了,那么所有的机器都可以被访问了,所以对S1要做好安全防护。