大网数据广告活动
服务器运维问答

How can I match a CIDR range for an SSH config host entry?

· 52CE 我爱测

I'm looking for a way to use specific CIDR blocks to match hosts in the SSH client configuration (usually ~/.ssh/config ). For example, I have an entry to forward all traffic through a bastion host if the IP falls into a certain …

问题原文

原帖链接 · fazy · CC BY-SA 3.0

I'm looking for a way to use specific CIDR blocks to match hosts in the SSH client configuration (usually ~/.ssh/config). For example, I have an entry to forward all traffic through a bastion host if the IP falls into a certain range, let's say 10.1.0.0/16:

host 10.1.*
    proxycommand ssh -q bastion -W %h:%p

This works very well, but how about when I add some ranges that don't fit the dot notation exactly?

# doesn't work, unfortunately
host 10.2.0.0/18
    proxycommand ssh -q bastion-foo -W %h:%p
host 10.2.64.0/18
    proxycommand ssh -q bastion-bar -W %h:%p

Is there something in the manual that I've missed, or a clever scripting trick that would enable matching these host IP ranges?

社区高分解答

原帖链接 · Alex Stragies · CC BY-SA 4.0

You could use the very powerful Match directive with the grepcidr tool:

Match exec "grepcidr 10.2.0.0/18 <(echo %h) &>/dev/null"
   Proxycommand ssh -q bastion-foo -W %h:%p

How this works:

  • %h in the commandline gets expanded to the hostname (see Tokens)
  • <(echo %h) wraps this into a temporary "file"
  • Maybe use <(dig +short %h) if working with hostnames
  • then use grepcidr to match the hostname %h against a.b.c.d/e
  • &>/dev/null because we only care about the return code, not the output.

This needs the additional tiny grepcidr package, which should exist in your package manager.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2016-09-19)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0 / CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。