How to automatically switch ssh config based on local subnet?

前端 未结 5 2005
无人及你
无人及你 2021-02-14 15:36

When I\'m on a certain network (subnet is 10.10.11.x) I need to jump through an intermediate host to reach my destination because of destination port I can\'t change and limited

5条回答
  •  太阳男子
    2021-02-14 16:18

    Based on the answer by Fedor Dikarev, Mike created a bash script named onsubnet:

    #!/usr/bin/env bash
    
    if [[ "$1" == "--help" ]] || [[ "$1" == "-h" ]]  || [[ "$1" == "" ]] ; then
      printf "Usage:\n\tonsubnet [ --not ] partial-ip-address\n\n"
      printf "Example:\n\tonsubnet 10.10.\n\tonsubnet --not 192.168.0.\n\n"
      printf "Note:\n\tThe partial-ip-address must match starting at the first\n"
      printf "\tcharacter of the ip-address, therefore the first example\n"
      printf "\tabove will match 10.10.10.1 but not 110.10.10.1\n"
      exit 0
    fi
    
    on=0
    off=1
    if [[ "$1" == "--not" ]] ; then
      shift
      on=1
      off=0
    fi
    
    regexp="^$(sed 's/\./\\./g' <<<"$1")"
    
    if [[ "$(uname)" == "Darwin" ]] ; then
      ifconfig | fgrep 'inet ' | fgrep -v 127.0.0. | cut -d ' ' -f 2 | egrep -q "$regexp"
    else
      hostname -I | tr -s " " "\012" | fgrep -v 127.0.0. | egrep -q "$regexp"
    fi
    
    if [[ $? == 0 ]]; then 
      exit $on
    else
      exit $off
    fi
    

    Then in his .ssh/config file, he uses Match exec like Jakuje's answer:

    Match exec "onsubnet 10.10.1." host my-server
        HostName web.example.com
        Port 1111
        ForwardAgent yes
        ProxyCommand ssh -p 110 -q relay.example.com nc %h %p
    
    Match exec "onsubnet --not 10.10.1." host my-server
        HostName web.example.com
        Port 1111
    

提交回复
热议问题