skip to Main Content

I’d like to be able to run ssh 142 (for example) from a bash prompt and have it automatically expand to ssh 10.33.7.142. I’m thinking I should be able to do this from .bashrc, but I can’t figure out how to detect if a command-line argument is a single octet, and if so, automatically add a subnet before it.

I’d like to implement this on my CentOS LXC host nodes. The vast majority of the time when ssh is used on them it is to connect to a container running on them, all of which are in the same subnet.

Thank you.

2

Answers


  1. In ~/.ssh/config or /etc/ssh/ssh_config :

    Host 142
    Hostname 10.33.7.142
    

    Now you can run :

    ssh 142
    

    To generate the config file :

    #!/bin/bash
    
    while read host; do
        echo -e "Host $hostnHostname 10.33.7.$hostn"
    done < <(printf '%sn' {1..254})
    
    Login or Signup to reply.
  2. You could write a function in your .bashrc like this:

    ssh=$(which ssh) # the real ssh binary
    ssh(){
      if [[ "$1" =~ ^[0-9]+$ ]]; then # if first arg to ssh is an integer
        $ssh 10.33.7.$1               # then ssh with prepended subnet
      else
        $ssh $@                       # else just do some regular ssh
      fi
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search