kyopages/scripts/getInfo

2269 lines
96 KiB
Bash
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/bin/bash
version=2.19.6
date="28/10/2017"
projet="simpledeb"
contact="IRC freenode ##sdeb ou https://framagit.org/kyodev/kyopages/issues/"
script="getInfo"
##### license LPRAB/WTFPL
# auteur: simpledeb
# contributeurs: kyodev, saiqui, naguam, agentcobra
#####
# assigne $affichage_text
f__affichage(){ # 29/10/2017
f__color
affichage_text=" _ ___ __
__ _ ___| |_|_ _|_ __ / _| ___
/ _' |/ _ \ __|| || '_ \| |_ / _ \
| (_| | __/ |_ | || | | | _| (_) |
\__, |\___|\__|___|_| |_|_| \___/
|___/ "
clear
echo -e "$BLUE$affichage_text\n$YELLOW version $version - $date$STD\n"
}
# detect system architecture, assign $architecture : 32bits, i686 | 64bits, amd64, return 1 on unknown architecture
# remarque, debian: dpkg --print-architecture affiche i386
f__architecture(){ # 08/2017 spécifique
case "$(uname -m)" in
amd64 | x86_64 )
architecture="64bits, amd64";;
i?86 | x86 )
architecture="32bits, i686";;
* )
case "$(getconf LONG_BIT)" in
64 )
architecture="64bits, amd64";;
32 )
architecture="32bits, i686";;
*)
return 1
esac ;;
esac
}
# $1=commande à tester, return localisation cmd si existe, return 1 si absent avec aucun message (ala debian)
# pour un test concis genre [ "$(f__cmd_exist $cmd)" ] && echo "$cmd existe"
# utilisation `type -p` pour le test, pour une bonne portabilité
f__cmd_exist(){ # 22/10/2017
# command -v
if type -p "$1" &>/dev/null ; then
echo $(type -p $1)
else
return 1
fi
}
f__color(){ # 08/10/2017
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
MAGENTA=$(tput setaf 5)
CYAN=$(tput setaf 6)
BOLD=$(tput bold)
ITAL=$(tput sitm)
SOUL=$(tput smul)
}
# $1=oui|non&[-tx] réponse par défaut & -tx=timeout, $2=message question, return 0 pour oui, 1 pour non
f__dialog_oui_non(){ # 08/10/2017
local reply param
[[ "$1" =~ -t[0-9]{1,2} ]] && param="$(sed -En 's/.*(-t[0-9]{1,2}).*/\1/p' <<< $1)"
printf "$BLUE$2$STD"
[[ "$1" =~ oui ]] && printf " [O/n] " || printf " [o/N] "
if [ "$param" ]; then
read -t2 reply
else
read reply
fi
if [ -z "$reply" ]; then
[[ "$1" =~ oui ]] && reply="oui" || reply="non"
fi
echo
if [[ ${reply,,} =~ ^ou?i?$ ]]; then return 0; else return 1; fi
}
# affichage $1 en rouge, $1++ optionnels en bleu, sortie script sur erreur, log $1 si $opType=upgrade
f__error(){ # 15/10/2017
echo -e "\n$RED $script $version, erreur critique: $1 $STD"
for (( i=2 ; i<=$# ; i++ )); do
echo -e " $BLUE${!i}$STD"
done
echo
if [ "$opType" == "upgrade" ]; then f__log "$script $version: $1"; fi
exit 1
}
# conversion human, source ko, $1=nombre à convertir, affiche ko ou Mo ou Go, ! dépendance gawk
f__unit_human(){ # 09/10/2017
printf "$( gawk ' {
if ( $1<1024 ) {unit="ko"; printf "%d%s", $1, unit; exit}
if ( $1<1024*1024 && $1>=1024 ) {unit="Mo"; printf "%d%s", $1/1024, unit}
else {unit="Go"; printf "%.1f%s", $1/1024/1024, unit}
}' <<< $1 )"
}
# affichage des paramètres en bleu, si $1=raw pas de ligne vide à la fin, si $1=log alors uniquement $2 logué
f__info(){ # 15/10/2017
local depart=1 i
if [ "$1" == "raw" ] || [ "$1" == "log" ]; then depart=2; fi
[ "$1" == "log" ] && f__log "$(sed -E 's/\\t//;s/\\n// ' <<< $2 | xargs )"
for (( i=$depart ; i<=$# ; i++ )); do
echo -e " $BLUE${!i}$STD"
done
[ "$1" == raw ] || echo
}
# log spécifique, fichier log limité à 10000octets, $1 message à loguer
f__log(){ # 27/10/2017
if [ -w "$fileLogs" ]; then
if [ "$(stat -c %s $fileLogs)" -ge "10000" ]; then
echo "$(date +%Y%m%d\ %H%M%S) $1" &>/dev/null > "$fileLogs"
else
echo "$(date +%Y%m%d\ %H%M%S) $1" &>/dev/null >> "$fileLogs"
fi
fi
}
# test dépendances/paquets, $1 liste commande[>paquet] (ex: killall>psmisc)
# si manque, SORTIE & info commandes manquantes, si debian, SORTIE & proposition paquet à installer
# si $2=debOnly et si paquets manquants: return 1 et $debOnlyPackages ( $1=liste paquets )
# si $2=debOnly et si paquets présent: return 0 et $debOnlyPresents ( $1=liste paquets )
# attention priorité $debOnlyPackages sur $debOnlyPresents
f__requis(){ # 22/10/2017
local dependsMissing packagesMissing command package ireq compteur pluriel
unset debOnlyPackages debOnlyPresents
for ireq in $1; do
command="$(cut -d '>' -f 1 <<< $ireq)"
package="$(cut -d '>' -f 2 <<< $ireq)"
if [ "$2" == "debOnly" ]; then
if [ "$(f__cmd_exist dpkg)" ]; then # package only et debian
LC_ALL=C dpkg --get-selections | grep -qE "^$package[[:space:]]+install" \
&& debOnlyPresents+="$package " || debOnlyPackages+="$package "
else
f__error "dpkg n'est pas disponible sur ce système"
fi
elif [ -z "$(f__cmd_exist $command)" ]; then
dependsMissing+="$command "
packagesMissing+="$package "
fi
done
[ "$debOnlyPackages" ] && debOnlyPackages="$(xargs <<< $debOnlyPackages)" # trim début & fin
[ "$debOnlyPresents" ] && debOnlyPresents="$(xargs <<< $debOnlyPresents)" # trim début & fin
[ "$debOnlyPackages" ] && return 1
[ "$debOnlyPresents" ] && return 0
if [ "$dependsMissing" ]; then
compteur="$(wc -w <<< $dependsMissing)"
[ "$compteur" -gt "1" ] && pluriel="s" || unset pluriel
if [ -e /etc/debian_version ]; then
f__error "$compteur paquet$pluriel manquant$pluriel: $STD$BOLD$dependsMissing" \
"\n vous devriez exécuter:$GREEN apt install $packagesMissing"
else
f__error "$compteur commande$pluriel manquante$pluriel: $STD$BOLD$dependsMissing";
fi
fi
}
# $1=rep à scanner [$2=profondeur max|4 défaut] [$3=profondeur encours|0 défaut]
# affichage stdout si $fileOutput non définis, /usr/bin/strings (binutils) requis
f__scandir(){ # 17/10/2017
[ -d "$1" ] || f__error "erreur sur le répertoire à scanner"
f__requis "strings>binutils" # requis pour fonctionnement programme
local repToScan irep rc text prof prof_max tempo
[ "${1: -1}" == "/" ] && repToScan="$1" || repToScan="$1/" # ajout / final si besoin
[ "$2" ] && prof_max="$2" || prof_max=4 # profondeur max par défaut si besoin
[ "$3" ] && prof=$3 || prof=0 # initialisation compteur profondeur en cours si nécessaire (début)
text="répertoire: $repToScan \n"
for irep in $(ls $repToScan); do # contenu du répertoire
prof=$(( $prof+1 )) # niveau++
if [ -d "$repToScan$irep" ]; then # si c'est un répertoire
# si compteur niveau <= max, scandir, sinon suivant dans la boucle
[ "$prof" -le "$prof_max" ] && f__scandir "$repToScan$irep/" "$prof_max" "$prof" || continue
else # si c'est pas un répertoire
if [ ! -r "$repToScan$irep" ]; then # si fichier non lisible (read)
text+="$repToScan$irep : inaccessible en lecture \n"
continue # suivant dans la boucle
fi
# traitements fichier
[[ "$irep" == "uevent" || "$irep" == "modalias" ]] && rc=" \n" || unset rc
tempo="$(strings -aw -n1 $repToScan$irep)" # au moins 1 caractère, inclus white space, all tout le fichier
[ "$tempo" ] && text+="$irep: $rc$tempo \n" || text+="$irep: <vide> \n"
fi
prof=$(( prof-1 )) # niveau--
done
[ "$fileOutput" ] && echo -e "$text" >> "$fileOutput" # sauvegarde dans fichier si $fileOutput défini
[ "$fileOutput" ] || echo -e "$text" # affichage si $fileOutput non défini
}
# $1=cmd si $2: nb de tentatives pour s'identifier, sinon 2 tentatives par défaut
f__sudo(){ # 22/10/2017
local nb=2 sudo isudo
# sudo --shell bash équivalent su ?
if sudo -v &>/dev/null && [ $EUID -ne 0 ] ; then
sudo="sudo su --shell $(f__cmd_exist bash) --preserve-environment -c "
else
sudo="su --shell $(f__cmd_exist bash) --preserve-environment -c "
fi
[ "$2" ] && nb="$2"
for (( isudo=1 ; isudo<="$nb" ; isudo++ )); do
$sudo " $1"
[ "$?" == 0 ] && break
[ "$isudo" == "$nb" ] && return 1
done
}
# user ayant initié la session graphique, assigne $user_
# return 1 sur échec identification user, return 2 sur absence home/
# gestion variable environnement user avec: USER_INSTALL=user script
f__user(){ # 09/10/2017
local user_id test 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
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
user_="$root_login"
return 0
fi
fi
if [ "$SUDO_UID" ]; then
user_id="$SUDO_UID";
elif grep -qEo '[0-9]+' <<< "$XDG_RUNTIME_DIR" ; then
user_id="$(grep -Eo '[0-9]+' <<< $XDG_RUNTIME_DIR | cut -d'/' -f4)"
elif grep -qEo '[0-9]+' <<< "$XAUTHORITY" ; then
user_id="$(grep -Eo '[0-9]+' <<< $XAUTHORITY | cut -d'/' -f4)"
fi
[ "$user_id" ] && user_="$(grep $user_id /etc/passwd | cut -d ":" -f 1 )"
if [ "$user_" ] && [ "$user_" != "$root_login" ]; then
return 0
else
if [ "$SUDO_USER" ] && [ "$SUDO_USER" != "$root_login" ]; then
user_="$SUDO_USER";
elif grep -qv 'root' <<< "$(who)"; then
user_="$(grep -v 'root' <<< $(who) | head -n1 | cut -d ' ' -f1)"; # grep -v 'root' <<< $(who) | gawk 'FNR==1{print $1}'
elif grep -q 'hourly.*get[A-Z].*\.anacrontab.*\.config/anacron/spool' /etc/crontab; then
user_="$(grep 'hourly.*get[A-Z].*\.anacrontab.*\.config/anacron/spool' /etc/crontab | head -n1 | cut -d' ' -f2)"; # grep 'hourly.*get[A-Z].*\.anacrontab.*\.config/anacron/spool' /etc/crontab | gawk 'FNR==1{print $2}
fi
fi
if [ -z "$user_" ]; then return 1; fi
if [ ! -d "/home/$user_" ]; then return 2; fi
return 0
}
# test wget, $1 url à tester, sortie du script si $1 seul (même si url testée ok)
# si $2=print affiche url testée & entêtes http & location (si présente) et sortie normale fonction
# si $2=loc affiche seulement location et sortie normale fonction
# si $2=test return 0 si ok, return 1 si ko
f__wget_test(){ # 17/10/2017
local file_test_wget retourWget retourHttp location
file_test_wget="/tmp/testWget-$$-$RANDOM"
wget -Sq --timeout=10 --user-agent="$user_agent" --spider --save-headers "$1" &>"$file_test_wget"
retourWget="$?"
[ "$2" == "test" ] && rm "$file_test_wget"
[ "$2" == "test" ] && [ "$retourWget" == "0" ] && return 0 || return 1
[ "$retourWget" == 1 ] && retourWget="code erreur générique"
[ "$retourWget" == 2 ] && retourWget="parse erreur (ligne de commande?)"
[ "$retourWget" == 3 ] && retourWget="erreur Entrée/sortie fichier"
[ "$retourWget" == 4 ] && retourWget="défaut réseau"
[ "$retourWget" == 5 ] && retourWget="défaut vérification SSL"
[ "$retourWget" == 6 ] && retourWget="défaut authentification"
[ "$retourWget" == 7 ] && retourWget="erreur de protocole"
[ "$retourWget" == 8 ] && retourWget="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" == "print" ]; then
if [ "$retourWget" ]; then
echo "erreur wget: $RED$retourWget"
echo -e "$BLUE $1$STD\t$RED $retourHttp"
else
echo -e "$BLUE $1$STD\t$GREEN $retourHttp"
fi
fi
if [ "$2" == "print" ] || [ "$2" == "loc" ]; then
[ "$location" ] && echo "$YELLOW $location" || echo "$YELLOW no location"
echo "$STD"
return 0
fi
if [ "$retourWget" ]; then
rm "$file_test_wget"
f__error "erreur wget, $retourWget" "$1" "$YELLOW$retourHttp"
fi
if [ "$(grep -c '200' <<< $retourHttp)" -ne 0 ]; then
echo -e "$GREEN\ntout est ok, réessayer\n$STD"
fi
rm "$file_test_wget"
exit 0
}
# f_display: $1 variable à afficher, $2=var|cmd|sans (type titrage) [$3 titrage] [$4 commentaire titrage en gras si cmd]
# f_display "variable" "type" "titrage" "titrage_commentaire"
f_display(){ # 25/10/2017
[ "$text" ] && echo -en "$text" >> "$fileOutput" # flush avant fonction de text parent
unset text
local display=""
[[ "$2" == "sans" || "$2" == "var" || "$2" == "cmd" ]] || display="erreur script \$2 ($1 $2 $3)"
[ "$2" == "var" ] && display="**$3** \n"
[ "$2" == "cmd" ] && display="\`$3\` \n"
#echo $(sed -En 's/[^/]*(\/.*)$/\1/p' <<< "$3")
[[ "$2" == "cmd" && "$4" ]] && display="\`$3\` **$4** \n"
display+='``` \n'
display+="${!1} \n"
display+='``` \n'
echo -en "$display \n" >> "$fileOutput" # flush fonction
}
# $1 fichier testé
f_display_file(){ # 26/10/2017
echo -e "* fichier **$1** non trouvé ou absent \n" >> "$fileOutput"
}
# $1 répertoire à scanner, $2 profondeur
f_display_scandir(){ # 21/10/2017
[ "$text" ] && echo -e "$text" >> "$fileOutput" # flush avant fonction
unset text
local text
text="\`$1 $2\` \n"
text+='``` \n'
echo -e "$text" >> "$fileOutput" # flush avant scandir
unset text
if [ -d "$1" ]; then
f__scandir $1 $2
else
text="$1 inexistant \n"
fi
text+='``` \n'
echo -e "$text" >> "$fileOutput" # flush fonction
}
f_help(){ # 28/10/2017
printf "$BLUE"
cat << 'EOF'
./getInfo : exécution normale, rapport markdown de la configuration
getInfo : exécution normale si script installé dans le système
options:
-c : (catégorie) menu sélection catégorie d'analyse
-cs : catégorie système -cs : catégorie configuration
-cr : catégorie réseau -ca : catégorie analyse
-h : (help) affichage aide
-j : (journaux) analyse démarrage système, log Xorg, kernel et système, catégorie -ca
-l : (list) afficher le rapport markdown existant
-p : (paste) exporte le rapport markdown existant, durée standard du paste 7 jours
-tn : durée du paste de n jour(s)
-us : upgrade spécial du script (pas de mise à jour auto, maj du script en place)
--ip : affiche ip publique (ipv4/ipv6), infos confidentielles, pas de rapport markdown
--mac : affiche les adresses Mac, infos confidentielles, pas de rapport markdown
--ssid : affiche configurations ssid, infos confidentielles, pas de rapport markdown,
root et NetworkManager requis
--debug-batt : scan valeurs power_supply et rapport markdown
--debug-hw : scan valeurs hwmon et rapport markdown
--debug-dmi : scan valeurs dmi et rapport markdown
-i, --install : installation du script dans le système, root requis
-r, --remove : suppression du script dans le système, root requis
-u, --upgrade : upgrade script installé si maj possible
-v, --version : version du script, en ligne et en cours d'exécution
EOF
echo -e "$STD\n plus d'infos: $GREEN$urlNotice\n$STD"
}
fi_batt(){ # 25/10/2017
local pluriel
[ "$fg_nb_batt" ] || figet_batt # appel figet_battery si pas déjà fait par fi_systeme
[[ "$fg_nb_batt" == "-1" || "$fg_nb_batt" -gt 0 ]] || return 0 # pas de batterie
###
[ "$fg_nb_batt" -gt 1 ] && pluriel="s" || unset pluriel
text="## batterie$pluriel \n\n"
f_display "fg_batt" "sans"
printf "$text\n" >> "$fileOutput"
unset text
}
fi_cpu(){ # 25/10/2017
#manuellement: lscpu (util-linux)
local cpu_flags text pluriel
cpu_flags="$(sed -n 's/^flags.*: \(.*\)$/\1/p;' /proc/cpuinfo | sed -n '1p')"
[ "$fget_cpu" ] || figet_cpu
###
[ ${fget_cpu:0:1} -gt 1 ] && pluriel="s" || unset pluriel
text="## processeur$pluriel \n\n"
f_display "fget_cpu" "sans"
f_display "cpu_flags" "var" "flags cpu:"
printf "$text\n" >> "$fileOutput"
unset text
}
fi_disk(){ # 29/10/2017
local disk_lsblk disk_df disk_df_i fstab resume idResume idSwap alert_uuidResume text pluriel
local dd_temp dd_temp_alert dd_temp idisk tempodd
disk_lsblk="$(lsblk -o NAME,FSTYPE,SIZE,LABEL,MOUNTPOINT,UUID)"
disk_df="$(df -h --output=source,target,fstype,size,used,avail,pcent --exclude=tmpfs --exclude=devtmpfs | grep -Ev 'devpts|none|proc|sys|tmpfs|udev')"
disk_df_i="$(df -i --exclude=tmpfs --exclude=devtmpfs | grep -Ev 'devpts|none|proc|sys|tmpfs|udev')"
fstab="$(grep -Ev '^[[:blank:]]*#|^$' /etc/fstab)"
resume="$(grep -Evs '^[[:blank:]]*#|^$' /etc/initramfs-tools/conf.d/resume)"
if [ -z "$resume" ]; then
# alert resume absent
resume="Pas de fichier _resume_ dans /etc/initramfs-tools/conf.d/ \n"
resume+="Ce n'est pas (forcément) une erreur. \n"
resume+="La plus grosse partition swap est choisie dans ce cas. \n"
resume+="À investiguer si erreur au boot ou boot très long. \n"
fi
idResume="$(grep -Evs '^[[:blank:]]*#|^$' /etc/initramfs-tools/conf.d/resume | sed -En 's/.*UUID=([0-9a-Z-]*).*$/\1/p')"
idSwap="$(grep -Ev '^[[:blank:]]*#|^$' /etc/fstab | sed -En 's/UUID=([0-9a-Z-]*).*swap.*$/\1/p')"
if [ "$idSwap" ] && [ "$idResume" ] && [ "$idSwap" != "$idResume" ]; then
alert_uuidResume+="id swap : $idSwap \nid resume: $idResume\n"
alert_uuidResume+="**vérifier la config resume**, l'UUID ne correspond pas à celui du swap. \n"
alert_uuidResume+="vous pouvez utiliser _RESUME=auto_ ou _RESUME=/dev/sdx_, voir supprimer ce fichier"
fi
[ "$fget_nb_disk" ] || figet_disk # appel figet_disk si pas déjà fait par fi_systeme
if [ "$(f__cmd_exist hddtemp)" ]; then
unset dd_temp dd_temp_alert
for idisk in $fget_disk_fixe; do
[ -r "/dev/$idisk" ] || continue
tempodd="$(LC_ALL=C hddtemp /dev/$idisk | cut -d ':' -f3 | sed 's/[^0-9]*//g; /not available/d')"
dd_temp+="$idisk: $tempodd °C"$'\n'
[ "$tempodd" -ge 50 ] && dd_temp_alert+="/!\ $idisk: température > 50°C) "$'\n'
done
dd_temp=${dd_temp::-1} # suppression dernier $'\n'
dd_temp_alert=${dd_temp_alert::-1} # suppression dernier $'\n'
fi
###
[ "$fget_nb_disk" -gt 1 ] && pluriel="s" || unset pluriel
text="## disque$pluriel \n\n"
text+='``` \n'
# espace des partitions fixes montées
text+="$fget_disk_part_fix_tot \n\n"
# disques fixes et amovibles
[ "$(wc -w <<< $fget_disk_fixe)" -gt 1 ] && pluriel="s" || unset pluriel
text+="$(printf '%-17s: %s' "disque$pluriel fixe$pluriel" "$fget_disk_fixe") \n"
[ "$(wc -w <<< $fget_disk_amov)" -gt 1 ] && pluriel="s" || unset pluriel
text+="$(printf '%-17s: %s' "disque$pluriel amovible$pluriel" "$fget_disk_amov") \n\n"
# partitions fixes montées / swap / non montées
[ "$(wc -w <<< $fget_disk_part_fixe_m)" -gt 1 ] && pluriel="s" || unset pluriel
text+="$(printf '%-24s: %s' "partition$pluriel fixe$pluriel montée$pluriel" "$fget_disk_part_fixe_m") \n"
[ "$(wc -w <<< $fget_disk_part_swap)" -gt 1 ] && pluriel="s" || unset pluriel
text+="$(printf '%-24s: %s' "partition$pluriel swap$pluriel" "$fget_disk_part_swap") \n"
[ "$(wc -w <<< $fget_disk_part_fixe_nm)" -gt 1 ] && pluriel="s" || unset pluriel
text+="$(printf '%-28s: %s' "partition$pluriel fixe$pluriel non montée$pluriel" "$fget_disk_part_fixe_nm") \n\n"
# partitions amovibles montées / non montées
[ "$(wc -w <<< $fget_disk_part_amov_m)" -gt 1 ] && pluriel="s" || unset pluriel
text+="$(printf '%-32s: %s' "partition$pluriel amovible$pluriel montée$pluriel" "$fget_disk_part_amov_m") \n"
[ "$(wc -w <<< $fget_disk_part_amov_nm)" -gt 1 ] && pluriel="s" || unset pluriel
text+="$(printf '%-32s: %s' "partition$pluriel amovible$pluriel non montée$pluriel" "$fget_disk_part_amov_nm") \n\n"
# détails des disques
text+="$fget_disk_detail \n"
text+='``` \n\n'
text+="**types de disque** \n\n"
text+="| sata | usb | mmc | nvme | \n"
text+="| :---: | :---: | :---: | :---: | \n"
text+="| $fget_disk_ata | $fget_disk_usb | $fget_disk_mmc | $fget_disk_nvme | \n\n"
# éventuellement hddtemp
[ "$dd_temp" ] && f_display "dd_temp" "cmd" "hddtemp /dev/sd?" "(température disques)"
if [ "$dd_temp_alert" ]; then
text+="$dd_temp_alert \n"
text+="$dd_temp_alert_text \n\n"
fi
# df, espaces des partitions montées seules
f_display "disk_df" "cmd" \
"df -h --output=source,target,fstype,size,used,avail,pcent --exclude=tmpfs --exclude=devtmpfs" \
"(utilisation disques)"
# df -i, inoeuds
f_display "disk_df_i" "cmd" "df -i --exclude=tmpfs --exclude=devtmpfs" "(utilisation inoeuds)"
# lsblk
f_display "disk_lsblk" "cmd" "lsblk -o NAME,FSTYPE,SIZE,LABEL,MOUNTPOINT,UUID" "(disques)"
# fstab
f_display "fstab" "cmd" "grep -Ev '^[[:blank:]]*#|^$' /etc/fstab" "(fstab)"
# resume
f_display "resume" "cmd" "grep -Evs '^[[:blank:]]*#|^$' /etc/initramfs-tools/conf.d/resume" "(resume)"
if [ "$alert_uuidResume" ]; then
text+="$alert_uuidResume \n\n"
fi
printf "$text\n" >> "$fileOutput"
unset text
}
fi_dmesg(){ # 25/10/2017
local dmesg_err dmesg_warn dmesg_crit file text nb_lignes=25
file="/tmp/$$-$RANDOM-dmesg"
[ "$EUID" -eq 0 ] || echo
f__sudo "dmesg -Hk --nopager -l emerg > $file-emerg ; \
dmesg -Hk --nopager -l alert > $file-alert ; \
dmesg -Hk --nopager -l crit > $file-crit ; \
dmesg -Hk --nopager -l warn > $file-err ; \
dmesg -Hk --nopager -l warn > $file-warn ; \
chown $user_: $file-*"
if [ "$?" != "0" ]; then
f__info "\n les commandes$GREEN dmesg$RED ont échoué $BLUE(droits root requis, échec authentification?)" \
"vous pouvez relancer le script complet$RED en root$BLUE pour voir les erreurs du noyau via dmesg" \
"ou juste la partie journaux avec $GREEN./getInfo -j$BLUE ou$GREEN getInfo -j$BLUE (script installé)"
text+="les commandes \`dmesg\` ont échoué, relancer avec les droits root \n\n"
echo -e "$text" >> "$fileOutput"
return 0
fi
dmesg_emerg=$(sed -n 1,"$nb_lignes"p $file-emerg)
dmesg_alert=$(sed -n 1,"$nb_lignes"p $file-alert)
dmesg_crit=$(sed -n 1,"$nb_lignes"p $file-crit)
dmesg_err=$(sed -n 1,"$nb_lignes"p $file-err)
dmesg_warn=$(sed -n 1,"$nb_lignes"p $file-warn)
[ "$dmesg_emerg" ] || dmesg_emerg=" <vide>"
[ "$dmesg_alert" ] || dmesg_alert=" <vide>"
[ "$dmesg_crit" ] || dmesg_crit=" <vide>"
[ "$dmesg_err" ] || dmesg_err=" <vide>"
[ "$dmesg_warn" ] || dmesg_warn=" <vide>"
rm "$file-"*
###
text="## dmesg kernel (emergency, alerte, erreur, warning ou critique) \n\n"
f_display "dmesg_emerg" "cmd" "dmesg -l emerg" "(emergency, $nb_lignes premières lignes)"
f_display "dmesg_alert" "cmd" "dmesg -l alert" "(alerte, $nb_lignes premières lignes)"
f_display "dmesg_crit" "cmd" "dmesg -l crit" "(critique, $nb_lignes premières lignes)"
f_display "dmesg_err" "cmd" "dmesg -l err" "(erreur, $nb_lignes premières lignes)"
f_display "dmesg_warn" "cmd" "dmesg -l warn" "(warning, $nb_lignes premières lignes)"
text+="**les $nb_lignes premières lignes commencent à la date la plus ancienne encore dans les logs kernel** \n\n"
printf "$text\n" >> "$fileOutput"
unset text
}
fi_graph(){ # 29/10/2017
local slots cards cmd alert_hybrid alert_3D providers preferred current openGl resolutions modules ig text
# cardsManuel="$(lspci -nnk | grep -EiA 3 'vga|display|3d')" # -nn: textual and numeric ID's, k kernel
# cardsManuel="$(lspci -nnv | grep -iEA11 'vga|display|3d)" # v=verbose
# cardsManuel="lspci -nnv -s $( lspci | grep -Ei 'vga|display|3d' | cut -d" " -f1 )" si plusieurs devices possibles??
#debug: slots="$(cat tests/lspci | grep -Ei 'vga|display|3d' | cut -d" " -f1)"
# lspci
slots="$(lspci | grep -Ei 'vga|display|3d' | cut -d" " -f1)"
if [ $(f__cmd_exist optirun) ]; then
for ig in $slots; do
cards+="$(optirun lspci -nnv -s $ig)"$'\n'
done
cmd="optirun lspci -nnv | grep -iEA11 'vga|display|3d'"
else
for ig in $slots; do
cards+="$(DRI_PRIME=1 lspci -nnv -s $ig)"$'\n'
done
cmd="DRI_PRIME=1 lspci -nnv | grep -iEA11 'vga|display|3d'"
fi
cards=${cards::-1} # suppression dernier $'\n'
if [ $(grep -c 'Unknown header type 7f' <<< "$cards") -gt 0 ]; then
alert_hybrid="Une carte graphique est désactivée actuellement, lspci n'est pas complet. \n"
alert_hybrid+="Voir DRI_PRIME, vga-switcheroo, Bumbledee...? \n"
fi
# openGl
if [ $(f__cmd_exist glxinfo) ]; then
openGl=$( glxinfo | grep -i 'direct rendering' )$'\n'
alert_3D=$(grep -i 'no' <<< $openGl )
openGl+="$( glxinfo | grep 'OpenGL vendor' )"$'\n'
openGl+="$( glxinfo | grep 'OpenGL renderer' )"$'\n'
openGl+="$( glxinfo | grep 'OpenGL version' )"$'\n'
openGl+="$( glxinfo | grep 'OpenGL shading language version' )"$'\n'
openGl+="$( glxinfo | grep 'OpenGL extensions' )"$'\n'
openGl="$( sed 's/ string//g' <<< "$openGl" )"
fi
[ "$alert_3D" ] && alert_3D="l'accélération 3D n'est pas active \n\n"
# xrandr: résolutions & providers & preferred & current
[ $(f__cmd_exist xrandr) ] && resolutions="$( xrandr --query | grep -A11 'Screen [0-9]' )"
[ $(f__cmd_exist xrandr) ] && providers="$( xrandr --listproviders )"
[ $(f__cmd_exist xrandr) ] && current="$( xrandr --verbose | grep -A2 '*current' )"
[ $(f__cmd_exist xrandr) ] && preferred="$( xrandr --verbose | grep -A2 '+preferred' )"
# modules
modules="$(lsmod | grep -Ei 'amdgpu|ati|i915|nouveau|nvidia|radeon|video|gma')"
# fonctions externes
[ "$fget_gpu" ] || figet_gpu
[ "$fget_resolution" ] || figet_screen
###
text="## graphisme \n\n"
# cartes graphiques
text+="$(sed -E 's/(.*)/> \* \*\*\1\*\*/' <<< $fget_gpu) \n\n"
# nb écran & résolution(s) active(s)
text+="nombre d'écrans: **$fget_nb_screen** \n"
text+="résolution: **$fget_resolution** \n\n"
# lspci
f_display "cards" "cmd" "$cmd"
[ "$alert_hybrid" ] && text+="$alert_hybrid \n\n"
# openGl
[ "$openGl" ] && f_display "openGl" "cmd" "glxinfo | grep 'OpenGL"
[ "$alert_3D" ] && text+="**$alert_3D** \n"
# liste providers, preferred, current,
[ "$current" ] && f_display "current" "cmd" "xrandr --verbose | grep -A2 '*current'"
[ "$preferred" ] && f_display "preferred" "cmd" "xrandr --verbose | grep -A2 '+preferred'"
[ "$providers" ] && f_display "providers" "cmd" "xrandr --listproviders"
# résolutions possibles, pas d'affichage si mode (ssh) ou xrandr pas accessible
if [ "$resolutions" ]; then
f_display "resolutions" "cmd" "xrandr --query | grep -A11 'Screen [0-9]'" "(10 premières résolutions possibles)"
fi
# modules vidéo
text+="### modules video \n\n"
if [ "$modules" ]; then
f_display "modules" "var" "modules recherchés: amdgpu, ati, i915, nouveau, nvidia, radeon, video, gma"
else
text+="Modules non reconnus. Il serait bien de communiquer le retour de \`lsmod\` pour mettre "
text+="à jour le script. Merci de contacter $projet: \n$contact "
fi
printf "$text\n" >> "$fileOutput"
unset text
}
fi_hw(){ # 25/10/2017
figet_hw
###
text="## hardware monitor ACPI \n\n"
if [ "$fget_hw" ]; then
f_display "fget_hw" "sans"
else
text+="**pas d'informations détectées** \n\n"
fi
printf "$text\n" >> "$fileOutput"
unset text
}
fi_journal(){ # 25/10/2017
local jctl_boot jctl_alert_k jctl_crit_k jctl_err_k jctl_warn_k jctl_warn_nok file text nb_lignes=25
[ "$(f__cmd_exist journalctl)" ] || fi_dmesg # pas systemd, appel dmesg
file="/tmp/$$-$RANDOM-journalctl"
[ "$EUID" -eq 0 ] || echo
f__sudo "LC_ALL=C journalctl --no-hostname --boot 0 | sed -E -n '/^-- Logs begin.*$/p' > $file-boot ; \
LC_ALL=C journalctl --no-hostname --boot 0 -k -p 1 > $file-alert ; \
LC_ALL=C journalctl --no-hostname --boot 0 -k -p 2..2 > $file-crit ; \
LC_ALL=C journalctl --no-hostname --boot 0 -p 3..3 > $file-err ; \
LC_ALL=C journalctl --no-hostname --boot 0 -p 4..4 > $file-warn ; \
chown $user_: $file-*"
if [ "$?" != "0" ]; then
f__info "\n les commandes$GREEN journalctl$RED ont échoué $BLUE(droits root requis, échec authentification?)" \
"vous pouvez relancer le script complet$RED en root$BLUE pour voir les erreurs des journaux" \
"ou juste la partie journaux avec $GREEN./getInfo -j$BLUE ou$GREEN getInfo -j$BLUE (script installé)"
text+="les commandes \`journalctl\` ont échoué, relancer avec les droits root \n\n"
echo -e "$text" >> "$fileOutput"
return 0
fi
jctl_boot=$(cat $file-boot)
jctl_boot=$(gawk -F '--|,' '{ sub(/^ /,"",$2);print $2}' <<< $(cat $file-boot))
jctl_alert_k=$(sed '/kernel:/!d' $file-alert | sed -n 1,"$nb_lignes"p) # emergency & alert
jctl_crit_k=$(sed '/kernel:/!d' $file-crit | sed -n 1,"$nb_lignes"p)
jctl_err_k=$(sed '/kernel:/!d' $file-err | sed -n 1,"$nb_lignes"p)
jctl_warn_k=$(sed '/kernel:/!d' $file-warn | sed -n 1,"$nb_lignes"p)
[ "$jctl_alert_k" ] || jctl_alert_k=" <vide>"
[ "$jctl_crit_k" ] || jctl_crit_k=" <vide>"
[ "$jctl_err_k" ] || jctl_err_k=" <vide>"
[ "$jctl_warn_k" ] || jctl_warn_k=" <vide>"
jctl_alert_nok=$(sed '/-- Logs begin/d;/kernel:/d; s/-- No entries --/ <vide>/' $file-alert | sed -n 1,"$nb_lignes"p)
jctl_crit_nok=$(sed '/-- Logs begin/d;/kernel:/d; s/-- No entries --/ <vide>/' $file-crit | sed -n 1,"$nb_lignes"p)
jctl_err_nok=$(sed '/-- Logs begin/d;/kernel:/d; s/-- No entries --/ <vide>/' $file-err | sed -n 1,"$nb_lignes"p)
jctl_warn_nok=$(sed '/-- Logs begin/d;/kernel:/d; s/-- No entries --/ <vide>/' $file-warn | sed -n 1,"$nb_lignes"p)
rm "$file-"*
###
# kernel
text="## journalctl kernel (emergency, alert, erreur, warning ou critique) \n\n"
text+="**$jctl_boot** \n\n"
f_display "jctl_alert_k" "cmd" "journalctl --no-hostname --boot 0 -k -p 1" \
"(kernel emergency 0 & alerte 1, $nb_lignes premières lignes)"
f_display "jctl_crit_k" "cmd" "journalctl --no-hostname --boot 0 -k -p 2..2" \
"(kernel critique, $nb_lignes premières lignes)"
f_display "jctl_err_k" "cmd" "journalctl --no-hostname --boot 0 -k -p 3..3" \
"(kernel erreur, $nb_lignes premières lignes)"
f_display "jctl_warn_k" "cmd" "journalctl --no-hostname --boot 0 -k -p 4..4" \
"(kernel warning, $nb_lignes premières lignes)"
# non kernel
text+="## journalctl hors kernel (emergency, alert, erreur, warning ou critique) \n\n"
text+="**$jctl_boot** \n\n"
f_display "jctl_alert_nok" "cmd" "journalctl --no-hostname --boot 0 -p 1 | grep -v kernel" \
"(hors kernel, emergency 0 & alerte 1, $nb_lignes premières lignes)"
f_display "jctl_crit_nok" "cmd" "journalctl --no-hostname --boot 0 -p 2..2 | grep -v kernel" \
"(hors kernel, critique, $nb_lignes premières lignes)"
f_display "jctl_err_nok" "cmd" "journalctl --no-hostname --boot 0 -p 3..3 | grep -v kernel" \
"(hors kernel, erreur, $nb_lignes premières lignes)"
f_display "jctl_warn_nok" "cmd" "journalctl --no-hostname --boot 0 -p 4..4 | grep -v kernel" \
"(hors kernel, warning, $nb_lignes premières lignes)"
text+="**les $nb_lignes premières lignes commencent à la date du dernier boot** \n\n"
printf "$text\n" >> "$fileOutput"
unset text
}
fi_locale(){ # 27/10/2017
local locale localectl timezone timedatectl
local xKeyboardMap keyboard alert_Rtc alert_Rtc_info alert_NTP alert_Ntp_info text
# locale
locale="$(grep -Esv '#|^$' /etc/default/locale* /etc/locale.conf)"
[ "$(f__cmd_exist localectl)" ] && localectl=$(localectl --no-pager status)
# timezone
timezone="$(grep -Hs . /etc/timezone)"
if [ "$(f__cmd_exist timedatectl)" ]; then
timedatectl="$(timedatectl status --no-pager)"
grep -q 'RTC in local TZ: yes' <<< "$timedatectl" && alert_Rtc="Attention RTC in local TZ"
alert_Rtc_info="**Lhorloge système doit être en UTC** pour que les applications de date et heure fonctionnent
correctement avec le fuseau horaire configuré sur le système. Les modifications dheure
dété/hiver peuvent être incohérentes quand lhorloge matérielle est en heure locale. \n"
grep -q 'Network time on: no' <<< "$timedatectl" && alert_NTP="Attention NTP"
alert_Ntp_info="Le système ne synchronise pas l'heure sur un serveur NTP. Si ce n'est pas voulu:
activer le service: timedatectl set-ntp true
et/ou installer le démon Ntp: apt install ntp \n"
fi
# keyboard layout
keyboard="$(grep -EHsv '#|^$' /etc/default/keyboard*)"
[ "$(f__cmd_exist setxkbmap)" ] && xKeyboardMap="$(setxkbmap -query)"
###
text="## localisation \n\n"
# locale
[ "$locale" ] && f_display "locale" "cmd" "grep -Esv '#|^$' /etc/default/locale* /etc/locale.conf"
[ "$localectl" ] && f_display "localectl" "cmd" "localectl --no-pager status"
# timezone
[ "$timezone" ] && f_display "timezone" "cmd" "grep -Hs . /etc/timezone*"
[ "$timezone" ] || f_display_file "/etc/timezone*"
[ "$timedatectl" ] && f_display "timedatectl" "cmd" "timedatectl status --no-pager"
[ "$alert_Rtc" ] && text+="$alert_Rtc_info \n"
[ "$alert_Ntp" ] && text+="$alert_Ntp_info \n"
# keyboard layout
[ "$keyboard" ] && f_display "keyboard" "cmd" "grep -EHv '#|^$' /etc/default/keyboard*"
[ "$keyboard" ] || f_display_file "/etc/default/keyboard"
[ "$xKeyboardMap" ] && f_display "xKeyboardMap" "cmd" "setxkbmap -query"
printf "$text\n" >> "$fileOutput"
unset text
}
fi_log_xorg(){ # 25/10/2017
[ "$ENV_SSH" ] && return 0
local logXorg xfile extract text nb_lignes=50
# Markers: (--) probed, (**) from config file, (==) default setting, (++) from command line, (!!) notice,
# (II) informational, (WW) warning, (EE) error, (NI) not implemented, (??) unknown (WW) warning, (EE) erreur
# voir options appliquées par config file: cat /var/log/Xorg.0.log | grep -E '\(\*\*\)'
# voir options par défaut: cat /var/log/Xorg.0.log | grep -E '\(==\)'
for xfile in /var/log/Xorg.0.log /home/$user_/.local/share/xorg/Xorg.0.log ; do
if [ -e "$xfile" ]; then
extract="$(grep -Es '\(WW\)|\(EE\)|\(\?\?\)' $xfile | sed '/(WW) warning, (EE) error,/d')"
extract="$(sed -n 1,"$nb_lignes"p <<< $extract)"
if [ "$extract" ]; then
logXorg+="$xfile (WW) **warning**, (EE) **erreur**, (??) inconnu, $nb_lignes premières lignes \n\n"
logXorg+="$(grep -E '\(EE\)' <<< $extract) \n"
logXorg+="$(grep -E '\(WW\)' <<< $extract) \n\n"
else
logXorg+="$xfile : <vide> \n\n"
fi
else
logXorg+="$xfile : inexistant\n\n"
fi
done
logXorg="${logXorg::-2}"
###
text="## journaux Xorg \n\n"
f_display "logXorg" "cmd" \
"grep -Es '\(WW\)|\(EE\)|\(\?\?\)' /var/log/Xorg.?.log /home/<user>/.local/share/xorg/Xorg.?.log" \
"(Xorg.log)"
printf "$text\n" >> "$fileOutput"
unset text
}
fi_mem(){ # 25/10/2017
local swappiness text var_temp
swappiness="$(cat /proc/sys/vm/swappiness 2>/dev/null)"
figet_mem "mem" #options possibles mem swap total notitle nocoltitle
var_temp="$fget_mem \n\n"
figet_mem "swap" "notitle"
var_temp+="$fget_mem \n\n"
var_temp+="swappiness: $swappiness"
###
text="## mémoire \n\n"
f_display "var_temp" "sans"
printf "$text\n" >> "$fileOutput"
unset text
}
fi_nm(){ # 29/10/2017
[ "$(f__cmd_exist nmcli)" ] || return 0
local nm_etat nm_conf nm_wifis nm_connected text
nm_etat=$(grep -Esv '#|^$' /var/lib/NetworkManager/NetworkManager.state)
nm_conf=$(grep -Esv '#|^$' /etc/NetworkManager/NetworkManager.conf)
nm_wifis=$(nmcli -f SSID,BSSID,MODE,CHAN,FREQ,RATE,SIGNAL,BARS,SECURITY device wifi list | head -n15)
nm_connected=$(LC_ALL=C nmcli -f SSID,ACTIVE,IN-USE device wifi list | gawk '/yes[[:space:]]+\*/ {print $1}')
###
text="## NetworkManager \n\n"
[ "$nm_etat" ] && f_display "nm_etat" "cmd" "grep -Ev '#|^$' /var/lib/NetworkManager/NetworkManager.state"
[ "$nm_etat" ] || f_display_file "/var/lib/NetworkManager/NetworkManager.state"
[ "$nm_conf" ] && f_display "nm_conf" "cmd" "grep -Ev '#|^$' /etc/NetworkManager/NetworkManager.conf"
[ "$nm_conf" ] || f_display_file "/etc/NetworkManager/NetworkManager.conf"
if [ "$nm_wifis" ]; then
text+="## wifis à proximité \n\n"
f_display "nm_wifis" "cmd" "nmcli -f SSID,BSSID,MODE,CHAN,FREQ,RATE,SIGNAL,BARS,SECURITY device wifi list | head -n15"
fi
printf "$text\n" >> "$fileOutput"
unset text
}
fi_vrms(){ # 29/09/2017
local vrms text tempo tempo1 tempo2 pluriel
[ "$(f__cmd_exist vrms)" ] && vrms="$(vrms)"
###
# tempo1=$(grep -o '.*non-free packages' <<< "$vrms" | xargs)
# tempo2=$(grep -o '.*contrib packages' <<< "$vrms" | xargs)
# tempo=$(( ${tempo1:0:1} + ${tempo2:0:1} ))
# [[ "$tempo1" && "$tempo" -gt 1 ]] && pluriel="s" || unset pluriel
if [ "vrms" ]; then
text="## paquets$pluriel non-libres$pluriel \n\n"
f_display "vrms" "cmd" "vrms"
else
text+="* les paquets non-free ou contrib ne peuvent être détectés sans l'installation de vrms \n"
fi
printf "$text\n" >> "$fileOutput"
unset text
}
fi_reseau(){ # 27/10/2017
local slots cards ip_a iwconfig interfaces route resolv canal_wifi ifx alert_wlx text pluriel
# cardsManuel="$(lspci -nnk | grep -EiA 5 'network|ethernet')"
# cardsManuel="$(lspci -nnv | grep -EiA 15 'network|ethernet')"
# cardsManuel="lspci -nnv -s $( lspci | grep -Ei 'network|ethernet' | cut -d" " -f1 )" si devices plusieurs slots???
#lspci
slots="$(lspci | grep -Ei 'network|ethernet' | cut -d" " -f1)"
for ifx in $slots; do
cards+=$(lspci -s $ifx -nnv)$'\n'
done
cards=${cards::-1} # suppression dernier $'\n'
# ip a & route
ip_a="$(ip a | sed '/link\/ether/d; /valid_lft/d')" # filtre sur adr MAC & bail
# ip_a="$(sed '/inet6.*scope global/d; /inet6.*scope link/d' <<< $ip_a)" # filtre sur inet6 scope global & scope link (fe80::)
ip_a="$(sed '/inet6.*/d' <<< $ip_a)" # filtre sur inet6)
route="$(ip route show)"
# interfaces & resolv
interfaces="$(grep -EHrsv '#|^$' /etc/network/interfaces*)"
interfaces="$(sed -E 's/wpa-psk [[:graph:]]+/wpa-psk <WPA key removed>/; s/:/: /' <<< $interfaces )"
resolv="$(grep -Esv '#|^$' /etc/resolv.conf)"
# iwconfig
if [ $(f__cmd_exist iwconfig) ]; then #paquet wireless-tools requis
iwconfig="$(iwconfig 2>&1 | grep -v 'no wireless extensions' | grep -v '^$')"
fi
# iwlist
if [ $(f__cmd_exist iwlist) ]; then # canal wifi utilisé; /sbin, paquet wireless-tools requis
canal_wifi="$(iwlist chan 2>&1 | grep 'Current Frequency' | grep -Eio 'channel [0-9]+')"
fi
# network manager
netmgrpaths=("/usr/sbin/NetworkManager" "/usr/sbin/wicd" "/usr/sbin/connmand")
netmgrnames=("NetworkManager" "Wicd" "ConnMan")
for ifx in "${!netmgrpaths[@]}"; do
[ -f "${netmgrpaths[$ifx]}" ] && netmgrinst+=${netmgrnames[$ifx]}
if [ "$(ps -ef | grep -c ${netmgrpaths[$ifx]})" -ge 2 ]; then
netmgrrun+="$(ps -ef | grep -o "${netmgrpaths[$ifx]}.*$" | head -n 1)"
fi
done
figet_ip
if grep -q 'wlx' <<< "$fg_ifn"; then
alert_wlx="**Attention:** une interface wifi est en erreur: $(grep -o 'wlx' <<< $fg_ifn) \n"
alert_wlx+="l'interface n'est pas reconnue et est donc mal nommée \n"
alert_wlx+="au pire, changer le renommage: "
alert_wlx+="https://kyodev.frama.io/kyopages/trucs/interfaces-nommage-classique/ \n\n"
fi
figet_mod_net
###
text="## réseau \n\n"
#lspci
f_display "cards" "cmd" "lspci -nnv | grep -EiA 15 'network|ethernet"
# ip locales avec type
f_display "fg_ip_tp" "var" "IP locale(s):"
[ "$alert_wlx" ] && text+="alert_wlx \n\n"
text+="* les adresses Mac peut être affichées avec "'`./getInfo --mac` ou `getInfo --mac`'" (script installé) \n"
text+="* l'IP publique peut être connue avec: "'`./getInfo --ip` ou `getInfo --ip` (script installé) \n\n'
# gateways
f_display "fg_gws" "var" "Passerelle(s):"
# interface prioritaire
[ $(wc -w <<< $fg_ifn) -gt 1 ] && f_display "fg_ifn_prior" "var" "interface prioritaire"
# ip a & route & interface & resolv
f_display "ip_a" "cmd" "ip address" "(sans ipV6 et sans adresses MAC)"
f_display "route" "cmd" "ip route show"
[ "$interfaces" ] && f_display "interfaces" "cmd" "grep -EHrsv '#|^$' /etc/network/interfaces*"
[ "$interfaces" ] || f_display_file "/etc/network/interfaces*"
[ "$resolv" ] && f_display "resolv" "cmd" "cat /etc/resolv.conf" "(serveurs de noms DNS utilisés)"
[ "$resolv" ] || f_display_file "/etc/resolv.conf"
# iwconfig & iwlist
[ "$iwconfig" ] && f_display "iwconfig" "cmd" "iwconfig" "état carte wifi"
if [ "$canal_wifi" ]; then
f_display "canal_wifi" "cmd" "iwlist chan | grep 'Current Frequency' | grep -Eio 'channel [0-9]+'" \
"canal wifi utilisé"
text+="* la configuration ssid utilisée peut être connue (si NetworkManager utilisé) avec \n"
text+="\`./getInfo --ssid\` ou \`getInfo --ssid\` (script installé) \n\n"
fi
# network manager
if [ "$netmgrinst" ]; then
text+="### gestionnaire de réseau \n\n"
if [ "$netmgrinst" ]; then
[ $(wc -w <<< $netmgrinst) -gt 1 ] && pluriel="s" || unset pluriel
text+="installé$pluriel: **$netmgrinst** \n"
else
[ $(wc -w <<< $netmgrnames[@]) -gt 1 ] && pluriel="s" || unset pluriel
text+="non trouvé$pluriel parmi: ${netmgrnames[@]} \n"
fi
text+="en fonctionnement: "
[ "$netmgrrun" ] && text+="**$netmgrrun** \n\n" || text+="aucun \n\n"
fi
# modules réseau
text+="### modules réseau \n\n"
[ "$fget_mod_net" ] && f_display "fget_mod_net" "var" "liste non garantie complète"
[ "$fget_mod_net" ] || text+="**Modules chargés non reconnus**"
printf "$text\n" >> "$fileOutput"
unset text
}
fi_sources(){ # 25/10/2017
[ "$(f__cmd_exist dpkg)" ] || return 0
local sources dateMaj nb_packages apt text pluriel
local alert_autoremove alert_nbAutoremove alert_paquetToRemove alert_httpredir alert_httpredir_text
local alert_upgradable alert_upgradable_text alert_nbUpgradable
local alert_paquetBiz alert_paquetBiz_text0 alert_paquetBiz_text
printf "."
sources="$(grep -Ersv '^#|^$' /etc/apt/sources.list /etc/apt/sources.list.d/*.list)"
sources="$(sed 's/:deb/: deb/; s/ / /g' <<< $sources)"
dateMaj="$(date -r /var/cache/apt/pkgcache.bin '+%d/%m/%Y %H:%M %z')" # /var/lib/dpkg/
nb_packages="$(dpkg -l | grep -c '^ii')"
printf "."
apt="$(LC_ALL=C apt-get autoremove --simulate)"
alert_nbAutoremove="$(grep -c 'Remv' <<< $apt)"
if [ "$alert_nbAutoremove" -ne 0 ]; then
[ "$alert_nbAutoremove" -gt 1 ] && pluriel="s" || unset pluriel
alert_autoremove="$alert_nbAutoremove paquet$pluriel installé$pluriel inutile$pluriel, "
alert_autoremove+="vous pouvez utiliser: \`apt autoremove\`"
alert_paquetToRemove="$(sed -En 's/Remv (.*)\[[0-9.-]*\]/\1/p' <<< $apt | tr '\n' ' ')"
fi
printf "."
alert_httpredir="$(grep 'httpredir' <<< $sources)"
if [ "$alert_httpredir" ]; then
alert_httpredir_text="url **httpredir**, ces urls sont obsolètes, préférer "
alert_httpredir_text+="http://deb.debian.org/debian/ ou un miroir local"
fi
alert_upgradable="$(LC_ALL=C apt list --upgradable 2>/dev/null | sed '1d')"
if [ "$alert_upgradable" ]; then
alert_nbUpgradable="$(grep -c '.' <<< "$alert_upgradable")"
[ "$alert_nbUpgradable" -gt 1 ] && pluriel="s" || unset pluriel
alert_upgradable_text="$alert_nbUpgradable paquet$pluriel à mettre à jour, "
alert_upgradable_text+='`apt list --upgradable`:'
fi
printf "."
alert_paquetBiz="$(dpkg -l | gawk 'FNR>5 && ! /^i/ {print $1, $2, $3}')"
if [ "$alert_paquetBiz" ]; then
[ "$(grep -c '.' <<< "$alert_paquetBiz")" -gt 1 ] && pluriel="s" || unset pluriel
alert_paquetBiz_text0="$(grep -c '.' <<< \
"$alert_paquetBiz") paquet$pluriel dans un état non installé"
[[ ${alert_paquetBiz,,} =~ ^. ]] && alert_paquetBiz_text="* **État souhaité** "$'\n'
[[ ${alert_paquetBiz,,} =~ ^h ]] && alert_paquetBiz_text+=" * **h**old (à garder) "$'\n'
[[ ${alert_paquetBiz,,} =~ ^i ]] && alert_paquetBiz_text+=" * **i**nstall (à installer) "$'\n'
[[ ${alert_paquetBiz,,} =~ ^p ]] && alert_paquetBiz_text+=" * **p**urge (à purger) "$'\n'
[[ ${alert_paquetBiz,,} =~ ^r ]] && alert_paquetBiz_text+=" * **r**emove (à supprimer) "$'\n'
[[ ${alert_paquetBiz,,} =~ ^u ]] && alert_paquetBiz_text+=" * **u**nknown (inconnu) "$'\n'
[[ ${alert_paquetBiz,,} =~ ^.. ]] && alert_paquetBiz_text+="* **État du paquet** "$'\n'
[[ ${alert_paquetBiz,,} =~ ^.c ]] && alert_paquetBiz_text+=" * **c**onfig-files (fichiers de configuration seuls) "$'\n'
[[ ${alert_paquetBiz,,} =~ ^.f ]] && alert_paquetBiz_text+=" * hal**F**-configured-configured (semi-configuré) "$'\n'
[[ ${alert_paquetBiz,,} =~ ^.h ]] && alert_paquetBiz_text+=" * **H**alf-installed (semi-installé) "$'\n'
[[ ${alert_paquetBiz,,} =~ ^.i ]] && alert_paquetBiz_text+=" * **i**nstalled (installé) "$'\n'
[[ ${alert_paquetBiz,,} =~ ^.n ]] && alert_paquetBiz_text+=" * **n**ot-installed (non installé) "$'\n'
[[ ${alert_paquetBiz,,} =~ ^.t ]] && alert_paquetBiz_text+=" * **t**riggers-pending (en instance déclencheurs) "$'\n'
[[ ${alert_paquetBiz,,} =~ ^.u ]] && alert_paquetBiz_text+=" * **u**npacked (décompressé seulement) "$'\n'
[[ ${alert_paquetBiz,,} =~ ^.w ]] && alert_paquetBiz_text+=" * triggers-a**w**aiting (attente déclencheurs) "$'\n'
[[ ${alert_paquetBiz,,} =~ ^..r ]] && alert_paquetBiz_text+="* **Drapeaux d'erreur**\n * (réinstallation requise) "$'\n'
alert_paquetBiz_text=${alert_paquetBiz_text::-1} # suppression dernier $'\n'
fi
###
text="## sources liste \n\n"
f_display "sources" "cmd" "grep -Ersv '^#|^$' /etc/apt/sources.list /etc/apt/sources.list.d/*.list"
text+="nombre de paquets installés: **$nb_packages** \n\n"
text+="dernière mise à jour apt: **$dateMaj** \n\n"
[ "$alert_autoremove" ] && f_display "alert_paquetToRemove" "var" "$alert_autoremove"
[ "$alert_httpredir" ] && f_display "alert_httpredir" "var" "$alert_httpredir_text"
[ "$alert_upgradable" ] && f_display "alert_upgradable" "var" "$alert_upgradable_text"
if [ "$alert_paquetBiz" ]; then
f_display "alert_paquetBiz" "var" "$alert_paquetBiz_text0"
text+="$alert_paquetBiz_text"' \n\n'
fi
printf "$text\n" >> "$fileOutput"
unset text
}
fi_ssid(){ # 27/10/2017
[ "$(f__cmd_exist nmcli)" ] || f__error "NetworkManager requis"
local nm_ssid file="/tmp/$$-$RANDOM-fi_ssid" text
# nm_ssid="$(grep -Ev '#|^$' /etc/NetworkManager/system-connections/*)"
[ "$EUID" -eq 0 ] || echo
f__sudo "grep -Ev '#|^$' /etc/NetworkManager/system-connections/* > $file ; \
chown $user_: $file"
if [ "$?" != "0" ]; then
f__info "\n la consultation des connections NetworkManager$RED a échoué$BLUE (droits root requis, échec authentification?)" \
"vous pouvez relancer le script$RED en root:$GREEN./getInfo --ssid$STD ou$GREEN getInfo --ssid$BLUE (script installé)"
text+="la consultation des connections NetworkManager a échoué, relancer avec les droits root \n"
echo -e "$text" >> "$fileOutput"
return 0
fi
nm_ssid="$(< $file)"
rm "$file"
###
f__info "la$RED clé du réseau wifi étant visible$STD, aucun rapport n'a été créé"
text="## configuration(s) ssid networkmanager \n\n"
text+="$GREEN""grep -Ev '#|^$' /etc/NetworkManager/system-connections/*$STD \n\n"
text+="$nm_ssid \n\n"
printf "$text" >> "$fileOutput"
unset text
}
fi_system_analyse(){ # 25/10/2017
[ "$(f__cmd_exist systemd-analyze)" ] || return 0 # pas systemd
local bootTime bootBlame text
bootTime="$(systemd-analyze time)"
bootBlame="$(systemd-analyze blame | head -n 20)"
###
text="## analyse boot \n\n"
text+="$(sed 's/Startup finished in /**durée de boot:** /; s/userspace/espace utilisateur/; s/= \(.*\)$/= **\1**/' <<< $bootTime) \n\n"
f_display "bootBlame" "cmd" "systemd-analyze blame | head -n 20"
printf "$text\n" >> "$fileOutput"
unset text
}
fi_systeme(){ # 25/10/2017
local mbr description uname bootImage initDaemon xorg shells lastboot uptime charge pluriel text
local alim_total alimentation
[ -d /sys/firmware/efi ] && mbr="EFI" || mbr="Legacy (mbr)"
[ -x "/usr/bin/lsb_release" ] && description="$(lsb_release -ds)" #dépend de apt install lsb-release, sur debian, en standard, juste : lsb-base
uname="$(uname -rmo)"
bootImage="$(gawk '/BOOT_IMAGE/ {print $1}' /proc/cmdline)"
bootImage="$(gawk '{print $1}{i=2; while (i <= NF-1) { print " ",$i; i++}}' /proc/cmdline)"
initDaemon="$(ps -p1 | gawk 'FNR==2 {print $4}')" #? ps -ax | gawk '$1==1' ou ps -p1 | gawk '$1==1'
[ "$ENV_SSH" ] && xorg="n/a (ssh)" || xorg="$XDG_SESSION_TYPE"
if [ -z "$xorg" ]; then
[ "$(ps -ef | grep -c 'wayland')" -gt 1 ] && xorg="wayland" || xorg="indéterminé"
fi
shells="$(grep -Ev '^[[:blank:]]*#|^$' /etc/shells | sed 's/\/bin\///' | tr '\n' ' ')"
if [ $(grep -c 'AC' <<< $(ls /sys/class/power_supply/ 2>/dev/null)) -gt 0 ]; then
alim_total=$(grep -cs . <<< $(ls /sys/class/power_supply/AC*/online))
# alim_on=$(grep -cs '1' /sys/class/power_supply/AC*/online)
# alim_off=$(grep -cs '0' /sys/class/power_supply/AC*/online)
alimentation=$( awk -v "alim_total=$alim_total" '
{ alim_on=sprintf("%d", $1); if (alim_on>1) pllo="s" }
END { if ( alim_total > 1 ) pllt="s"; printf alim_total " alimentation" pllt
if ( alim_total != alim_on ) print ", " alim_on " branchée" pllo; else print "" }
' /sys/class/power_supply/AC*/online )
fi
# lastboot="$(last -n 1 --time-format iso reboot | gawk 'FNR==1 {sub(/T/," ",$5);print $5}')" # remis à jours en début de mois ?!!
lastboot="$(date -r /var/run/utmp '+%d/%m/%Y %H:%M %z')"
uptime="$(uptime -p | sed 's/up/depuis/; s/week/semaine/; s/weeks/semaines/; s/days/jours/; s/day/jour/; s/hour[s]*/h/; s/minute[s]*/mn/')"
charge="$(uptime | sed -En 's/.*load average: (.*), (.*), (.*)/\1 \2 \3/; s/,/./gp')"
figet_batt
figet_cpu
figet_de
figet_dmi
figet_disk
figet_distro
figet_gpu
figet_screen
figet_shell
figet_wm
###
f__architecture || f__info "Architecture non supportée" "vous pouvez contacter $projet, $contact " \
"pour aider à parfaire le script"
text="## système \n\n"
text+="> **$fget_dmi** \n\n"
text+="* CPU \n"
text+=" * **$(sed -n '1p' <<< $fget_cpu)** \n"
text+="* GPU \n"
text+="$(sed -E 's/(.*)/ \* \*\*\1\*\*/' <<<$fget_gpu) \n"
text+="* boot **$mbr** \n"
text+="* distribution **$fget_distro** \n\n"
text+='``` \n'
text+="architecture: $architecture \n"
[ "$description" ] && text+="description: $description \n"
text+="uname: $uname \n"
text+="$bootImage \n"
text+="démon d'initialisation: $initDaemon \n"
text+="serveur d'affichage: $xorg \n"
text+="nombre d'écrans: $fget_nb_screen \n"
text+="résolution: $fget_resolution \n"
text+="desktop (DE): $fget_de \n"
text+="window manager: $fget_wm \n"
text+="shell actif: $fget_shell \n"
text+="shells installés: $shells \n"
text+="$fget_disk_part_fix_tot \n"
[ "$alimentation" ] && text+="$alimentation \n"
if [ "$fg_batt" ]; then
[ "$fg_nb_batt" -gt "1" ] && pluriel="s" || unset pluriel
text+="$fg_nb_batt batterie$pluriel présente$pluriel: \n"
text+="$(sed -En 's/^BAT(.*)$/ BAT\1/p' <<< $fg_batt) \n"
fi
text+="dernier boot: $lastboot, uptime: $uptime \n"
text+="charge système depuis les 1, 5 et 15 dernières minutes: $charge \n"
text+='``` \n\n'
printf "$text\n" >> "$fileOutput"
unset text
}
fi_usb(){ # 25/10/2017
local lsusb lsusb_t text
lsusb="$(lsusb)"
lsusb_t="$(lsusb -t)"
###
text="## USB \n\n"
f_display "lsusb" "cmd" "lsusb"
f_display "lsusb_t" "cmd" "lsusb -t"
printf "$text\n" >> "$fileOutput"
unset text
}
# informations batterie(s), assigne $fg_nb_batt $fg_batt
figet_batt(){ #v2 29/10/2017
local batt_detail batt_nb batt_unit batt_capa_design batt_capa_full batt_capa_now batt_conso
local batt_volt_min batt_volt_now batt_status batt_cycle batt_sn alert_batt_alarm
local batt_sante batt_restant tempo batRep ibat uevent
if [ ! -d /sys/class/power_supply ]; then # anciennes interfaces ou inconnu
[ -d /proc/acpi/battery ] && batt_detail="ancienne interface ACPI non gérée (obsolète)"
[ -f /proc/apm ] && batt_detail="anciennes batteries APM non gérées (obolète)"
[ "$batt_detail" ] || batt_detail="répertoire power_supply inaccessible"
batt_nb="-1"
return 1
fi
[ "$(grep -c 'BAT' <<< $(ls /sys/class/power_supply/ 2>/dev/null))" -gt 0 ] || return 0
batt_nb="$(grep -i 'Battery' /sys/class/power_supply/*/type | grep -c .)"
[ "$batt_nb" ] || return
batRep="/sys/class/power_supply"
unset batt_detail
for ibat in $(ls $batRep); do
grep -qi 'Battery' "$batRep/$ibat/type" || continue # plus loin si non batterie
[ -e "$batRep/$ibat/uevent" ] || batt_detail="$ibat: **uevent** incorrect"
[ -e "$batRep/$ibat/uevent" ] || continue
uevent="$(grep -s . $batRep/$ibat/uevent)"
# extractions valeur de calcul selon type
if grep -q 'POWER_SUPPLY_CHARGE_' <<< $uevent ; then
batt_unit="mAh"
batt_capa_design="$(gawk -F '=' '/POWER_SUPPLY_CHARGE_FULL_DESIGN=/ {printf "%d", $2/1000}' <<< $uevent)" # mA
batt_capa_full="$(gawk -F '=' '/POWER_SUPPLY_CHARGE_FULL=/ {printf "%d", $2/1000}' <<< $uevent)" # mA
batt_capa_now="$(gawk -F '=' '/POWER_SUPPLY_CHARGE_NOW=/ {printf "%d", $2/1000}' <<< $uevent)" # mA
batt_conso="$(gawk -F '=' '/POWER_SUPPLY_CURRENT_NOW=/ {printf "%d", $2/1000}' <<< $uevent)" # mA
elif grep -q 'POWER_SUPPLY_ENERGY_' <<< $uevent ; then
batt_unit="Wh"
batt_capa_design="$(gawk -F '=' '/POWER_SUPPLY_ENERGY_FULL_DESIGN=/ {printf "%.2f", $2/1000000}' <<< $uevent)" # W
batt_capa_full="$(gawk -F '=' '/POWER_SUPPLY_ENERGY_FULL=/ {printf "%.2f", $2/1000000}' <<< $uevent)" # W
batt_capa_now="$(gawk -F '=' '/POWER_SUPPLY_ENERGY_NOW=/ {printf "%.2f", $2/1000000}' <<< $uevent)" # W
batt_conso="$(gawk -F '=' '/POWER_SUPPLY_POWER_NOW=/ {printf "%.2f", $2/1000000}' <<< $uevent)" # W
fi
# extractions simples
batt_volt_min="$(gawk -F '=' '/POWER_SUPPLY_VOLTAGE_MIN_DESIGN=/ {printf "%.2f", $2/1000000}' <<< $uevent)" # V
batt_volt_now="$(gawk -F '=' '/POWER_SUPPLY_VOLTAGE_NOW=/ {printf "%.2f", $2/1000000}' <<< $uevent)" # V
batt_status="$(gawk -F '=' '/POWER_SUPPLY_STATUS=/ {print $2}' <<< $uevent)"
batt_cycle="$(gawk -F '=' '/POWER_SUPPLY_CYCLE_COUNT=/ {print $2}' <<< $uevent)"
batt_sn="$(gawk -F '=' '/POWER_SUPPLY_SERIAL_NUMBER=/ {sub(/^ | $|0/,"",$2); print $2}' <<< $uevent)"
alert_batt_alarm="$(cat $batRep/$ibat/alarm 2>/dev/null)"
[ "$alert_batt_alarm" == "0" ] && unset alert_batt_alarm || alert_batt_alarm="$ibat: $alert_batt_alarm"
# calculs
batt_sante="$(gawk '$1 != "na" && $2 != "" && $2 != 0 {printf "%.1f", $1/$2*100}' <<< "$batt_capa_full $batt_capa_design")"
if [[ "$batt_status" == "Full" || "$batt_status" == "Unknown" ]]; then
batt_restant="totalement chargée"
elif [ "$batt_status" == "Discharging" ]; then
batt_restant="en décharge, reste approximativement: "
tempo="$(gawk '$1+$2 != "" && $2!=0 {print $1*0.9/$2}' <<< "$batt_capa_now $batt_conso")"
elif [ "$batt_status" == "Charging" ]; then
batt_restant="en charge, reste approximativement: "
tempo="$(gawk '$1+$2+$3 != "" && $3 != 0 {print ($1-$2)/$3}' <<< "$batt_capa_full $batt_capa_now $batt_conso")"
fi
batt_restant+="$(gawk '$1 != "" {printf "%d h %02d mn \n", $1, $1*60%60}' <<< $tempo) "
# mise en forme pour sortie, séparateur milliers
if [ "$batt_unit" == "mAh" ]; then
batt_capa_design="$(printf "%'d" $batt_capa_design)"
batt_capa_full="$(printf "%'d" $batt_capa_full)"
batt_conso="$(printf "%'d" $batt_conso)"
fi
# sortie
batt_detail+="$ibat: $(cat $batRep/$ibat/manufacturer 2>/dev/null) "
batt_detail+="($(cat $batRep/$ibat/model_name 2>/dev/null)) $(cat $batRep/$ibat/technology 2>/dev/null) "
batt_detail+="$batt_capa_design$batt_unit - $batt_volt_min""V / $batt_volt_now""V (mini/actuel) "
[ "$(xargs <<< $batt_sn)" ] && batt_detail+="n° série: $batt_sn"
[ "$batt_cycle" != "0" ] && batt_detail+="$batt_cycle cycles"$'\n' || batt_detail+=$'\n' #ln 1fin
[ "$batt_capa_full" ] && batt_detail+="pleine charge effective: $batt_capa_full$batt_unit, "
batt_detail+="pleine charge théorique: $batt_capa_design$batt_unit => "
if [[ "$batt_conso" != "0" && "$batt_conso" != "0.00" ]]; then # conso éventuelle
if [ "$batt_unit" == "mAh" ]; then
batt_restant+="(consommation en cours: $(printf "%'d" $batt_conso)$(sed 's/h//' <<< $batt_unit), "
batt_restant+="charge actuelle: $(printf "%'d" $batt_capa_now)$batt_unit)"
else
batt_restant+="(consommation en cours: $(printf "%s" $batt_conso)$(sed 's/h//' <<< $batt_unit), "
batt_restant+="charge actuelle: $(printf "%s" $batt_capa_now)$batt_unit)"
fi
fi
[ "$batt_sante" ] && batt_detail+="$batt_sante% (indicateur)"$'\n' #ln 2fin
[ "$batt_restant" ] && batt_detail+="$batt_restant"$'\n' #ln 3fin
# alertes batterie
[ "$alert_batt_alarm" ] && batt_detail+="**batterie en alarme** $alert_batt_alarm "$'\n' #[ln 4]
if [ "$batt_capa_design" == "$batt_capa_full" ] && [ "$batt_volt_min" == "$batt_volt_now" ]; then
batt_detail+="les pleines charges et les voltages sont incohérents, batterie "
batt_detail+="mal gérée ou batterie HS?"$'\n' #[ln 5]
fi
if [ "$(awk '{printf "%d", $1}' <<< $batt_sante)" -lt 50 ] && [[ "$batt_status" == "Full" || "$batt_status" == "Unknown" ]]; then
batt_detail+="batterie très mal chargée (moins de 50%): mauvais état?"$'\n' #[ln 5]
fi
done
fg_nb_batt="$batt_nb"
fg_batt=${batt_detail::-1} # suppression dernier $'\n'
}
# assigne $fget_cpu (3 lignes description cpu)
figet_cpu(){ #v2 25/10/2017
local cpuinfo speedNom speedMax speedMin speedCpu cpu1 cpu2 cpu3
cpuinfo="$(cat /proc/cpuinfo)"
# speed
speedNom=$(gawk -F ':' '/cpu MHz/ {printf "%.2f", $2/1000;exit}' <<< "$cpuinfo")
speedMax=$(gawk '{printf "%.2f", $1/1000000}' /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq 2>/dev/null)
speedMin=$(gawk '{printf "%.2f", $1/1000000}' /sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq 2>/dev/null)
speedCpu=""
[ "$speedMin" ] && speedCpu+="$speedMin/"
[ "$speedNom" ] && speedCpu+="$speedNom"
[[ "$speedMax" && "$speedMax" != "$speedNom" ]] && speedCpu+="/$speedMax"
[ "$speedCpu" ] && speedCpu=$(printf "%sGHz" $speedCpu)
[ "$speedCpu" ] || speedCpu=$(gawk -F '@' '/model name/ {sub(/^ | $/,"",$2); print $2;exit}' <<< "$cpuinfo")
# motifs?: Processor Dual-Core Quad-Core Six-Core Eight-Core Core 'with Radeon * Graphics'
cpu1=$(
gawk -v "speedCpu=$speedCpu" -F ':|@' '
/^model name/ { gsub(/^ | *$|\(R\)|\(TM\)|\(r\)|\(tm\)|CPU/,"",$2); gsub(/ /," ",$2); cpu=$2 }
/^physical id/ { if ($2+1 != nbCpu) nbCpu=$2+1 }
/cpu cores/ { procCore=sprintf("%d",$2); if (procCore>1) pllc="s" }
/siblings/ { procThread=sprintf("%d",$2); if (procThread>1) pllt="s" }
/microcode/ { sub(/^ /,"",$2); microCode=$2 }
END { print nbCpu" x "cpu " (" procCore "core" pllc ", " procThread "thread" pllt ") {" speedCpu "} microcode:" microCode }
' <<< "$cpuinfo "
)
cpu2=$(
gawk -F ':' '
/^vendor_id/{gsub(/ /,"",$2);vendor=$2}; /^cpu family/{family=$2};
/^model[^ ]/{model=$2}; /^stepping/{rev=$2}
END {print "{fréq. mini/nominale/maxi} " vendor" famille" family", modèle"model", révision" rev}
' <<< "$cpuinfo"
)
cpu3=$(
gawk -F ':' '
/address sizes/ { gsub(/ bits/,"b",$2); sub(/physical/,"physique",$2);
sub(/virtual/,"virtuel",$2); sub(/^ | $/,"",$2); add=$2 }
/cache size/ {gsub(/ /,"",$2); gsub(/B/,"o",$2); gsub(/K/,"k",$2); cache=$2}
/bogomips/ { bogomips=sprintf("%d",$2) }
END { print add ", bogomips: " bogomips ", cache: " cache }
' <<< "$cpuinfo"
)
fget_cpu=$(echo -e "$cpu1\n$cpu2\n$cpu3")
}
figet_de(){ # thanks neofetch, assigne $fget_de #22/10/2017
if [ "$ENV_SSH" ]; then
fget_de="n/a (ssh)"
return 0
fi
# local de="${XDG_CURRENT_DESKTOP/i3}" #supprime i3??...
local de="$XDG_CURRENT_DESKTOP"
de="${de/'X-'}"
de="${de/Budgie:GNOME/Budgie}"
# Fallback to using xprop.
if [[ -n "$DISPLAY" && -z "$de" ]]; then
de="$(xprop -root | gawk '/KDE_SESSION_VERSION|^_MUFFIN|xfce4|xfce5|TDE_FULL_SESSION/')" #ajout TDE_FULL_SESSION, oubli?à tester
fi
# Format strings
case "$de" in
"KDE_SESSION_VERSION"* )
de="KDE${de/* = }"
;;
*"TDE_FULL_SESSION"* )
de="Trinity"
;;
*"MUFFIN"* | "Cinnamon" )
de="$(cinnamon --version)"
de="${de:-Cinnamon}"
;;
*"xfce"*)
de="xfce" # suppression xfce4 ou xfce5 (la version ne sort pas dans xprop ou $XDG_
;;
esac
fget_de="${de,,}"
fget_de="${fget_de^}"
}
# $fget_nb_disk : nb disk fixe & amovible, $fget_disk_detail : tableau sommaire
# $fget_disk_fixe : liste devices block fixes, $fget_disk_amov : liste devices block amovibles
# $fget_disk_part_fix_tot : espace des partitions fixes montées
# $fget_disk_ata, $fget_disk_usb, $fget_disk_mmc, $fget_disk_nvme : liste disk ata, usb...
# $fget_disk_part_fixe_m, $fget_disk_part_amov_m : liste partitions montées, fixes ou amovibles
# $fget_disk_part_swap : liste partitions swap
# $fget_disk_part_fixe_nm, $fget_disk_part_amov_nm : liste partitions non montées, fixes ou amovibles
figet_disk(){ #v2 19/10/2017
local size type vendor_model serial_rev list_id idisk lsblk
unset fget_disk_fixe fget_disk_amov
# $fget_disk_detail: tableau sommaire des disques
# disk taille type vendeur modèle n° série révision
# sda 149,1G Fixe ATA Hitachi HTS54321 090620FB02015CD5N3XA C40C
fget_disk_detail="$(printf '%-5s %-8s %-6s %-24s %-26s' "disk" "taille" "type" "vendeur modèle" " n° série révision")"$'\n'
for idisk in $(grep -v 'loop' <<< $(ls /sys/block/)); do
size="$( lsblk -no SIZE -d /dev/$idisk | xargs )" #149,1G
type="$( sed -n '2p' <<< $(lsblk -no HOTPLUG /dev/$idisk) | xargs )" # 0 \n 0 \n ...
[ "$type" == "0" ] && type="Fixe" || type="Amov"
vendor_model="$( lsblk -no VENDOR,MODEL /dev/$idisk | xargs )" # sda ATA Hitachi HTS54321 \n \n \n ...
# if [ -z "$vendor_model" ]; then
if [ "$vendor_model" ]; then
vendor_model=" na na"
#$9=ata-MATSHITADVD-RAM_UJ-850S_HC71_186848 $11=../../sr0
# sur arch: sr0 est reporté en wwn(pas ata), $9,$11: wwn-0x5001480000000000 ../../sr0
# vendor_model="$(ls -l /dev/disk/by-id/ | gawk '{print $9,$11}' | sed '/-part/d' | grep $idisk)"
vendor_model="$(ls -l /dev/disk/by-id/ | gawk ' !/-part/ {print $9,$11}' | grep $idisk)"
#echo "$vendor_model"
vendor_model="$(sed -E 's/.*-(.*)_[0-9]+.*$/\1/;s/_/ /g' <<< $vendor_model)"
fi
serial_rev="$( lsblk -no SERIAL,REV /dev/$idisk | xargs )" # 090620FB02015CD5N3XA C40C \n \n \n ...
fget_disk_detail+="$(printf '%-5s %-8s %-6s %-24s %-26s' "$idisk" "$size" "$type" "$vendor_model" "$serial_rev")"$'\n'
# liste disques fixes ou amovibles
if [ "$(lsblk -no HOTPLUG /dev/$idisk | xargs | cut -d' ' -f2)" == "0" ]; then
fget_disk_fixe+="$idisk " # "sda sdb ..."
else
fget_disk_amov+="$idisk "
fi
done
fget_disk_detail=${fget_disk_detail::-1} # suppression dernier $'\n'
#echo "$fget_disk_detail"
# nb de disques (fixe+amovible), peut servir d'indicateur fonction déja appelée
fget_nb_disk="$(tr ' ' '\n' <<< "$fget_disk_fixe$fget_disk_amov" | grep -c .)"
# séquences partitions fixes, montées (m) et non montées (nm)
lsblk="$(lsblk -no KNAME,MOUNTPOINT $(printf '/dev/%s ' $fget_disk_fixe) 2>/dev/null)"
fget_disk_part_fixe_m="$(echo "$lsblk" | gawk '/\// {print $1}' | tr '\n' ' ')"
fget_disk_part_fixe_nm="$(echo "$lsblk" | gawk '!/\// && /[0-9]+/ && !/\[SWAP\]/{print $1}' | tr '\n' ' ')"
# séquences partitions amovibles, montées (m) et non montées (nm)
lsblk="$(lsblk -no KNAME,MOUNTPOINT $(printf '/dev/%s ' $fget_disk_amov) 2>/dev/null)"
fget_disk_part_amov_m="$(echo "$lsblk" | gawk '/\// {print $1}' | tr '\n' ' ')"
fget_disk_part_amov_nm="$(echo "$lsblk" | gawk '!/\// && /[0-9]+/ && !/\[SWAP\]/{print $1}' | tr '\n' ' ')"
# partitions swap
fget_disk_part_swap="$(echo "$(lsblk -no KNAME,MOUNTPOINT)" | gawk '/\[SWAP\]/ {print $1}' | tr '\n' ' ')"
[ "$fget_disk_fixe" ] || fget_disk_fixe="-"
[ "$fget_disk_amov" ] || fget_disk_amov="-"
[ "$fget_disk_part_fixe_m" ] || fget_disk_part_fixe_m="-"
[ "$fget_disk_part_swap" ] || fget_disk_part_swap="-"
[ "$fget_disk_part_fixe_nm" ] || fget_disk_part_fixe_nm="-"
[ "$fget_disk_part_amov_m" ] || fget_disk_part_amov_m="-"
[ "$fget_disk_part_amov_nm" ] || fget_disk_part_amov_nm="-"
# total espaces partitions fixes montées
fget_disk_part_fix_tot="espace des partitions fixes montées (total, utilisé, dispo): "
fget_disk_part_fix_tot+="$(df -h --total --output=size,used,avail $(printf '/dev/%s ' $fget_disk_part_fixe_m) 2>/dev/null | tail -n-1 | xargs)"
fget_disk_part_fix_tot="$(sed 's/G/Go/g; s/M/Mo/g; s/K/ko/g' <<< $fget_disk_part_fix_tot)"
# liste des disques par type
list_id="$(ls -l /dev/disk/by-id/ | gawk '{print $9,$11}')"
fget_disk_ata="$(sed '/^ata/!d; /part/d' <<< $list_id | awk -F '/' '{print $NF}' | tr '\n' ' ')"
fget_disk_usb="$(sed -n '/part/d; /^usb/p' <<< $list_id | awk -F '/' '{print $NF}' | tr '\n' ' ')"
# fget_disk_mmc="$(sed '/^mmc/!d; /part/d; /\/mmcblk/!d; s/^.*\(mmcblk..*\)$/\1/' <<< $list_id | tr '\n' ' ')"
fget_disk_mmc="$(sed '/^mmc/!d; /part/d' <<< $list_id | awk -F '/' '{print $NF}' | tr '\n' ' ')"
fget_disk_nvme="$(sed '/^nvme/!d; /part/d' <<< $list_id | awk -F '/' '{print $NF}' | tr '\n' ' ')"
[ "$fget_disk_ata" ] || fget_disk_ata="-" && fget_disk_ata="$(tr ' ' '\n' <<< "$fget_disk_ata" | sort | tr '\n' ' ')"
[ "$fget_disk_usb" ] || fget_disk_usb="-" && fget_disk_usb="$(tr ' ' '\n' <<< "$fget_disk_usb" | sort | tr '\n' ' ')"
[ "$fget_disk_mmc" ] || fget_disk_mmc="-" && fget_disk_mmc="$(tr ' ' '\n' <<< "$fget_disk_mmc" | sort | tr '\n' ' ')"
[ "$fget_disk_nvme" ] || fget_disk_nvme="-" && fget_disk_nvme="$(tr ' ' '\n' <<< "$fget_disk_nvme" | sort | tr '\n' ' ')"
}
#assigne fget_distro
figet_distro(){ # thanks neofetch, assigne $fget_distro # 09/10/2017
local distro file
if type -p lsb_release >/dev/null; then distro="$(lsb_release -sd)";
elif type -p guix >/dev/null; then distro="GuixSD";
elif type -p crux >/dev/null; then distro="$(crux)";
else
# Source the os-release file
for file in /etc/os-release /usr/lib/os-release /etc/*release /usr/lib/*release; do
source "$file" && break
done
# Workarounds for distros that go against the os-release standard.
[[ -z "${distro// }" ]] && distro="$(gawk '/BLAG/ {print $1; exit}' /etc/*ease /usr/lib/*ease)"
[[ -z "${distro// }" ]] && distro="$(gawk -F '=' '{print $2; exit}' /etc/*ease /usr/lib/*ease)"
# for debian, add version
grep -qi 'Debian' /etc/issue && distro="$(sed 's/"//g' <<< $distro) $(< /etc/debian_version)"
fi
[[ -z "$distro" ]] && distro="$os (non déterminée)"
fget_distro="$distro"
}
# informations DMI, assigne $fget_dmi
figet_dmi(){ # 29/10/2017
# lors révision tester $(grep -s . /sys/class/dmi/id/*)
# ex: /sys/class/dmi/id/bios_vendor:American Megatrends Inc.
local product board bios tempo idmi indic1 indic2
unset indic1 indic2
# ligne1 Pc/produit
for idmi in sys_vendor product_name product_version chassis_type; do
tempo=$(cat /sys/class/dmi/id/$idmi 2>/dev/null)
tempo=$(sed 's/x.xx*//; s/To be filled by O\.E\.M\.//g' <<< $tempo | xargs)
if [ "$idmi" == "chassis_type" ]; then
[ "$tempo" == "10" ] && tempo="(Notebook)" || tempo="($tempo)"
fi
# indic1 pour tester égalité avec board
[[ "$idmi" == "sys_vendor" || "$idmi" == "product_name" ]] && indic1+="$tempo "
product+="$tempo "
done
# ligne2 carte mère
for idmi in board_vendor board_name board_version; do
tempo=$(cat /sys/class/dmi/id/$idmi 2>/dev/null)
tempo=$(sed 's/x.xx*//; s/To be filled by O\.E\.M\.//g' <<< $tempo | xargs)
# indic2 pour tester égalité avec product
[[ "$idmi" == "board_vendor" || "$idmi" == "board_name" ]] && indic2+="$tempo "
board+="$tempo "
done
# ligne3 bios
for idmi in bios_vendor bios_version bios_date; do
tempo=$(cat /sys/class/dmi/id/$idmi 2>/dev/null)
tempo=$(sed 's/x.xx*//; s/To be filled by O\.E\.M\.//g' <<< $tempo | xargs)
bios+="$tempo "
done
fget_dmi=$(printf '%7s: %s' "produit" "$product")$'\n'
[ "$indic1" != "$indic2" ] && fget_dmi+=$(printf '%7s: %s' "board" "$board")$'\n'
fget_dmi+=$(printf '%7s: %s' "bios" "$bios")
# for idmi in chassis_vendor chassis_version chassis_type; do
# tempo=$(cat /sys/class/dmi/id/$idmi 2>/dev/null)
# tempo=$(sed 's/x.xx*//' <<< $tempo)
# [[ "$idmi" == "chassis_type" && "$tempo" == "10" ]] && tempo="Notebook"
# chassis+="$tempo "
# done
}
figet_gpu(){ # thanks neofetch, assigne $fget_gpu # 09/10/2017
local gpu="$(lspci -mm | gawk -F '\\"|\\" \\"' '/"Display|"3D|"VGA/ {print $3 " " $4}')"
# debug: gpu="$(cat tests/lspci | gawk -F '\\"|\\" \\"' '/"Display|"3D|"VGA/ {print $3 " " $4}')"
case "$gpu" in
*"advanced"*)
gpu="${gpu//Intel*$'\n'}"
gpu="${gpu/'[AMD/ATI]' }"
gpu="${gpu/'[AMD]' }"
gpu="${gpu/OEM }"
gpu="${gpu/ \/ *}"
gpu="${gpu/*\[}"
gpu="${gpu/\]*}"
gpu="AMD $gpu" ;;
*"nvidia"*)
gpu="${gpu//Intel*$'\n'}"
gpu="${gpu/*\[}"
gpu="${gpu/\]*}"
gpu="NVIDIA $gpu" ;;
*"virtualbox"*)
gpu="VirtualBox Graphics Adapter" ;;
esac
[[ "$gpu" =~ "intel" ]] && gpu="Intel Integrated Graphics"
fget_gpu="$gpu"
}
# infos température et fan via acpi, assigne $fget_hw
figet_hw(){ #v2 14/10/2017
local name labelF inputF labelT inputT critT hystT maxiT fan temp ihw
if [ ! -d /sys/class/hwmon/ ]; then
fget_hw="gestion acpi hwmon non accessible"
return 1
fi
unset fan temp
for ihw in $(ls /sys/class/hwmon/); do
[ -e /sys/class/hwmon/$ihw/name ] && name="$(cat /sys/class/hwmon/$ihw/name)" || name="indéfini"
## TEMPÉRATURE
if grep -Eq 'temp[0-9]+' <<< $(ls /sys/class/hwmon/$ihw/) ; then
# extraction label
# labelT=$(printf "%s/" "$(cat /sys/class/hwmon/$ihw/temp*_label 2>/dev/null)" | sed 's/ //g' | tr '\n' ' ')
labelT=$(printf "%s/" "$(cat /sys/class/hwmon/$ihw/temp*_label 2>/dev/null)" | tr ' ' '.' | tr '\n' ' ')
# extraction températures
inputT=$(gawk '$0!="" && $0!=0 {printf "%.1f/", $1/1000}' <<< $(cat /sys/class/hwmon/$ihw/temp*_input 2>/dev/null))
critT=$(gawk '$0!="" && $0!=0 {printf "%.1f/", $1/1000}' <<< $(cat /sys/class/hwmon/$ihw/temp*_crit 2>/dev/null))
hystT=$(gawk '$0!="" && $0!=0 {printf "%.1f/", $1/1000}' <<< $(cat /sys/class/hwmon/$ihw/temp*_crit_hyst 2>/dev/null))
maxiT=$(gawk '$0!="" && $0!=0 {printf "%.1f/", $1/1000}' <<< $(cat /sys/class/hwmon/$ihw/temp*_max 2>/dev/null))
# suppression doublons
critT=$(echo $critT | tr '/' '\n' | sort --unique | tr '\n' '/')
hystT=$(echo $hystT | tr '/' '\n' | sort --unique | tr '\n' '/')
maxiT=$(echo $maxiT | tr '/' '\n' | sort --unique | tr '\n' '/')
# suppression premier /
[ ${critT:0:1} == "/" ] && critT=${critT:1}
[ ${hystT:0:1} == "/" ] && hystT=${hystT:1}
[ ${maxiT:0:1} == "/" ] && maxiT=${maxiT:1}
# suppression dernier caractère (/) fin (nécessaire si multi-valeurs)
[ "$inputT" ] && inputT=${inputT::-1}
[ "$labelT" ] && labelT=${labelT::-1}
[ "$critT" ] && critT=${critT::-1}
[ "$hystT" ] && hystT=${hystT::-1}
[ "$maxiT" ] && maxiT=${maxiT::-1}
# formation affichage
if [ "$inputT" ]; then
temp+="$(printf "%-8s %s°C %s " "$name" "$inputT" "$labelT")"
[ "$critT" ] && temp+="(crit: $critT""°C) "
[ "$hystT" ] && temp+="(hyst: $hystT""°C) "
[ "$maxiT" ] && temp+="(maxi: $maxiT""°C) "
[ "$temp" ] && temp+=$'\n'
fi
fi
## FAN
if grep -Eq 'fan[0-9]+' <<< $(ls /sys/class/hwmon/$ihw/) ; then
# extraction label
labelF=$(printf "%s/" $(cat /sys/class/hwmon/$ihw/fan*_label 2>/dev/null))
# extraction vitesse fan, \047=' pour insérer séparateur de milliers
inputF=$(gawk '$0!="" && $0!=0 {printf "%\047d/", $1}' <<< $(cat /sys/class/hwmon/$ihw/fan*_input 2>/dev/null))
# suppression dernier caractère (/) fin (nécessaire si multi-valeurs)
[ "$labelF" ] && labelF=${labelF::-1}
[ "$inputF" ] && inputF=${inputF::-1}
# formation affichage
if [ "$inputF" ]; then
fan+="$(printf "%-8s %st/mn %s" "$name" "$inputF" "$labelF")"$'\n'
fi
fi
done
fget_hw="$temp$fan"
[ "$fget_hw" ] && fget_hw=${fget_hw::-1}
}
# assigne $fg_ip, $fg_ip_tp, $fg_gws, $fg_gws_tp, $fg_ifn_prior, $fg_ifn, $fg_mac, fg_mac_tp
figet_ip(){ # 27/10/2017
local ifn
[ "$(f__cmd_exist ip)" ] || return 1
fg_ip="$(sed '/[[:digit:]]:[[:blank:]]lo.*inet/d; /inet6.*scope/d' <<< $(ip -o a) | gawk '{print " ",$4,"(",$2,")"}')"
fg_ip_tp="$(sed -E 's/(^.*wl.*)/\1 (wifi)/;s/(^.*en.*|^.*eth.*)/\1 (ethernet)/' <<< $fg_ip)"
fg_gws="$(LC_ALL=C ip -4 route | gawk '/default via/ {print " ",$3,"(",$5,")"}')"
fg_gws+="$(LC_ALL=C ip -6 route | gawk '/default via/ {print " ",$3,"(",$5,")"}')"
fg_gws_tp="$(sed -E 's/(^.*wl.*)/\1 (wifi)/;s/(^.*en.*|^.*eth.*)/\1 (ethernet)/' <<< $fg_gws)"
fg_ifn_prior="$(ip route get 255.255.255.255 | sed -nr 's/.*src ([0-9.]+).*/\1/p')"
for ifn in $(ls /sys/class/net/) ; do
[ "$ifn" != "lo" ] && fg_ifn+=" $ifn"$'\n'
[ "$ifn" != "lo" ] && fg_mac+=" $ifn: $(< /sys/class/net/$ifn/address)"$'\n'
done
fg_ifn="$(sed '/^$/d' <<< $fg_ifn)" # suppression \n final
fg_mac="$(sed '/^$/d' <<< $fg_mac)" # suppression \n final
fg_mac_tp="$(sed -E 's/(^.*wl.*)/\1 (wifi)/;s/(^.*en.*|^.*eth.*)/\1 (ethernet)/' <<< $fg_mac)"
fg_ifn=${fg_ifn::-1} # suppression dernier $'\n'
fg_mac=${fg_mac::-1} # suppression dernier $'\n'
}
# $1=4|6, assigne $fg_public
figet_ip_pub(){ # 27/10/2017
local dig_test ip_test iip
list_ip4(){
ip_test+=" http://whatismyip.akamai.com"
ip_test+=" http://ipof.in/txt"
ip_test+=" http://eth0.me"
ip_test+=" http://ipecho.net/plain"
ip_test+=" http://alma.ch/myip.cgi"
ip_test+=" http://checkip.amazonaws.com"
ip_test+=" http://eth0.me"
ip_test+=" http://ipecho.net/plain"
ip_test+=" api.infoip.io/ip" # http & https
ip_test+=" api.ipify.org" # http & https
ip_test+=" ipinfo.io/ip" # http & https
}
list_ip6(){
ip_test+=" http://ipv6.whatismyip.akamai.com"
ip_test+=" http://bot.whatismyipaddress.com"
ip_test+=" ip.tyk.nu" # http & https
ip_test+=" l2.io/ip" # http & https
ip_test+=" ident.me" # http & https
ip_test+=" icanhazip.com" # http & https
ip_test+=" wgetip.com" # http & https
ip_test+=" https://canhazip.com"
ip_test+=" https://tnx.nl/ip"
}
list_ip4_dig(){
dig_test+=" whoami.akamai.net/@ns1-1.akamaitech.net"
dig_test+=" myip.opendns.com/@resolver1.opendns.com"
dig_test+=" myip.opendns.com/@resolver2.opendns.com"
dig_test+=" myip.opendns.com/@resolver3.opendns.com"
dig_test+=" myip.opendns.com/@resolver4.opendns.com"
}
list_ip6_dig(){
dig_test+=" -6/myip.opendns.com/aaaa/@resolver1.ipv6-sandbox.opendns.com"
dig_test+=" -6/myip.opendns.com/aaaa/@resolver2.ipv6-sandbox.opendns.com"
}
unset fg_public
if [ "$1" == "4" ]; then
ping -4 -c1 google.com &>/dev/null || ping -4 -c1 free.fr &>/dev/null || return 1 # test connectivité
list_ip4_dig
list_ip4
ip_telnet=4.ifcfg.me
elif [ "$1" == "6" ]; then
ping -6 -c1 google.com &>/dev/null || ping -6 -c1 free.fr &>/dev/null || return 1 # test connectivité
list_ip6_dig
list_ip6
ip_telnet=6.ifcfg.me
fi
if [ "$(f__cmd_exist dig)" ] && [ -z "$fg_public" ]; then
for iip in $dig_test ; do
fg_public="$(dig +short $(sed 's;/; ;g' <<< $iip))"
[ "$fg_public" ] && break
done
fi
if [ "$(f__cmd_exist wget)" ] && [ -z "$fg_public" ]; then
cmd="wget --quiet --timeout=5 -O - "
for iip in $ip_test ; do
fg_public="$($cmd $iip)"
[ "$fg_public" ] && break
done
fi
if [ "$(f__cmd_exist curl)" ] && [ -z "$fg_public" ]; then
cmd="curl --silent --location --retry 0 --max-time 5" #--location pour aider redirections
for iip in $ip_test ; do
fg_public="$($cmd $iip)"
[ "$fg_public" ] && break
done
fi
if [ "$(f__cmd_exist telnet)" ] && [ -z "$fg_public" ]; then
fg_public="$(telnet $ip_telnet 23 2>/dev/null | grep $1 | cut -d ' ' -f 4)"
fi
if [ "$(f__cmd_exist nc)" ] && [ -z "$fg_public" ] && [ "$1" != "IPv6" ]; then
fg_public="$(nc $ip_telnet 23 2>/dev/null | grep $1 | cut -d ' ' -f 4)"
fi
if [ -z "$fg_public" ]; then
f__error "il manque une des commandes suivantes:\n" \
"dig / wget / curl / telnet / nc \n" \
"ou les ip de test sont devenues défaillantes\n" \
"réessayer après avoir installé dig (dnsutils) et wget\n" \
"si l'erreur persiste, merci de prévenir $projet, $contact"
fi
}
# $1=mem|swap [total|notitle|nocoltitle], assigne $fget_mem ($2=debug all cols + free)
figet_mem(){ # 13/10/2017
local freeDebug MemTotal MemFree MemAvailable Buffers Cached SReclaimable Shmem MemUsed
local SwapTotal SwapFree SwapCached col
[ "$2" == "debug" ] && freeDebug="$(free -hw | sed '3d')"
while IFS=':' read a b; do
[ "$a" == "MemTotal" ] && MemTotal="${b/kB}" #echo "$a $((${b/kB}/1024))" ! partie entière !
[ "$a" == "MemAvailable" ] && MemAvailable="${b/kB}"
[ "$a" == "MemFree" ] && MemFree="${b/kB}"
[ "$a" == "Buffers" ] && Buffers="${b/kB}"
[ "$a" == "Cached" ] && Cached="${b/kB}"
[ "$a" == "SReclaimable" ] && SReclaimable="${b/kB}"
[[ "$a" =~ Shmem$|MemShared$ ]] && Shmem="${b/kB}" # = free shared
[ "$a" == "SwapTotal" ] && SwapTotal="${b/kB}"
[ "$a" == "SwapFree" ] && SwapFree="${b/kB}"
[ "$a" == "SwapCached" ] && SwapCached="${b/kB}"
done <<< $(< /proc/meminfo)
MemUsed=$(( $MemTotal-($MemFree+$Buffers+$Cached+$SReclaimable) ))
SwapUsed=$(( $SwapTotal-$SwapFree ))
totalTotal=$(( $MemTotal+$SwapTotal ))
totalUsed=$(( $MemUsed+$SwapUsed ))
totalAvailable=$(( $MemAvailable+$SwapFree ))
MemTotal=$( printf '%10s' $(f__unit_human $MemTotal) )
MemUsed=$( printf '%10s' $(f__unit_human $MemUsed) )
MemAvailable=$( printf '%10s' $(f__unit_human $MemAvailable) )
MemFree=$( printf '%10s' $(f__unit_human $MemFree) )
Buffers=$( printf '%10s' $(f__unit_human $Buffers) )
Cached=$(( $Cached+$SReclaimable ))
Cached=$( printf '%10s' $(f__unit_human $Cached) )
Shmem=$( printf '%10s' $(f__unit_human $Shmem) )
SwapTotal=$( printf '%10s' $(f__unit_human $SwapTotal) )
SwapFree=$( printf '%10s' $(f__unit_human $SwapFree) )
SwapUsed=$( printf '%10s' $(f__unit_human $SwapUsed) )
SwapCached=$( printf '%10s' $(f__unit_human $SwapCached) )
totalTotal=$( printf '%10s' $(f__unit_human $totalTotal) )
totalUsed=$( printf '%10s' $(f__unit_human $totalUsed) )
totalAvailable=$( printf '%10s' $(f__unit_human $totalAvailable) )
unset fget_mem
if [[ ! "$*" =~ notitle ]]; then
[[ "$*" =~ nocoltitle ]] || col="mém.:"
fget_mem="$col totale utilisée disponible"$'\n'
fi
if [[ "$*" =~ mem ]]; then
[[ "$*" =~ nocoltitle ]] || col="ram :"
fget_mem+="$col$MemTotal$MemUsed$MemAvailable"$'\n'
fi
if [[ "$*" =~ swap ]]; then
[[ "$*" =~ nocoltitle ]] || col="swap:"
fget_mem+="$col$SwapTotal$SwapUsed$SwapFree"$'\n'
fi
if [[ "$*" =~ total ]]; then
[[ "$*" =~ nocoltitle ]] || col="tot.:"
fget_mem+="$col$totalTotal$totalUsed$totalAvailable"$'\n'
fi
if [ "$2" == "debug" ]; then
local espace=$(printf '% 6s')
fget_mem="$espace""mém.: totale utilisée libre shared buffers cache disponible"$'\n'
fget_mem+="$espace""ram :$MemTotal$MemUsed$MemFree$Shmem$Buffers$Cached$MemAvailable"$'\n'
fget_mem=${fget_mem::-1} # suppression dernier $'\n'
echo "$fget_mem"
echo "$freeDebug"
fi
fget_mem=${fget_mem::-1} # suppression dernier $'\n'
}
figet_mod_net(){ # thanks wireless-info, assigne $fget_mod_net # 01/10/2017
local MODMATCHES LSMODMATCHES
MODMATCHES="(air|ar5|at7|ath[^3]?|b43|bcma|brcm|carl|ipw|iwl|ndis|r(818|8192[eu]|871|92su)|8(188|189|192|723|812)[acde][esu]|rt[23567]|rtl|ssb|wl|(cfg|mac)80211)"
LSMODMATCHES="(wmi|(dell|ideapad)[-_]laptop)"
fget_mod_net="$(lsmod | grep -E "(^|[[:punct:] ])($MODMATCHES|$LSMODMATCHES)[^[:punct:] ]*([[:punct:] ]|$)")"
}
# assigne $fget_nb_screen, $fget_resolution. si $ENV_SSH pas vide, return avec
# fget_resolution=n/a (ssh) & fget_nb_screen=n/a
figet_screen(){ #v2 26/10/2017
local resolution
fget_nb_screen="n/a"
fget_resolution="n/a"
[ "$ENV_SSH" ] && fget_resolution+=" (ssh)"
[ "$ENV_SSH" ] && return 0
# xrandr & et xdpyinfo ne retourne pas de nombre écrans correct (multiplex? hybrid?)
if [ $(f__cmd_exist xrandr) ]; then
resolution=$( gawk '/[0-9]\*/ {gsub(/\*\+/,"",$2); printf "%s pixels (%dHz), ", $1, $2}' <<< $( xrandr --query ) )
elif [ $(f__cmd_exist xdpyinfo) ]; then
resolution=$( gawk '/dimensions/ { print $2, $3 ", " }' <<< $(xdpyinfo) )
fi
resolution="${resolution%,*}"
fget_resolution="$resolution"
fget_nb_screen=$( grep -o 'pixels' <<< $fget_resolution | grep -c . )
}
figet_shell(){ # thanks neofetch, assigne $fget_shell # 04/10/2017
local shell
shell="${SHELL##*/}"
case "${SHELL##*/}" in
"bash")
shell+=" ${BASH_VERSION/-*}" ;;
"zsh")
shell+="$(zsh --version)"
shell="${shell/ zsh}" ;;
"mksh" | "ksh")
shell+="$("$SHELL" -c 'printf "%s" "$KSH_VERSION"')"
shell="${shell/ * KSH}" ;;
"tcsh" | "csh")
shell+="$("$SHELL" --version)"
shell="${shell/tcsh}"
shell="${shell/\(*}" ;;
"fish")
shell+="$(fish -c 'printf "%s" "$FISH_VERSION"')" ;;
esac
fget_shell="$shell"
}
figet_test_batt(){ # 23/10/2017
local text var_temp objet
# matériel
figet_dmi
figet_batt
###
f_display "fget_dmi" "sans"
text="--- \n\n"
text+="## batterie test \n\n"
# acpi éventuel
if [ "$(f__cmd_exist acpi)" ]; then
var_temp=$(acpi -abi)
[ "$var_temp" ] || var_temp="pas de batterie dans $(f__cmd_exist acpi)"
f_display "var_temp" "cmd" "acpi -abi"
fi
# upower
if [ "$(f__cmd_exist upower)" ]; then
objet=$(grep -i 'battery' <<< $(upower -e))
var_temp=$(upower -i $objet)
f_display "var_temp" "cmd" "upower -i $objet"
fi
# scandir
[ -d /sys/class/power_supply/BAT* ] && f_display_scandir "/sys/class/power_supply/" 1
# fonction script
f_display "fg_batt" "var" "figet_batt"
}
figet_test_dmi(){ # 21/10/2017
local text var_temp
text+="## dmi test \n\n"
# /sys/class/dmi/
var_temp="/sys/class/dmi/"
f_display_scandir "$var_temp" 1
# fonction script
figet_dmi
f_display "fget_dmi" "var" "figet_dmi"
}
figet_test_hw(){ # 22/10/2017
local text var_temp
# matériel
figet_dmi
f_display "fget_dmi" "sans"
text="--- \n\n"
###
text+="## hwmon test \n\n"
# sensors et acpi éventuel
if [ "$(f__cmd_exist sensors)" ]; then
var_temp=$(sensors -u)
f_display "var_temp" "cmd" "sensors -u"
fi
if [ "$(f__cmd_exist acpi)" ]; then
var_temp=$(acpi -V | grep -E 'Thermal|Cooling')
f_display "var_temp" "cmd" "acpi -V"
fi
# /sys/class/hwmon/
var_temp="/sys/class/hwmon/"
f_display_scandir "$var_temp" 1
# /sys/class/thermal/thermal_zone0/
var_temp="/sys/class/thermal/thermal_zone0/"
f_display_scandir "$var_temp" 0
# /sys/devices/platform/coretemp.0/hwmon/
var_temp="/sys/devices/platform/coretemp.0/hwmon/"
f_display_scandir "$var_temp" 1
# analyse méthode neofetch
if [ -f "/sys/class/hwmon/hwmon0/temp1_input" ]; then
var_temp="$(< "/sys/class/hwmon/hwmon0/temp1_input")"
var_temp="$((var_temp * 100 / 10000))" # 33000 x 100 / 10 000 = 330
var_temp="[${var_temp/${var_temp: -1}}.${var_temp: -1}°C]" # formatage 1 point décimal
else
var_temp=" non accessible"
fi
f_display "var_temp" "var" "hwmon0/temp1_input ala neofetch"
# fonction script
figet_hw
f_display "fget_hw" "var" "figet_hw"
}
figet_wm(){ # thanks neofetch, assigne $fget_wm # 22/10/2017
if [ "$ENV_SSH" ]; then
fget_wm="n/a (ssh)"
return 0
fi
local id wm
if [ -n "$DISPLAY" ]; then
id="$(xprop -root -notype | gawk '$1=="_NET_SUPPORTING_WM_CHECK:"{print $5}')"
wm="$(xprop -id "$id" -notype -f _NET_WM_NAME 8t)"
wm="${wm/*_NET_WM_NAME = }"
wm="${wm/\"}"
wm="${wm/\"*}"
# Fallback for Wayland wms
[[ "$wm" == "xwlc" ]] && wm="$(ps -e | grep -m 1 -o -F -e "sway" -e "orbment" -e "velox" -e "orbital")"
else
wm="pas de windows manager détecté"
fi
fget_wm="$wm"
}
# aiguillage export paste
fipaste(){
f__requis "curl" # requis pour paste
fipaste_curl_pastery "$fileOutput" "$pasteDuration" "$optDebug"
# à tester fipaste_curl_markdownshare "$fileOutput"
}
# $1 fichier à exporter, $2 durée de conservation en jour; $3 debug
fipaste_curl_pastery(){ # 25/10/2017
[ -e "$1" ] || f__error "fichier $1 inexistant"
local curl id pluriel
# curl -X POST "https://www.pastery.net/api/paste/?title=getInfo&language=markdown" -F file=@$1
curl="$(curl --silent -X POST "https://www.pastery.net/api/paste/?title=getInfo_$version&language=markdown&duration=$(($2*1440))" --data-binary @$1)"
if grep -q '"result": "error' <<< "$curl" ;then
f__info "$RED""Erreur critique export rapport:"
f__info "$curl"
f__info "merci contacter $projet, $contact pour aider à parfaire le script"
else
id="$(echo $curl | cut -d '"' -f 4)"
[ "$pasteDuration" -gt 1 ] && pluriel="s" || unset pluriel
f__info "votre paste:$GREEN https://www.pastery.net/$id/" \
"(valide pendant $RED$pasteDuration jour$pluriel)"
echo -e "exporté sur https://www.pastery.net/$id/ \n\n" >> "$fileOutput"
fi
[ "$3" == "debugPaste" ] && f__info "$curl"
# UTF-8
# ?api_key=<api_key>
# &duration=<duration> en mn, 1 jour par défaut
# &language=autodetect possible
# &max_views=<max_views>
# 100ko max
#{"id": "kddgar", "title": "getInfo_2.5.0", "url": "https://www.pastery.net/kddgar/", "language": "markdown", "duration": 1439}
#{"result": "error", "error_msg": "Your request body was not valid UTF-8."}
}
fipaste_curl_markdownshare(){ # à tester/finir
[ -e "$1" ] || f__error "fichier $1 inexistant"
curl -H "Accept: application/json" -X POST -F "text=<$1" https://markdownshare.com/create/
#-A, --user-agent and -e, --referer options
#If you wish to allow a post to expire then add an expire= parameter too:
#expire=Nh Expire in N hours.
#expire=Nd Expire in N days.
#-d expire ? ou --data expire
}
# inscription dans tache upgrade en anacron hebdomadaire, via cron horaire, $1=upgrade|install|remove
fscript_cronAnacron(){ # 17/09/2017
local dirAnacron dirSpool fileAnacron
[ "$(type -t fscript_cronAnacron_special)" ] && fscript_cronAnacron_special # test, si fonction spécifique, appel
dirAnacron="/home/$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 /opt/bin/$script --upgrade 1>/dev/null" > "$fileAnacron" # juste erreurs en syslog
## anacron journalier pour dev logname
if [ -e "$fileDev" ]; then
echo "1 00 $script""Dev nice /opt/bin/$script --upgrade 1>/dev/null" >> "$fileAnacron"
fi
# création spool anacron utilisateur
mkdir -p "$dirSpool"
chown -R "$user_:" "$dirAnacron" "$dirSpool"
if [ "$EUID" -eq 0 ]; then
# crontab pour activation horaire anacron
echo "@hourly $user_ /usr/sbin/anacron -t $fileAnacron -S $dirSpool" >> /etc/crontab
fi
[ "$(grep "$script" /etc/crontab)" ] || echo f__error "inscription crontab" \
"certains systèmes semblent poser poser problème, merci de rapporter ce bug à $projet, $contact"
;;
remove )
rm "$dirSpool/$script"* &>/dev/null
rm "$fileAnacron" &>/dev/null
rmdir "$dirSpool" "$dirAnacron" &>/dev/null
;;
esac
}
# version script en ligne, assigne $versionScript, $script_aJour=ok|ko
fscript_get_version(){ # 27/10/2017
f__info "raw" "$GREEN""version script en cours: $version"
versionScript=$(wget -q --timeout=15 -O - "$urlScript" | grep -m1 '^version=' | cut -d'=' -f2)
if [ "$versionScript" ]; then
if [ "$version" != "$versionScript" ]; then
f__info "version script en ligne: $versionScript, mise à jour possible"
script_aJour="ko"
else
f__info "version script en ligne: $versionScript"
script_aJour="ok"
fi
else
f__info "version script en ligne$RED non accessible"
fi
}
# installation du script dans le système
fscript_install(){ # 08/10/2017
if grep -q 'bin' <<< "$(dirname $0)" ; then
f__info "$RED""l'installation dans le système doit se faire depuis un script local $GREEN(./$script -i )"
return 1
fi
if [ "$EUID" -ne 0 ]; then
f__info "vous devez être$RED ROOT$BLUE pour installer ce script dans le système"
f__sudo "exec $0 -i"
return $?
fi
[ "$(type -t fscript_install_special)" ] && fscript_install_special # test, si fonction spécifique, appel
f__requis "wget anacron cron"
# install /opt
mkdir -p /opt/bin/
cp -d "$(basename $0)" "/opt/bin/$script"
ln -s "/opt/bin/$script" "/usr/bin/$script" &>/dev/null
chmod 775 "/opt/bin/$script" # rwx rwx r-x, proprio user_
# cron/anacron install
fscript_cronAnacron "install"
# création fichier log
touch "$fileLogs"
chmod 664 "$fileLogs" # rw- rw- r--, proprio user_
chown "$user_:" "$fileLogs" "/opt/bin/$script"
[ -e "$fileDev" ] || rm "$(basename $0)" &>/dev/null ## 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 ./)"
}
# suppression du script dans le système
fscript_remove(){ # 08/10/2017
if ! grep -q 'bin' <<< "$(dirname $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 "/opt/bin/$script" ];then
f__info "$RED$script n'est pas installé"
return 1
fi
if [ "$EUID" -ne 0 ]; then
f__info "vous devez être$RED ROOT$BLUE pour supprimer ce script dans le système"
f__sudo "exec $0 -r"
return $?
fi
[ "$(type -t fscript_remove_special)" ] && fscript_remove_special # test, si fonction spécifique, appel
# suppression de /opt
rm "/opt/bin/$script" &>/dev/null
unlink "/usr/bin/$script" &>/dev/null
# cron/anacron remove
fscript_cronAnacron "remove"
f__info "log" "$script $version supprimé du système."
}
# mise à jour script si dispo, v2, +update spécifique
# à tester avant généraliser fileInstall="/opt/bin/$script" ?
fscript_update(){ # 27/10/2017
local dirTemp="/tmp/$script-$RANDOM"
[ $(type -t fscript_update_special) ] && fscript_update_special # test, si fonction spécifique, appel
if [ -z "$updateSpecial" ] && ! grep -q 'bin' <<< "$(dirname $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
fscript_get_version
if [ "$script_aJour" == "ok" ]; then
f__info "log" "pas de mise à jour disponible pour $script $version"
return 0
fi
mkdir -p "$dirTemp"
wget -q --tries=2 --timeout=15 -O "$dirTemp/$script" "$urlScript"
if [ "$?" != "0" ]; then f__wget_test "$urlScript"; fi
cp -d "$dirTemp/$script" "$fileInstall"
rm -rf "$dirTemp/"
chmod 775 "$fileInstall" # rwx rwx r-x, proprio user_
chown "$user_:" "$fileInstall"
[ -z "$updateSpecial" ] && fscript_cronAnacron "upgrade"
f__info "log" "$script mis à jour en version $versionScript $updateSpecial"
}
prg_1(){ # début
echo > "$fileOutput"
chown $user_: "$fileOutput" &>/dev/null
chmod 666 "$fileOutput" &>/dev/null # rw-rw-rw-, si root permet écriture & effacement à tous
echo -e "> $script sur **$(uname -n)** \n" > "$fileOutput"
echo -e "$ligneRapport \n\n" >> "$fileOutput"
}
prg_2(){ # traitements principaux
if [ "$EUID" -eq 0 ]; then
f__info "des erreurs$YELLOW No protocol specified, Can't open display :0$BLUE peut indiquer un défaut de configuration système (Xorg, Wayland?)" \
"lancer le script en utilisateur pour avoir toutes les informations"
fi
printf " ."
if [[ "$1" == all || "$1" =~ s ]]; then #systeme, matériel -cs
echo -e "# Système et matériel \n\n" >> "$fileOutput"
for i in fi_systeme fi_cpu fi_mem fi_hw fi_batt fi_graph fi_disk fi_usb ; do
$i
printf "."
done
fi
if [[ "$1" == all || "$1" =~ c ]]; then #configuration #debian, packages -cc
echo -e "# Configuration et packages \n\n" >> "$fileOutput"
for i in fi_locale fi_vrms fi_sources ; do
$i
printf "."
done
fi
if [[ "$1" == all || "$1" =~ r ]]; then #reseau -cr
echo -e "# Réseau \n\n" >> "$fileOutput"
for i in fi_reseau fi_nm ; do
$i
printf "."
done
fi
if [[ "$1" == all || "$1" =~ a ]]; then #analyse -ca
echo -e "# Analyse \n\n" >> "$fileOutput"
for i in fi_system_analyse fi_log_xorg fi_journal ; do
$i
done
fi
}
prg_3(){ # fin de traitements
echo -e "--- \n" >> "$fileOutput"
echo -e "$ligneRapport \n" >> "$fileOutput"
f__dialog_oui_non "non" "\n exporter sur le pastebin par défaut?" && fipaste
f__info "le rapport est disponible en local, fichier:$YELLOW $fileOutput" \
"vous pouvez le visualiser ultérieurement avec $GREEN$script -l" \
"vous pourrez l'exporter ultérieurement avec $BLUE$script -p"
}
prg_menu(){ # 10/10/2017
function display_menu {
local centre=50 left=2 larg=60 reply line
if [ $(( $(tput cols) )) -le 80 ]; then
centre=$(( $(tput cols)/2+$left ))
larg=$(( $centre+3*$left ))
fi
tput cud 1
tput hpa $left
printf '%.'$larg's' "$1"
tput hpa $centre
printf '%.'$larg's' "$2"
}
printf " $GREEN$script -h$STD : afficher l'aide \n"
display_menu "$GREEN$script -c$RED""s$STD : catégorie système" \
"$GREEN$script -c$RED""c$STD : catégorie configuration"
display_menu "$GREEN$script -c$RED""r$STD : catégorie réseau" \
"$GREEN$script -c$RED""a$STD : catégorie analyse"
echo -e "\n\n les catégories peuvent être cumulées: \n" \
" $GREEN$script -c$RED""sa$STD générera un rapport sur le système & l'analyse"
printf "\n choix des catégories à générer (all pour toutes)? "
tput sc
printf "\n ( ne pas saisir le préfixe $YELLOW-c$STD, all par défaut)"
tput rc
read reply
[ "$reply" ] && reply="-c${reply,,}" || reply="all"
reply="$(sed 's/-call/all/' <<< $reply)"
exec $0 "$reply"
}
prg_alert_init(){ # 23/10/2017
bashVersion=($(grep -o 'version 4' <<< $(bash --version)))
[ ${bashVersion[1]} -ge 4 ] || f__error "bash v4 requis" \
"version installée: $(sed -n '1p' <<< $(bash --version))"
[ -f /proc/cpuinfo ] || f__error "/proc/cpuinfo non trouvé" "/proc ne doit pas être monté"
# test OS
OS=$(uname -s)
[[ ${OS,,} =~ linux || ${OS,,} =~ gnu ]] && OS="linux"
[[ ${OS,,} =~ bsd || ${OS,,} =~ Bitrig || ${OS,,} =~ DragonFly ]] && OS="bsd"
[[ ${OS,,} =~ cygwin || ${OS,,} =~ msys || ${OS,,} =~ mingw ]] && OS="windows"
[ "$OS" == "bsd" ] && f__info "ce script pour Linux n'est pas prévu de fonctionner sur BSD..."
[ "$OS" == "windows" ] && f__info "ce script pour Linux n'est pas prévu de fonctionner sous windows..."
[ "$OS" != "linux" ] && f__error "Linux requis"
# 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
[ "$EUID" -eq 0 ] && user_="root" || f__error "user détecté, mais pas de home: /home/$user_"
f__info "user root"
fi
}
######## début script / initialisation
PATH='/usr/sbin:/usr/bin:/sbin:/bin'; TERM=xterm ; IFS=$' \t\n'
export PATH TERM IFS
[[ "$SSH_CLIENT" || "$SSH_CLIENT" || "$SSH_CLIENT" ]] && ENV_SSH="ssh"
# logo et définition couleurs
f__affichage
# tests au démarrage
prg_alert_init
# requis pour fonctionnement programme
f__requis "gawk wget ip>iproute2 lspci>pciutils wc>coreutils"
options=$@
# traitement option paramètres
for j in $options; do
case $j in
--debug-paste )
optDebug="debugPaste"
;; # si debug, retour json de pastery.net
-t* )
pasteDuration="$(sed -En 's/-t([0-9]+)/\1/p' <<< $j)"
;; # durée de conservation standard du paste en jours
esac
done
options="$(sed -E 's/--debug-paste//g; s/-t[0-9]+//g' <<< $options | xargs)" # nettoyage options
[ "$options" ] || options="all"
# paramètres généraux
[ "$pasteDuration" ] || pasteDuration=7 # durée de conservation standard du paste en jours
fileOutput="getInfo_rapport.md"
fileLogs="/var/log/sdeb_$script.log"
fileDev="/opt/bin/fileDev"
fileInstall="/opt/bin/$script"
urlScript="https://frama.link/getInfo"
urlNotice="https://frama.link/doc-getInfo"
# test sur frama.link ok, sinon fallback sur framagit
if [[ "$options" =~ all|-d|-h|-c ]]; then
if ! f__wget_test "$urlScript" "test"; then
urlScript="https://framagit.org/kyodev/kyopages/raw/master/scripts/$script"
urlNotice="https://kyodev.frama.io/kyopages/scripts/getInfo/"
fi
fi
ligneRapport="Rapport du $(date '+%d/%m/%Y %H:%M %z') | $0 $* | [$script $version]($urlNotice)"
# traitement options menu catégories
for k in $options; do
categorie+="$(sed -En 's/-c([a-z]+)/\1/p' <<< $k)"
options="$(sed -E 's/-c[a-z]+//' <<< $k | xargs)"
done
[ "$categorie" ] && options+=" -c$categorie"
# actions
for j in $options; do
case $j in
-t | --test )
prg_1 "$*"
fi_disk
prg_3
exit ;; # test seulement
-c* | all )
[ "$j" == "-c" ] && exec $0 "menu"
prg_1 "$*"
j=$(sed -E 's/-c//' <<< $j)
prg_2 "$j"
prg_3
exit ;; # rapport complet ou par catégorie
-j )
prg_1 "$*"
prg_2 "a"
exit ;; # exporte le rapport existant
-l )
[ -e $fileOutput ] && cat $fileOutput || f__info "pas de rapport à afficher" \
"vous devez lancer une analyse auparavant: $GREEN$script -l" \
"ou afficher l'aide $GREEN$script -h"
exit ;; # afficher le rapport existant
-p )
fipaste
exit ;; # exporte le rapport existant
-h )
f_help
exit ;; # affichage help
--debug-all )
prg_1 "$*"
figet_test_batt
figet_test_dmi
figet_test_hw
prg_3
exit ;; # test batterie, dmi, hwmon
--debug-batt )
prg_1 "$*"
figet_test_batt
prg_3
exit ;; # test batterie avec scan /sys/class/power_supply/
--debug-dmi )
prg_1 "$*"
figet_test_dmi
prg_3
exit ;; # test dmi avec affichage /sys/class/dmi/id/
--debug-hw )
prg_1 "$*"
figet_test_hw
prg_3
exit ;; # test hwmon avec affichage /sys/class/hwmon/
--ip )
if figet_ip_pub "4" ; then
f__info "raw" " ipv4 publique: $GREEN$fg_public"
else
f__info "$BLUE pas de connectivité ipv4"
fi
if figet_ip_pub "6" ; then
f__info "raw" " ipv6 publique: $GREEN$fg_public"
else
f__info "$BLUE pas de connectivité ipv6"
fi
exit ;; # affiche ip public
--mac )
figet_ip
f__info "fg_mac:\n$GREEN$fg_mac_tp"
exit ;; # affiche adresses mac
--ssid )
fi_ssid
exit ;; # affiche configurations ssid, root requis
-i | --install )
fscript_install
exit ;; # installation du script dans le système
-r | --remove )
fscript_remove
exit ;; # suppression du script dans le système
-u | --upgrade )
opType="upgrade" # log si f__error
fscript_update
exit ;; # upgrade script si maj possible
-us )
opType="upgrade" # log si f__error
updateSpecial="update spécial actif"
fileInstall="$(dirname $0)/$script"
fscript_update
exit ;; # upgrade spécial
-v | --version )
fscript_get_version
exit ;; # version du script, en ligne et exécuté
menu | * )
prg_1 "$*"
prg_menu
exit ;; # affichage help
esac
done
exit 0
wget -nv -O getInfo https://frama.link/getinfo
chmod +x getInfo && ./getInfo
wget -nv -O getInfo https://framagit.org/kyodev/kyopages/raw/master/scripts/getInfo