kyopages/scripts/getIp

1039 lines
35 KiB
Bash
Executable File

#!/bin/bash
version=2.16.0
date="28/06/2018"
script="getIp"
# contact="IRC ##sdeb@freenode.net ou https://framagit.org/sdeb/getIp/issues"
##### license LPRAB/WTFPL
# auteur: sdeb
# contributeurs: kyodev
#####
# shellcheck disable=SC2034
f__color(){ # 29/05/2018
if type -p tput &>/dev/null && tput setaf 1 &>/dev/null; then
MAGENTA=$( tput setaf 5 )
BLACK=$( tput setaf 0 )
CYAN=$( tput setaf 6 )
YELLOW=$( tput setaf 3 ) # question
GREEN=$( tput setaf 2 ) # ok
BLUE=$( tput setaf 4 ) # info
RED=$( tput setaf 1 ) # alerte
STD=$( tput sgr0 ) # retour "normal"
BOLD=$( tput bold )
ITAL=$( tput sitm )
SOUL=$( tput smul )
else
YELLOW=$'\033[0;33m' # ?
GREEN=$'\033[0;32m' # ok
BLUE=$'\033[0;34m' # info
RED=$'\033[0;31m' # alerte
STD=$'\033[0m' # standard
fi
}
# $1=-c|-l|-lc, $2 répertoire, [$3] motif exclusion sur nom fichier, affiche 0|null si répertoire inexistant
# -c: compte du nombre de fichiers dans un répertoire
# -l: liste inline des noms de fichiers seuls (sans chemin) (similaire ls)
# -lc: liste en colonne des noms de fichiers seuls (sans chemin) (similaire ls -1)
# si joker (*?) sur chemin, le motif d'exclusion ne s'applique pas à un répertoire listé, juste sur le nom du fichier
# exemple: f__dir -l $dir "lock|partial" ou "\.list"
f__dir(){ # 05/03/2017
local i=0 action="-c" stock=''
[[ "$1" =~ - ]] && action="$1" || action="-c" # si option en erreur: -c par défaut
while read -r ; do
if [[ ! "$REPLY" =~ $3 ]] || [ -z "$3" ]; then
REPLY=${REPLY#*:} # suppression du titre de répertoire listé
[ -z "$REPLY" ] && continue # ligne vide, on passe
((i++))
stock+="$REPLY "
fi
done <<< "$( ls "$2" 2>/dev/null )"
if [ "$action" == "-c" ]; then
echo "$i"
elif [ "$action" == "-l" ]; then
echo "${stock% }"
elif [ "$action" == "-lc" ]; then
stock=${stock% }
echo -e "${stock// /$'\n'}"
fi
}
# affichage $1 en rouge, $1++ optionnels en bleu, sortie script sur erreur, log $1 si $operation=upgrade
f__error(){ # 07/O6/2018
local depart=1 i
echo -e "\\n$RED $script $version, erreur critique: $1 $STD" >&2
for (( i=2 ; i<=$# ; i++ )); do
echo -e " $BLUE${!i}$STD" >&2
done
echo
[ "$operation" == "upgrade" ] && f__log "$script $version: $1"
exit 1
}
# affichage en bleu, si $1=raw pas de ligne vide à la fin, si $1=log alors uniquement $2 logué, combiné: $1="log:raw"
f__info(){ # 07/06/2018
local depart=1 log i
if [[ "$1" =~ "raw" || "$1" =~ "log" ]]; then
depart=2
fi
if [[ "$1" =~ "log" ]]; then
log="$2"
log=${log//$'\t'}
log=${log//$'\n'}
f__trim log
f__log "$log"
fi
for (( i=depart ; i<=$# ; i++ )); do
echo -e " $BLUE${!i}$STD"
done
[[ "$1" =~ raw ]] || echo
}
# log spécifique, fichier log limité à 10000 octets, $1 message à loguer
f__log(){ # 05/03/2018
if [ -w "$script_logs" ]; then
if [ "$( stat -c %s "$script_logs" )" -ge "10000" ]; then
echo "$(date +%Y%m%d\ %H%M%S) $1" &>/dev/null > "$script_logs"
else
echo "$(date +%Y%m%d\ %H%M%S) $1" &>/dev/null >> "$script_logs"
fi
fi
}
# $1=bas-haut (ex: 0-5), nombre aléatoire entre bas & haut inclus, si [$2=seq] liste avec départ aléatoire
f__random(){ # 17/06/2018
local bas haut max rand start sequence xyz
bas=${1%%-*}
haut=${1#*-}
(( bas < 0 || haut < 0 )) && return 1
max=$(( 32768 / ( haut + 1 ) * ( haut + 1 ) ))
while (( (rand=RANDOM) >= max )); do : ; done
if [ "$2" == "seq" ]; then
start=$(( bas + ( rand % (haut+1-bas) ) ))
for (( xyz=start; xyz <= haut; xyz++ )); do echo "$xyz"; done
(( (start-bas) > 0 )) && for (( xyz=bas; xyz < start; xyz++ )); do echo "$xyz"; done
return
fi
echo $(( bas + ( rand % (haut+1 -bas) ) ))
}
# recherche commandes/paquets, $1 liste: cmd1|cmd2[>paquet] (séparées par espaces) ex: "gawk|mawk>gawk wget"
# si manque, return 1 & affiche commandes manquantes (si debian, ajout proposition paquet à installer)
f__requis(){ # 11/06/2018
local ENV_DEBIAN c_echo ireq cmds package commands command commandsMissing packagesMissing
if type -p dpkg &>/dev/null ; then
ENV_DEBIAN="oui" # debian
fi
if type -t f__info &>/dev/null; then
c_echo="f__info"
else
c_echo="echo -e" # f__info existe? sinon echo
fi
for ireq in $1; do
IFS='>' read -r cmds package <<< "$ireq" # ex: "awk|gawk>gawk wget file tar killall>psmisc"
mapfile -t -d '|' commands <<< "${cmds}"
[ -z "$package" ] && package=${commands[0]%$'\n'} # pas de packages dans les options, donc = commands[0]
for command in "${commands[@]%$'\n'}"; do
if type -p "$command" &>/dev/null ; then
unset commandsMissing packagesMissing
break
else # inexistant
commandsMissing+="$command "
packagesMissing+="$package "
fi
done
done
# dédoublonnage & triage
commandsMissing=$( echo "$commandsMissing" | tr ' ' '\n' | sort --unique | tr '\n' ' ' )
packagesMissing=$( echo "$packagesMissing" | tr ' ' '\n' | sort --unique | tr '\n' ' ' )
# suppression éventuel espace final
commandsMissing=${commandsMissing% }
packagesMissing=${packagesMissing% }
# affichage final
if [ "$commandsMissing" ] && [ "$ENV_DEBIAN" ]; then
$c_echo "${RED}erreur critique, manquant: $STD$BOLD$commandsMissing" \
"vous devriez exécuter:$GREEN apt install $packagesMissing"
elif [ "$commandsMissing" ]; then
$c_echo "${RED}erreur critique, manquant: $STD$BOLD$commandsMissing"
fi
[ "$commandsMissing" ] && return 1 || return 0
}
# $@=cmd à lancer en root avec su ou sudo. si sudo possible: prioritairesu su
f__sudo(){ # 11/06/2018
if sudo -v &>/dev/null && [ $EUID -ne 0 ] ; then
sudo su --preserve-environment -c "$@"
else
echo -n "[su] "
su --preserve-environment -c "$@"
fi
}
# $1=NOM de la variable à trimer (variable et non $variable), [$2=left|right|all], all si vide
f__trim(){ # 07/03/2018
local trim=${!1}
[[ "$2" == right || "$2" == all || -z "$2" ]] && trim="${trim%${trim##*[^[:space:]]}}" # fin right
[[ "$2" == left || "$2" == all || -z "$2" ]] && trim="${trim#${trim%%[^[:space:]]*}}" # début left
eval "$1=\"$trim\""
}
# user ayant initié la session graphique, assigne $fu_user
# return 1 sur échec identification user, return 2 sur absence home/
# gestion variable environnement user avec: USER_INSTALL=<user> script
f__user(){ # 08/03/2018
local user userid root_login
root_login="$(grep ':0:' /etc/passwd | cut -d':' -f1)" || root_login="root"
if [ "$USER_INSTALL" ]; then # user via variable environnement, moyen d'injecter root si pb
fu_user="$USER_INSTALL";
return 0
elif [[ "$TERM" =~ linux ]]; then #debian 9 recovery ou nomodeset TERM=linux
if [ "$USER" ]; then
user="$USER"
elif [ "$EUID" -eq 0 ]; then
fu_user="$root_login"
return 0
fi
fi
if [ "$SUDO_UID" ]; then
userid="$SUDO_UID";
elif grep -qEo '[0-9]+' <<< "$XDG_RUNTIME_DIR" ; then
userid=$( grep -Eo '[0-9]+' <<< "$XDG_RUNTIME_DIR" | cut -d'/' -f4 )
else
userid=$( grep -Eo '[0-9]+' <<< "$XAUTHORITY" | cut -d'/' -f4 )
fi
[ "$userid" ] && user=$( grep "$userid" /etc/passwd | cut -d ":" -f 1 )
if [ "$user" ] && [ "$user" != "$root_login" ]; then
fu_user="$user"
return 0
else
if [ "$SUDO_USER" ] && [ "$SUDO_USER" != "$root_login" ]; then
user="$SUDO_USER";
elif who | grep -qv 'root'; then
user=$( who | grep -v 'root' | head -n1 | cut -d ' ' -f1 ); # who | grep -v 'root' | awk 'FNR==1{print $1}'
else
user=$( grep -m1 'hourly.*get[A-Z].*\.anacrontab.*\.config/anacron/spool' /etc/crontab | cut -d' ' -f2 );
fi
fi
fu_user="$user"
[ "$fu_user" ] || return 1
[ -d "/home/$fu_user" ] || return 2
return 0
}
# $1='-l' lines, comptage ligne NON VIDE dans $var, affiche quantité de lignes NON VIDES
# si supplément -alnum, seules les lignes commençants pas des caractères alphanumériques sont comptabilisées
# $1='-w' words, comptage dans $var des mots, affiche quantité de mots dans $var
# $1='-o' occurrences, comptage dans $var, du <mot>, affiche quantité de <mot> dans $var
# f__wc -l $var | f__wc -w $var | f__wc $var -o <mot> ou f__wc -o <mot> $var
f__wc(){ # 28/06/2018
local data todo counter stck scan
while (( $# )) ; do
case "$1" in
-l ) todo='line' ;;
-alnum | -an ) alnum='yes' ;;
-w ) todo='words' ;;
-o ) todo='words_variable'; occurrence="$2" ; shift;;
* ) data="$1" ;;
esac
shift
done
while read -r; do
if [[ $todo == line && ! $REPLY =~ ^[[:blank:]]*$ ]]; then # wc -l compterait 1 pour une variable vide
[[ "$alnum" && ! $REPLY =~ ^[[:alnum:]] ]] && continue
(( counter++ ))
elif [[ $todo == words || $todo == words_variable ]]; then
stck+="$REPLY "
fi
done <<< "$data"
if [ "$todo" == 'line' ]; then
echo $(( counter ))
elif [ "$todo" == 'words' ]; then
read -ra stck <<< "$stck"
echo $(( ${#stck[@]} ))
elif [ "$todo" == 'words_variable' ]; then
read -ra stck <<< "$stck"
for scan in "${stck[@]}"; do
[[ $scan =~ $occurrence ]] && (( counter++ ))
done
echo $(( counter ))
fi
}
# test wget, $1=url à tester, $2=''|print|loc|test
# par défaut, sortie du script (même si url testée ok) avec affichage erreur ou ok
# si $2=print affiche url testée & entêtes http & location, return 0
# si $2=loc affiche seulement location, return 0
# si $2=test return 0 si ok, return 1 si KO
f__wget_test(){ # 07/06/2018
local file_test_wget="/tmp/testWget-$script" retourWget retourHttp location
wget -Sq --timeout=5 --tries=2 --user-agent="$user_agent" --spider --save-headers "$1" &>"$file_test_wget"
retourWget="$?"
[ "$retourWget" == 1 ] && retourWget="1: code erreur générique"
[ "$retourWget" == 2 ] && retourWget="2: parse erreur (ligne de commande?)"
[ "$retourWget" == 3 ] && retourWget="3: erreur Entrée/sortie fichier"
[ "$retourWget" == 4 ] && retourWget="4: défaut réseau"
[ "$retourWget" == 5 ] && retourWget="5: défaut vérification SSL"
[ "$retourWget" == 6 ] && retourWget="6: défaut authentification"
[ "$retourWget" == 7 ] && retourWget="7: erreur de protocole"
[ "$retourWget" == 8 ] && retourWget="8: réponse serveur en erreur"
retourHttp=$( grep -i 'HTTP/' "$file_test_wget" | tr -d '\n' | xargs )
location=$( grep -i 'location' $file_test_wget | xargs )
if [ "$2" == "test" ]; then
rm -f "$file_test_wget"
# spécial maintenance frama.link, pas de redirection sur page status framalink
grep -q '303' <<< "$retourHttp" && return 1 # 303 See Other
[ "$retourWget" == "0" ] && return 0 || return 1
fi
if [ "$2" == "print" ]; then
if [ "$retourWget" != "0" ]; then
echo " erreur wget: erreur $RED$retourWget"
echo -e "$BLUE $1$STD\\t$RED $retourHttp$STD"
else
echo -e "$BLUE $1$STD\\t$GREEN $retourHttp$STD"
fi
fi
if [ "$2" == "print" ] || [ "$2" == "loc" ]; then
[ "$location" ] && echo -n "$YELLOW $location" || echo -n "$YELLOW no location"
echo "$STD"
rm -f "$file_test_wget"
return 0
fi
if [ "$retourWget" != "0" ]; then
rm -f "$file_test_wget"
f__error "wget, erreur $retourWget" "$1" "$YELLOW$retourHttp" "$location"
echo -e "$RED erreur wget, $retourWget \\n $1 \\n $YELLOW$retourHttp \\n $location$STD" # pour les diags
return 1
fi
if grep -q '200' <<< "$retourHttp"; then
echo -e "$GREEN\\ntout est ok, réessayer$STD\\n"
fi
rm -f "$file_test_wget"
exit 0
}
# shellcheck disable=SC1117
f_affichage(){ # 16/06/2018
(( x_logo == 1 )) && return
x_logo=1
clear 2>/dev/null || tput clear 2>/dev/null
echo -n "$BLUE"
cat <<- end
_ ___
__ _ ___| |_|_ _|_ __
/ _' |/ _ \ __|| || '_ \
| (_| | __/ |_ | || |_) |
\__, |\___|\__|___| .__/
|___/ |_|
end
tput cuu1 # une ligne plus haut
tput cuf 10 # 10 caractères à droite
echo -n "$YELLOW$version"
tput cuf 10 # 10 caractères à droite
echo -e "$date$STD\n"
}
f_help(){ # 18/06/2018
cat <<- end
${GREEN}./getIp :$STD exécution script
${GREEN}getIp :$STD exécution script installé dans le système
ce script requiert une des commandes suivantes pour déterminer l'ip publique:
dig (dnsutils) | wget | curl
-----------------------------------------------------------------------
$BLUE$script -4$STD, --ip4 : affiche ipv4 public
$BLUE$script -6$STD, --ip6 : affiche ipv6 public
$BLUE$script -46$STD --public : affiche ipv4 & ipv6 public
$BLUE$script ''$STD, --local : affiche adresses mac / ip privées / passerelle
$BLUE$script -us$STD : upgrade spécial du script en place (sans être installé)
$GREEN --dev :$STD une version de dev du script (si existante) est recherchée
-----------------------------------------------------------------------
$BLUE./$script -i$STD : installation du script dans le système $RED(root)$STD
$BLUE$script -h$STD, --help : affichage aide
$BLUE$script -r$STD, --remove : désinstallation du script $RED(root)$STD
$BLUE$script -u$STD, --upgrade : mise à jour script
$BLUE$script -v$STD, --version : version du script, installée et en ligne
-----------------------------------------------------------------------
plus d'infos: $GREEN$url_notice$STD
end
}
# $1 [-4|-6], par défaut -4, affiche ip pub, return 1 on failure
# requiert f_n_cnx & f_ip_validate & f__random & f__log & f_n_dig
f_ip_pub(){ # 17/06/2018
local proto="-4" ip_pub base_size cmd sequence xyz server user_agent="Mozilla/5.0 Firefox"
declare -a base cmds raw4 raw6 dns4 dns6
{ # ip servers
raw4=(
v4.ident.me # raw ip4 only
ipv4.whatismyip.akamai.com # raw ip4 only
alma.ch/myip.cgi # raw ip4 only
api.infoip.io/ip # raw ip4 only
api.ipify.org # raw ip4 only
myip.dnsdynamic.org # raw ip4 only
ipecho.net/plain # raw ip4 only
ipinfo.io/ip # raw ip4 only
eth0.me # raw ip4 only
# checkip.amazonaws.com # raw ip4 only lent O4/2018
#~ ifconfig.me/ip # raw ip4 only pas fiable
)
raw6=(
v6.ident.me # raw, ip6 defaut
ipv6.whatismyip.akamai.com # raw, ip6 defaut
ip.tyk.nu # raw, ip6 defaut
myexternalip.com/raw # raw, ip6 defaut parfois ip4
smart-ip.net/myip # raw, ip6 defaut ! requiert user-agent
diagnostic.opendns.com/myip # raw, ip6 defaut
icanhazip.com # raw, ip6 defaut
wtfismyip.com/text # raw, ip6 defaut
l2.io/ip # raw, ip6 defaut
tnx.nl/ip # raw, ip6 defaut
# canhazip.com # raw, ip6 defaut ne raccourcit pas les ip
# wgetip.com # raw, ip6 defaut ne raccourcit pas les ip
# bot.whatismyipaddress.com # raw, ip6 defaut pb parfois sort ip4
# ipof.in/txt # raw, ip6 defaut NRP
# ident.me # raw, ip6 defaut
)
dns4=(
"A myip.opendns.com @resolver1.opendns.com"
"A myip.opendns.com @resolver2.opendns.com"
"A myip.opendns.com @resolver3.opendns.com"
"A myip.opendns.com @resolver4.opendns.com"
"A whoami.akamai.net @ns1-1.akamaitech.net"
)
dns6=(
"AAAA myip.opendns.com @resolver1.ipv6-sandbox.opendns.com"
"AAAA myip.opendns.com @resolver2.ipv6-sandbox.opendns.com"
"TXT o-o.myaddr.l.google.com @ns1.google.com"
)
}
[[ "$1" == @(-4|4) ]] && proto="-4"
[[ "$1" == @(-6|6) ]] && proto="-6"
type -p host &>>/dev/null && cmds+=( "f_n_host nostd " ) # deprecated
type -p dig &>/dev/null || type -p drill &>/dev/null && cmds+=( "f_n_dig nostd" )
type -p wget &>/dev/null && cmds+=( "wget --user-agent=$user_agent --quiet --timeout=1 --tries=1 -o /dev/null -O -" )
type -p curl &>/dev/null && cmds+=( "curl --silent --location --retry 0 --max-time 1" )
if (( ${#cmds[@]} == 0 )); then
echo "f_ip_pub(): no available commands (host|dig|drill|wget|curl)" >&2
return 1
fi
for cmd in "${cmds[@]}"; do
if [[ "$proto" == '-4' && "$cmd" =~ ^(f_n_host|f_n_dig) ]] ; then
base=( "${dns4[@]}" )
elif [[ "$proto" == '-6' && "$cmd" =~ ^(f_n_host|f_n_dig) ]] ; then
base=( "${dns6[@]}" )
elif [[ "$proto" == '-4' && "$cmd" =~ ^(wget|curl) ]] ; then
base=( "${raw4[@]}" )
elif [[ "$proto" == '-6' && "$cmd" =~ ^(wget|curl) ]] ; then
base=( "${raw6[@]}" )
fi
base_size=$(( ${#base[@]} - 1 )) # array index 0
sequence=$( f__random "0-$base_size" seq ) # range: 0 to base_size
for ii in $sequence; do
read -r -a server <<< "${base[$ii]}"
[[ $cmd =~ ^host ]] && server=( "${server[@]#@}" )
ip_pub=$( $cmd "${server[@]}" )
f_ip_validate "$ip_pub" && break 2 # exit if valid ip
done
done
if [ -z "$ip_pub" ]; then
if type -t f__log &>/dev/null && ! f_n_cnx "$proto" ; then # f__log() exists & no connection
f__log --error "f_ip_pub(): no connection"
fi
return 1
fi
echo "$ip_pub"
}
# $1=ip, test si ip = ipv4 ou ipv6, return 0|1
f_ip_validate(){ # 17/06/2018
# ip6: https://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses ()https://stackoverflow.com/a/17871737/9580455)
local proto reg regex result
for proto in -4 -6; do
if [[ "$proto" == "-6" ]]; then
regex="^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$"
else
reg="(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])"
regex="^$reg\\.$reg\\.$reg\\.$reg$"
# regex_priv="^(127\\.$reg|10\\.$reg|172\\.(1[6-9]|2[0-9]|3[0-1])|192\\.168)\\.$reg\\.$reg$"
fi
if [[ "$1" =~ $regex ]]; then
unset result
break
else
result="fail"
fi
done
if [ "$result" ]; then
return 1
fi
}
# test connexion, [$1=-4|-6] protocole -4 par défaut, return 0|1
f_n_cnx(){ # 17/06/2018
local proto="-4" cmds cmd ip servers
if [[ "$1" == '-6' || "$1" == '6' ]]; then
proto="-6"
servers=(
2606:4700:4700::1111 # cloudfare
2001:7fd::1 # root K RIPE
2001:500:a8::e # root E nasa
2001:4860:4860::8888 # google
)
else
servers=(
1.1.1.1 # cloudfare
193.0.14.129 # root K RIPE
192.203.230.10 # root E nasa
195.135.221.140 # conncheck.opensuse.org
80.67.169.12 # ns0.fdn.fr
8.8.8.8 # google
)
fi
type -p ping &>/dev/null && cmds+=( "ping -c1 -w1 -U " )
type -p fping &>/dev/null && cmds+=( "fping --retry=0 --elapsed --stats " )
if (( ${#cmds[@]} == 0 )); then
echo "f_n_cnx(): no available commands (ping|fping)" >&2
return 1
fi
for cmd in "${cmds[@]}"; do
for ip in "${servers[@]}" ; do
$cmd "$proto" "$ip" &>/dev/null && return 0
done
done
if nc -4 -h &>/dev/null; then # pris en charge par netcat-openbsd
for ip in "${servers[@]}" ; do
nc "$proto" -z -w1 "$ip" 53 &>/dev/null && return 0 # paquet netcat-traditional debian obsolète, ne gère pas protocoles
done
fi
return 1
}
# use dig or drill according to availability, options: hostname [@server|type|nostd], display ip | n/a (equivalent + short), return 0|1
# dig has priority over drill if the two command are presents
# type : aaaa | a | txt | soa | mx | AAAA | A | TXT | SOA | MX , A by default
# option nostd, for dig only: +timeout=1 +retry=1
f_n_dig(){ # 23/06/2018
local shopt_ini options type='A' server hostname cmd line ip
! type -p dig &>/dev/null && ! type -p drill &>/dev/null && return 1
(( $# == 0 )) || [ "$1" == test ] && return
shopt_ini=$( shopt -p )
shopt -s nocasematch
while (( $# )) ; do
case "$1" in
nostd ) options+=( '+timeout=1' '+retry=1' ) ;;
aaaa | a | txt | soa | mx ) type="$1" ;;
@* ) server="$1" ;;
* ) hostname="$1" ;;
esac
shift
done
if type -p dig &>/dev/null; then
cmd=$( LC_ALL=C dig "${options[@]}" "$hostname" "${server[@]}" "${type[@]}" )
elif type -p drill &>/dev/null; then
cmd=$( LC_ALL=C drill "$hostname" "${server[@]}" "${type[@]}" )
fi
if [[ $cmd =~ answer:\ 0 ]]; then
ip='n/a'
elif [[ $cmd =~ answer:\ [1-9] ]]; then
while read -r -a line; do
if [[ ${line[0]}${line[2]}${line[3]} == ${hostname}\.IN$type ]]; then
ip+="${line[(( ${#line[@]} - 1 ))]%\.} "
if [[ "$type" == @(SOA|TXT) ]]; then
ip="${line[4]%\.}"
fi
fi
done <<< "$cmd"
ip="${ip% }"
fi
ip=${ip%\"} # txt
ip=${ip#\"} # txt
eval "$shopt_ini"
echo "$ip"
if [ "$ip" == "n/a" ]; then
return 1
fi
}
# options: hostname [@server|type|nostd], display ip | n/a (equivalent to dig + short), return 0|1
# type : aaaa | a | txt | soa | mx | AAAA | A | TXT | SOA | MX , A by default
# option nostd: -R1 -W1
f_n_host(){ # 23/06/2018
local shopt_ini type='A' options server hostname ip line
! type -p host &>/dev/null && return 1
(( $# == 0 )) || [ "$1" == test ] && return
shopt_ini=$( shopt -p )
shopt -s nocasematch
while (( $# )) ; do
case "$1" in
aaaa | a | txt | soa | mx ) type="$1" ;;
nostd ) options+=( '-R1' '-W1' ) ;;
@* ) server="${1#@}" ;;
* ) hostname="$1" ;;
esac
shift
done
while read -r -a line; do
if (( ${#line[@]} > 3 )); then
ip+="${line[(( ${#line[@]} - 1 ))]%\.} " # last field
if [[ "$type" == SOA ]]; then
ip="${line[4]%\.}"
fi
fi
done <<< "$( LC_ALL=C host "${options[@]}" -t "${type[@]}" "$hostname" "${server[@]}" )"
ip="${ip% }"
[[ $ip =~ not\ found ]] && ip='not found'
[[ $ip =~ has\ no\ $type\ record ]] && ip='no record'
ip=${ip%\"} # txt
ip=${ip#\"} # txt
eval "$shopt_ini"
echo "$ip"
if [[ "$ip" == 'not found' || "$ip" == 'no record' ]]; then
return 1
fi
}
# f_pr "1|2|3|titre1|titre2|hl|quote|flush" "texte" '[CONDITION test]'
# $1:
# 1|2|3 indentation, liste à puce, une puce par ligne
# l1|l2|l3 ligne, indentation, avec espaces
# titre1|titre2|titre3
# quote|hl|flush
# $2 texte à afficher
# $3 test éventuel, Si CONDITION ok -> affichage
# ATTENTION aux éventuelles collision $x dans ce cas:
# "[ \"$1\" != \"notitre\" ]" ou "[ $1 != notitre ]" (attention au manque de ")
# flush (f_pr flush) inutile si f_d(x) final
# $1 type, $2 texte, [$3] test /!\ assigne la variable parent $text
f_pr(){ # 16/06/2018
local preline='' line='' endline=" \\n"
[[ "$1" == 'titre1' ]] && preline=" $GREEN"
[[ "$1" == 'titre1' ]] && endline+="$STD"
[[ "$1" == 'titre2' ]] && preline+="$BOLD"
[[ "$1" == 'titre2' ]] && endline+="$STD"
[[ "$1" == 'l1' ]] && line="$( sed -E 's/(.*)/\1/ ' <<< "$2" )"
[[ "$1" == 'l2' ]] && line="$( sed -E 's/(.*)/ \1/ ' <<< "$2" )"
[[ "$1" == 'l3' ]] && line="$( sed -E 's/(.*)/ \1/ ' <<< "$2" )"
[[ "$line" ]] || line="$2" # utilisation $2 sans traitement à faire
if [[ "$3" ]]; then
eval "$3" || return 0 # évaluation de la CONDITION, si erreur: sortie
fi
if [[ "$1" == "hl" ]]; then # <hl>
text+="\\n---\\n\\n"
elif [[ "$1" ]]; then
text+="$preline$line$endline" # ligne formatée
else
text+="\\n" # newline
fi
}
# affichage ip, local
# shellcheck disable=SC2016
fi_ip(){ # 16/06/2018
local ifn_p4 text
figet_ip "-4" || f__error "iproute2 doit être installé" "il remplace net-tools qui n'est plus développé"
ifn_p4="$fg_ifn_prior"
f_pr titre1 "IPv4"
f_pr l2 "$fg_ip"
f_pr
if [ "$(f__wc -l "$fg_gws")" -gt 1 ]; then pluriel="s"; else unset pluriel; fi
f_pr l2 "passerelle$pluriel: ${fg_gws//$'\n'/ ⊗ }"
f_pr
figet_ip "-6"
f_pr titre1 "IPv6"
f_pr l2 "$fg_ip"
f_pr
if [ "$(f__wc -l "$fg_gws")" -gt 1 ]; then pluriel="s"; else unset pluriel; fi
f_pr l2 "passerelle$pluriel: ${fg_gws//$'\n'/ ⊗ }"
f_pr
if [ "$(f__wc -w "$fg_ifn_prior")" -gt 1 ]; then pluriel="s"; else unset pluriel; fi
f_pr l2 "interface$pluriel sortante$pluriel ipv6: $fg_ifn_prior" '[ "$fg_ifn_prior" ]'
if [ "$(f__wc -w "$ifn_p4")" -gt 1 ]; then pluriel="s"; else unset pluriel; fi
f_pr l2 "interface$pluriel sortante$pluriel ipv4: $ifn_p4" '[ "$ifn_p4" ]'
f_pr
if [ "$(f__wc -l "$fg_mac")" -gt 1 ]; then pluriel="s"; else unset pluriel; fi
f_pr titre1 "adresse$pluriel Mac:"
f_pr l2 "$fg_mac"
f_pr '[ "$fg_ip_deprec" ]'
f_pr titre1 "ipv6 dépréciées:" '[ "$fg_ip_deprec" ]'
f_pr l2 "$fg_ip_deprec" '[ "$fg_ip_deprec" ]'
f_pr '[ "$fg_ip_deprec" ]'
echo -en "$text\\n" #>> "$fileOutput"
}
# $1=-4|-6|-46 protocole, affichage ip publiques
fi_ip_pub(){ # 15/06/2018 SPÉCIFIQUE
local itest option="$1" ippub
option=${option//-46/-4 -6}
for itest in $option; do
itest=-${itest//-}
if ippub=$(f_ip_pub "$itest"); then
echo "$BOLD$ippub$STD"
else
echo "pas de connectivité ipv${itest#-}"
fi
done
}
# $1=-4|-6, assigne $fg_ip, $fg_gws, $fg_ifn, $fg_mac, fg_ip_deprec (ipv6)
figet_ip(){ # 06/03/2018
local target ifn
unset fg_ip fg_ip_deprec fg_gws fg_ifn_prior fg_ifn fg_mac
type -p ip &>/dev/null || return 1
[ "$1" ] && proto="$1" || proto="-4"
# adresses ip
fg_ip=$( ip $proto -o address | awk -v proto="$proto" '
BEGIN { if (proto == -6) larg=41; else larg=16 }
/scope global/ {
sub(/wl.*/,$2" (wifi)",$2); sub(/.*en.*|.*eth.*/,$2" (ethernet)",$2);
printf "%-17s: %-"larg"s ",$2,$4
if (proto == -6) {
match($0,/scope .*\\/); scope=substr($0,RSTART,RLENGTH)
sub(/scope /,"",scope); sub(/\\/,"",scope)
match($0,/preferred_lft .*sec/); lft=substr($0,RSTART,RLENGTH)
sub(/sec/,"s",lft); sub(/preferred_lft/,"lft",lft)
printf "(%s) %s \n",lft,scope }
else printf "\n" }
/fe80::/ {
sub(/wl.*/,$2" (wifi)",$2)
match($0,/scope .* \\/); scope=substr($0,RSTART,RLENGTH); sub(/scope /,"",scope); sub(/ \\/,"",scope)
link=link"\n"sprintf("%-17s: %-22s %s",$2,$4,scope) }
/ lo / { lo=sprintf("%s (loopback) : %s",$2,$4) }
END { printf "%s\n%s",link,lo }
' )
# ipv6, traitemenent adresses dynamiques
if [ "$proto" == "-6" ]; then
fg_ip_deprec=$( sed -n '/temporary deprecated dynamic/p' <<< "$fg_ip" )
fg_ip=$( sed '/temporary deprecated dynamic/d; /preferred_lft 0sec/d' <<< "$fg_ip" )
fi
# passerelles
fg_gws=$( ip $proto route | awk '
BEGIN { if (proto == -6) larg=42; else larg=12 }
/default via/ { printf "%-"larg"s (%s)\n",$3,$5 }
' )
# interface sortante
if [ "$proto" == "-6" ]; then
target=$( ip $proto -o route | awk '/proto ra / { print $1; exit}' )
if [ "$target" ]; then
fg_ifn_prior=$( ip $proto route get "$target" | sed -En 's/.*dev (.*) proto.*src ([0-9a-f:]+).*/\1 (\2)/p' )
fi
else
fg_ifn_prior=$( ip $proto route get 255.255.255.255 | sed -En 's/.*dev (.*) src ([0-9.]+) .*/\1 (\2)/p' )
fi
# ifnames & mac
fg_ifn="" fg_mac=""
for ifn in $( f__dir -l /sys/class/net/ ) ; do
if [ "$ifn" != "lo" ]; then
fg_ifn+="$ifn "
fg_mac+="$ifn: $( cat "/sys/class/net/$ifn/address" )"$'\n'
fi
done
fg_ifn=${fg_ifn% } # suppression dernier espace
fg_mac=${fg_mac%[[:cntrl:]]} # suppression dernier $'\n'
}
# anacron hebdomadaire, via cron horaire, $1=upgrade|install|remove
fscript_cronAnacron(){ # 11/06/2018
local dirAnacron dirSpool fileAnacron
type -t fscript_cronAnacron_special &>/dev/null && fscript_cronAnacron_special # test, si fonction spécifique, appel
dirAnacron="/home/$fu_user/.config/anacron"
dirSpool="$dirAnacron/spool"
fileAnacron="$dirAnacron/$script.anacrontab"
[ "$EUID" -eq 0 ] && sed -i "/$script.anacrontab/d" /etc/crontab
case "$1" in
install | upgrade )
mkdir -p "$dirAnacron"
# table anacron
echo "7 10 $script nice $script_install --upgrade 1>/dev/null" > "$fileAnacron" # juste erreurs en syslog
## anacron journalier pour dev logname
if [ -e "$fileDev" ]; then
echo "1 00 ${script}Dev nice $script_install --upgrade 1>/dev/null" >> "$fileAnacron"
fi
# création spool anacron utilisateur
mkdir -p "$dirSpool"
chown -R "$fu_user:" "$dirAnacron" "$dirSpool"
if [ "$EUID" -eq 0 ]; then
# crontab pour activation horaire anacron
echo "@hourly $fu_user /usr/sbin/anacron -t $fileAnacron -S $dirSpool" >> /etc/crontab
fi
grep -q "$script" "/etc/crontab" || echo f__error "inscription crontab"
;;
remove )
rm -f "${dirSpool:?}/$script"*
rm -f "$fileAnacron"
rmdir "$${dirSpool:?}" "${dirAnacron:?}" 2>/dev/null
;;
esac
}
# assigne $ver_script_install, $ver_script_online, $script_a_jour=ok|KO
fscript_get_version(){ # 09/06/2018
x_script_get_version=1
# version online
if ver_script_online=$( wget -q --timeout=15 -o /dev/null -O - "$url_script" ); then
ver_script_online=${ver_script_online#*version=}
read -r ver_script_online <<< "$ver_script_online"
else
f__wget_test "$url_script"
fi
# version installée
if [ -e "$script_install" ]; then
while read -r ; do
if [[ "$REPLY" =~ ^version= ]]; then
ver_script_install=${REPLY#*=}
fi
done < "$script_install"
fi
# maj ?
if [[ "$ver_script_online" && "$script_install" ]]; then
if [ "$ver_script_install" != "$ver_script_online" ]; then
script_a_jour="KO"
else
script_a_jour="ok"
fi
fi
# affichage
ver_script_online=${ver_script_online:="${RED}n/a$STD"}
ver_script_install=${ver_script_install:="Non installé"}
f__info "raw" "script en place: $GREEN$ver_script_install"
f__info "script en ligne: $YELLOW$ver_script_online"
}
fscript_install(){ # 09/06/2018
if grep -Eq "$script_install|/usr/bin/$script" <<< "$0"; then
f__info "${RED}l'installation dans le système doit se faire depuis le script non installé $GREEN(./$script -i )"
return 1
fi
type -t fscript_install_special &>/dev/null && fscript_install_special # test, si fonction spécifique, appel
f__requis "wget anacron cron" || exit 1
# install /opt
mkdir -p /opt/bin/
cp "$0" "$script_install"
ln -s "$script_install" "/usr/bin/$script" 2>/dev/null
chmod 755 "$script_install"
# cron/anacron install
fscript_cronAnacron "install"
# création fichier log
touch "$script_logs"
chmod 644 "$script_logs"
chown "$fu_user:" "$script_logs" "$script_install"
[ -e "$fileDev" ] || rm -f "$0" ## on efface pas si fileDev (dev)
f__info "log" "$script $version installé dans le système." "maintenant, appel du script par: $GREEN$script$BLUE (sans ./)"
}
fscript_remove(){ # 09/06/2018
if ! grep -Eq "$script_install|/usr/bin/$script" <<< "$0"; then
f__info "${RED}cette fonction doit être appelée depuis le script installé dans le système $GREEN($script -r)"
return 1
fi
if [ ! -x "$script_install" ];then
f__info "$RED$script n'est pas installé"
return 1
fi
type -t fscript_remove_special &>/dev/null && fscript_remove_special # test, si fonction spécifique, appel
# suppression /opt, lien /usr/bin
rm -f "$script_install"
unlink "/usr/bin/$script" 2>/dev/null
# cron/anacron remove
fscript_cronAnacron "remove"
f__info "log" "$script $version supprimé du système."
}
# $1: update standard $1=std, si update en place $1=message d'info
fscript_update(){ # 11/06/2018
local dirTemp="/tmp/$script-maj" upgradeEnPlace
[ "$1" != 'std' ] && upgradeEnPlace="$1"
type -t fscript_update_special &>/dev/null && fscript_update_special # test, si fonction spécifique, appel
if [ -z "$upgradeEnPlace" ] && ! grep -Eq "$script_install|/usr/bin/$script" <<< "$0"; then
f__info "${RED}cette fonction doit être appelée depuis le script installé dans le système $GREEN($script -u)"
return 1
fi
(( x_script_get_version == 1 )) || fscript_get_version
if [ "$script_a_jour" == "ok" ]; then
f__info "log" "pas de mise à jour disponible pour $script $version"
return 0
else
f__info "mise à jour en cours"
fi
mkdir -p "$dirTemp"
if ! wget -q --tries=2 --timeout=15 -o /dev/null -O "$dirTemp/$script" "$url_script"; then
rm -fr "$dirTemp"
f__wget_test "$url_script"
fi
if grep -q '#!/bin/bash' "$dirTemp/$script" && grep -q '^### END CONTROL' "$dirTemp/$script"; then
cp "$dirTemp/$script" "$script_install"
chmod 755 "$script_install"
chown "$fu_user:" "$script_install"
[ -z "$upgradeEnPlace" ] && fscript_cronAnacron "upgrade"
f__info "log" "$script mis à jour en version $ver_script_online $upgradeEnPlace"
else
f_info "log" "$script: échec update" "mauvais téléchargement, réessayer plus tard"
fi
rm -fr "$dirTemp"
}
test_user(){ # 09/03/2018
# détermination user derrière root
f__user
retourFUser="$?"
[ "$retourFUser" -eq 1 ] && f__error "user indéterminé" \
"pour contourner, lancer le script avec:\\n$GREEN USER_INSTALL=<user> $0 \\n"
if [ "$retourFUser" -eq 2 ]; then
if [ "$EUID" -eq 0 ]; then
fu_user="root"
else
f__error "user détecté, mais pas de home: /home/$fu_user"
fi
f__info "user root"
fi
}
prg_init(){ # 15/06/2018
PATH='/usr/sbin:/usr/bin:/sbin:/bin'
TERM=xterm
IFS=$' \t\n'
export PATH TERM IFS
# options bash figées
shopt -s checkwinsize complete_fullquote extglob extquote interactive_comments sourcepath
shopt -u force_fignore execfail failglob
# test bash v4
[ "${BASH_VERSINFO[0]}" == 4 ] || f__error "bash v4 requis" "version installée: $BASH_VERSION"
# requis pour fonctionnement programme
f__requis "gawk|mawk>gawk wget ip>iproute2" || exit 1
# définition couleurs
f__color
}
######## début script / initialisation
# tests au démarrage
prg_init
# paramètres script
user_agent="Mozilla/5.0 Firefox"
fileDev="/opt/bin/fileDev"
script_install="/opt/bin/$script"
script_logs="/var/log/sdeb_$script.log"
url_script="https://framagit.org/sdeb/getIp/raw/master/getIp"
url_notice="https://framaclic.org/h/doc-getip"
script_options="$*"
# options
while (( $# )) ; do
case "$1" in
--dev ) url_script=${url_script//\/master\///dev/} ;;
* ) options+=( "$1" ) ;;
esac
shift
done
(( ${#options[@]} == 0 )) && options=( --local ) # vide help (si fileDev), sinon install
#actions
for i in "${!options[@]}"; do
# shellcheck disable=SC2221,SC2222
case ${options[$i]} in
-i | --install | -r | --remove )
if [ "$EUID" -ne 0 ]; then
f__info raw "vous devez être$RED ROOT$BLUE pour cette opération"
f__sudo "exec $0 $script_options"
exit
fi ;;&
!(--public|-4|-6|-46|-64) )
f_affichage
echo ;;&
-i | --install | -r | --remove | -u | --upgrade | -us )
test_user ;;&
-4 | --ip4 ) # affiche ip v4 public
fi_ip_pub "-4" ;;
-6 | --ip6 ) # affiche ip v6 public
fi_ip_pub "-6" ;;
-46 | -64 | --public ) # ip v4 & v6
fi_ip_pub "-46" ;;
--local ) # affiche ip locales
fi_ip ;;
-i | --install ) # installation du script dans le système
fscript_install ;;
-r | --remove ) # suppression du script dans le système
fscript_remove ;;
-u | --upgrade ) # upgrade script si maj possible
operation="upgrade" # log si f__error
fscript_update std # std argument obligatoire pour upgrade normal
exit ;;
-us ) # upgrade spécial
operation="upgrade" # log si f__error
script_install="$( dirname "$0" )/$script"
fscript_update "update en place" # redéfinition répertoire install avec celui du script
exit ;;
-v | --version ) # version du script, en ligne et exécuté
fscript_get_version ;;
-h | --help | * ) # affichage help
f_help ;;
esac
done
exit 0
### END CONTROL (contrôle chargement)
wget -nv -O getIp https://frama.link/getip
curl -L -o getIp https://frama.link/getip
chmod +x getIp && ./getIp
wget -nv -O getIp https://framagit.org/sdeb/getIp/raw/master/getIp
curl -LO https://framagit.org/sdeb/getIp/raw/master/getIp