#!/bin/bash # usage: # [[ $(host_reachable host.net) ]] && echo sure || echo nope # or # host_reachable &> /dev/null && echo sure || echo nope # or host_reachable () { # usage: host_reachable < -F configfile > host < port > # reachable returns yes and return 0 # return 1 - not reachable # return 2 no method available to try local host; local config function try( ) ( if [[ $(command -v nmap) ]] && [[ $2 ]]; then [[ $(nmap $1 -PN -p $2 | grep open) ]] && echo yes && return 0 || return 1 fi if [[ $(command -v nc) ]] && [[ $2 ]]; then [[ $(nc -w 2 $1 $2) ]] && echo yes && return 0 || return 1 fi if [[ $(command -v ping) ]]; then ping -c1 -W1 $1 &> /dev/null && echo yes && return 0 || return 1 fi return 2 # return 2 to indicate no method was available ) [[ $1 = "-F " ]] && { config=$2;shift 2; } host=$(lookup_host $1 $config) try $host $2 return $? } lookup_host () { # usage: lookup_host hostname < configfile > local config; local host; local lhost config=$([[ $2 ]] && echo $2 || echo ${SSH_CONFIG:-$HOME/.ssh/config}) host=$(parse_host $1) lhost=$(ssh -F $config -G $host | grep -w hostname | cut -d' ' -f2) [[ $lhost ]] && echo $lhost || echo $host } parse_host () { # usage: parse_host # returns extracted host if passed user@host # otherwise return value passed [[ $1 =~ "@" ]] && { echo $(sed 's/.*@\(.*\)/\1/' <<< "$1");return 0; } echo $1 return 1 } parse_user () { # usage: parse_user # returns extracted user if passed user@host # otherwise returns nothing # return 1 no user in string [[ $1 =~ "@" ]] && { echo $(sed 's/\(.*\)@.*/\1/' <<< "$1"); return 0; } || return 1 } valid_ip() { # usage: valid_ip ip # check so see if basic format is correct and all subs or numbers, no returns 2 # then checks if they are 0 to 254, no returns 1 # otherwise if good returns "true" and 0 local ip=$1 local res if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then OIFS=$IFS IFS='.' ip=($ip) IFS=$OIFS [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \ && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]] res=$([ $? == 0 ] && echo true) [[ $res ]] && { echo $res;return 0; } return 1 fi return 2 } get_domain() { # usage: get_domain fulldomain # returns domain.tld # exampe: get_domain discuss.mydomain.com => returns mydomain.com local domain domain=$(echo $1 | awk -F\. '{print $(NF-1) FS $NF}') echo "$domain" }