按主机子网进行ssh配置

26
我在我的10.10.10.x子网上有一堆机器,它们基本上都配置相同。我将它们与我的10.10.11.x子网上的机器区分开来,后者有不同的用途。
我希望能够键入"ssh 10.x"来连接到10.x网络上的机器,键入"ssh 11.x"来连接到11.x网络上的机器。
我知道我可以设置单独的机器以允许访问完整的IP,或者在我的~/.ssh/config中使用简写版本,像这样:
Host 10.10.10.11 10.11
HostName 10.10.10.11
User root

这对我的网络上的许多主机来说可能会变得非常重复,所以我的问题是:有没有办法将这个指定为整个子网的模式?类似这样的东西:
Host 10.10.10.x
User root

Host 10.x
HostName 10.10.10.x
User root
3个回答

29

这行代码将提供所需的功能:

Host 192.168.1.*
IdentityFile KeyFile

如果您尝试连接IP地址在此子网中的服务器,则可以建立SSH连接。


这基本上是我想要的,但是你能否访问“*”部分,例如我上面提到的想要通过模式将某个范围映射到HostName的用例? - jdeuce
我不得不在OS X中使用“Host 192.168.1.?”。 - Thiago Figueiro
我已经在连接IP时使其工作,但在连接该子网中的主机名时却无法工作。使用主机名连接时是否应该正常工作? - dado
如果使用子网访问其主机名,则无法正常工作。 - mirec

15

ssh_config(5)手册页面:

 A pattern consists of zero or more non-whitespace characters, ‘*’ (a
 wildcard that matches zero or more characters), or ‘?’ (a wildcard that
 matches exactly one character).  For example, to specify a set of decla‐
 rations for any host in the “.co.uk” set of domains, the following pat‐
 tern could be used:

       Host *.co.uk

 The following pattern would match any host in the 192.168.0.[0-9] network
 range:

       Host 192.168.0.?

 A pattern-list is a comma-separated list of patterns.  Patterns within
 pattern-lists may be negated by preceding them with an exclamation mark
 (‘!’).  For example, to allow a key to be used from anywhere within an
 organisation except from the “dialup” pool, the following entry (in
 authorized_keys) could be used:

       from="!*.dialup.example.com,*.example.com"

所以您可以直接使用 host 10.*


0
我注意到你关于映射的评论:
这基本上是我想要的,但是有没有办法可以访问“*”部分,例如我上面提到的想要按模式将某个范围映射到HostName的用例?
这可以通过使用tokens来实现。在你的情况下,使用“%h”来替换HostName的一部分,使用Host的值。
我已经将匹配模式更改为使用“?”来限制匹配段的长度。这避免了一些混淆,其中“10.*”也匹配“10.10.10.x”。从技术上讲,你可以在4个八位IP的Host块中添加一个显式的HostName,并确保它们出现在快捷块之前,但使用“?”更加可靠。
将这样的代码块放入你的~/.ssh/config文件中,与你的完整IP配置一起。
Host 10.? 10.?? 10.1??
    HostName 10.10.%h
    # Your parameters here.

Host 11.? 11.?? 11.1??
    HostName 10.10.%h
    # Your parameters here.

或者,如果你想将 10.10.10.x 的配置与 10.x 的配置集中在一起,你可以告诉SSH转换主机名,并再次通过配置文档,像这样:
# Both patterns can be combined into one block here because they share
# the same `HostName` stem and the differing config is set elsewhere.
Host 10.? 10.?? 10.1?? 11.? 11.?? 11.1??
    HostName 10.10.%h
    CanonicalizeHostname yes

Host 10.10.10.*
    # Your parameters here.

Host 10.10.11.*
    # Your parameters here.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接