Table des matières
- 2026:
- 2025:
4 billet(s) pour juillet 2026
| Procédure simple augmentation de la SWAP | 2026/07/17 15:49 | Jean-Baptiste |
| Exemple git clone avec Ansible | 2026/07/16 14:47 | Jean-Baptiste |
| Windows exe - Comparaison de fichiers binaires | 2026/07/16 10:25 | Jean-Baptiste |
| Pb git | 2026/07/01 17:36 | Jean-Baptiste |
Script bash fonctions en vrac
Voir Fonctions conversion Hexa ASCII
Fonctions récupérées de http://www.trapkit.de/tools/checksec.sh
#! /bin/bash set -euo pipefail IFS=$' \t\n' export LC_ALL=C SCRIPT_NAME=$(basename "$0") readonly SCRIPT_NAME SCRIPT_DIR=$(readlink -m "$(dirname "$0")") readonly SCRIPT_DIR # Launch this script as root if [ $EUID != 0 ]; then sudo "$0" "$@" exit $? fi [ -r /etc/default/plop ] && . /etc/default/plop # check if command exists command_exists() { type $1 > /dev/null 2>&1; } command_exists() { command -v "$1" >/dev/null 2>&1 || ( echo "I require $1 but it's not installed. Aborting." >&2 exit 127 ) } for COMMAND in "nova" "glance" "dmidecode" "tr" do command_exists "${COMMAND}" done exit_si_erreur(){ if [ $1 != 0 ] then echo "Sortie en erreur." exit 1 fi } # plop ; exit_si_erreur $? get_mountpoint() { df -l --output=target "$1" |sed -e "1d" ;} # check if directory is empty dir_is_empty() { if [ -z "$(ls -A $1)" ] then return 0 else return 1 fi } isNonEmptyStr() { echo "$@" | grep -q -v -e "^$" ;} is_empty_var() { local var var=$1 if [[ "${!var:-}" == "" ]] } is_valid_value_var() { # Syntax exemple : # is_valid_value_var BOOL y n && echo "VAR 'BOOL' is 'y' or 'n'" # is_valid_value_var NUM 1 2 3 || echo "VAR 'NUM' is not 1, 2, or 3" local var=$1 shift for value in "$@" do if [ "${!var-}" == "$value" ] then return 0 # TRUE fi done return 1 # FALSE } isDevMounted() { findmnt --source "$1" >/dev/null;} #device only isPathMounted() { findmnt --target "$1" >/dev/null;} #path only isMounted() { findmnt "$1" >/dev/null;} #device or path is_mount() { findmnt -M "$1" >/dev/null ;} # Voir aussi la commande "mountpoint" # check user privileges root_privs() { if [ "$(/usr/bin/id -u)" -eq 0 ] then return 0 else return 1 fi } # Require that this runs as root. [ "$UID" -eq 0 ] || exec sudo "$0" "$@" # check if input is numeric isNumeric() { echo "$@" | grep -q -v -e "[^0-9]" ; } # check if input is a string isString() { echo "$@" | grep -q -v -e "[^A-Za-z]" ; } # check if file exist file_exist() { if [ $# -ne 1 ] then echo "illegal number of parameters" exit 2 fi [ -e "$1" ] } # return_only_files_exists() { ls -1 "$@" 2>/dev/null ;} if !(isString "$2") then printf "\033[31mError: Please provide a valid process name.\033[m\n\n" exit 1 fi if ! command -v zgrep &> /dev/null then zgrep() { zcat "$2" | grep "$1" } fi check_device() { if [ -c "$1" ] then wrap_good "$1" 'present' else wrap_bad "$1" 'missing' EXITCODE=1 fi } strip_comment() { grep -Ev -e '^\s+#|^#' - ;} abs() { local -i VAL=$1 echo "${VAL#-}" } calc_sum() { awk '{s+=$1} END {printf "%.0f", s}' "$*" ;} mk_calc() { awk "BEGIN { print $* }"; } # ex : mk_calc 7.5/3.2 => 2.34375 # Voir aussi expr : CACHE_USED=$( expr \( $CACHE_USED \* 1024 \) ) # A helper to make sure that Chrome is linked correctly function installation_status() { google-chrome-stable --version > /dev/null 2>&1 [ $? -eq 0 ] } ############ Source : https://github.com/danguita/scripts/blob/master/kickstart/kickstart-debian.sh say() { printf "\n[$(date --iso-8601=seconds)] %s\n" "$1" } # shellcheck disable=SC2317 confirm() { while true; do read -r -p "$1 (y/[n]): " answer case $answer in [Yy]* ) return 0; break;; [Nn]* ) return 1; break;; "" ) return 1; break;; * ) echo "Please answer yes or no.";; esac done } install_package() { sudo apt install --no-install-recommends -y "$@" } ######### quote () { local quoted=${1//\'/\'\\\'\'}; printf "'%s'" "$quoted" } dequote () { eval printf %s "$1" 2> /dev/null }
get_dev.sh
#! /bin/bash # Respond to the question : if a new file is created, this will be on which block device ? # Input arg 1 : path (file) # Outpout : path (block device) set -euo pipefail IFS=$' \t\n' export LC_ALL=C NEW_FILE="$1" is_regular_file() { [[ -f $1 ]] } # check if directory exists is_dir() { [[ -d $1 ]] } get_parent_dir() { local CHEMIN="$1" while ! "$(dir_exists "$CHEMIN")" do CHEMIN=$(dirname "$CHEMIN") done echo "$CHEMIN" } get_device() { df -lP "$(get_parent_dir "$NEW_FILE")" |awk 'NR==2{print $1}' } get_device "$(get_parent_dir "$NEW_FILE")"
A la place de
dir_exists /tmp/plop || mkdir -p /tmp/plop
Il est préférable de faire d'uuliser la commande install
install -d /tmp/plop
Faire une division
echo $(( 10 / 3 )) echo $(( VAR / 3 )) expr 10 / 3 calc() { awk "BEGIN { print ""$*"" }" }
my_command || { echo 'my_command failed' ; exit 1; }
Bash Colors
source : https://github.com/moby/moby/blob/master/contrib/check-config.sh
color() { local codes=() if [ "$1" = 'bold' ]; then codes=( "${codes[@]}" '1' ) shift fi if [ "$#" -gt 0 ]; then local code= case "$1" in # see https://en.wikipedia.org/wiki/ANSI_escape_code#Colors black) code=30 ;; red) code=31 ;; green) code=32 ;; yellow) code=33 ;; blue) code=34 ;; magenta) code=35 ;; cyan) code=36 ;; white) code=37 ;; esac if [ "$code" ]; then codes=( "${codes[@]}" "$code" ) fi fi local IFS=';' echo -en '\033['"${codes[*]}"'m' } wrap_color() { text="$1" shift color "$@" echo -n "$text" color reset echo } wrap_good() { echo "$(wrap_color "$1" white): $(wrap_color "$2" green)" } wrap_bad() { echo "$(wrap_color "$1" bold): $(wrap_color "$2" bold red)" ; } wrap_warning() { wrap_color >&2 "$*" red ; } error() { printf "${red}!!! %s${reset}\\n" "${*}" 1>&2 ; } failure() { local rc=$? echo -e "\t[FAILED]" return $rc } success() { echo -e "\t[ OK ]" return 0 } # Getpass read -s password read -s -p "Password: " get_free_space() { local chemin=$1 local -i free_mb free_mb="$(df --output=avail -m "$chemin" | tail -1 | tr -d ' ')" echo "$free_mb" } check_free_space() { # check_free_space /tmp/ 200 # will exit if /tmp/ less than 200MB local chemin=$1 local -i min_free_mb=$2 if [[ "$(get_free_space "$chemin")" -lt min_free_mb ]] then echo ERROR: No space left on device >&2 exit 28 fi }
Appelle d'une fonction bash depuis un autre shell
Même UID pour deux utilisateurs différents
cat <<EOF | bash -s -- same_uid_for_Utilisateur_and_utilisateur() { local -i RET=0 local -i UID_Utilisateur=$(id -u Utilisateur) RET=$(( RET + $? )) local -i UID_utilisateur=$(id -u utilisateur) RET=$(( RET + $? )) if [[ (RET -eq 0) && (UID_Utilisateur -ne UID_utilisateur) ]] then echo "usermod -o -u $(id -u utilisateur) -g $(id -g utilisateur) Utilisateur" chown -R utilisateur:utilisateur /var/opt/plop usermod -o -u $(id -u utilisateur) -g $(id -g utilisateur) Utilisateur fi exit } same_uid_for_Utilisateur_and_utilisateur EOF
Variables
SCRIPTPATH=$(dirname "$(realpath "$0")")
http://linuxfr.org/users/srb/journaux/waitend-executer-une-commande-apres-une-autre-deja-lancee
Si la commande waitpid n'est pas présente (util-linux-extra)
waitpid() { while ps -p $1 >/dev/null ; do sleep 5 done shift "$@" }
Strip char / trim ⇒ utiliser xargs ex :
load5=$(echo $UPTIME | awk -F, '{print $5}' | xargs)
Gestion des logs
#!/bin/bash NAME=plop LOG=/var/log/$NAME/$NAME.log exec >>$LOG 2>&1 exec &> >(tee -i /var/log/stackscript.log)
Gestion des erreurs
#! /bin/bash # to combine `set -e` (same as: `set -o errexit`) with an ERR trap set -eE # same as: `set -o errexit -o errtrace` err_report() { echo "Error on line $1" } trap 'err_report $LINENO' ERR echo hello | grep foo # This is line number 9
Source : https://unix.stackexchange.com/questions/39623/trap-err-and-echoing-the-error-line
Exécution à la sortie
trap 'rm -f "$TMP_INV_INI"' EXIT ERR
ou encore
trap '[ "$?" -eq 61 ] || exit 61' 0
No sigterm terminate
#!/bin/bash trap '' SIGTERM
Utilisation d'aliases dans un script shell
shopt -s expand_aliases source ~/.bash_aliases
Autres
How to make sure only one instance of a bash script runs ?
if [ $(pidof -x $0| wc -w) -gt 2 ]; then echo "More than 1" exit fi
Note : NOP en bash :
true
# We use this to print to the terminal when the context # of STDOUT is something other than the pty. declare -r TTY="$(tty)" printf $'%s %s\n' "${method}" "${path}" >${TTY} printf $'HTTP/1.1 %s %s\r\n' "${status:?}" "${msg:?}" | tee ${TTY}
Bash variable Substitution
Supprimer une extention de fichier
$ VAR="plop.txt"
$ echo ${VAR%.txt}
plop
$ var=sd_feeef_efe_g
$ echo "${var#?*_}"
feeef_efe_g
$ var=toto-tt-ll
$ echo "${var//-/_}"
toto_tt_ll
$ echo "${a/-/_}"
toto_tt-ll
Case upper lower majuscule minuscule
x="Hello" echo $x # HELLO y=${x,,} echo $y # hello z=${y^^} echo $z # HELLO
Dernier caractère d'une chaine
echo "${str: -1}" # ou echo ${str:0-1}
Renommer en supprimant un prefix
for fic in *.j2 ; do mv "$fic" "${fic#PREFIX_}" ; done
#!/bin/bash SCRIPT_PATH="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" ${SCRIPT_PATH}/sds_run.sh portal
negate() { if [[ $# -eq 0 ]]; then echo "ERROR. ENOSYS Function not implemented" >&2 return 38 else # ! "${@}" "${@}" && return 1 || return 0 fi }
$ negate true ; echo $? 1 $ negate false ; echo $? 0 $ true | negate ; echo $? ERROR. ENOSYS Function not implemented 38 $ false | negate ; echo $? ERROR. ENOSYS Function not implemented 38
Voir aussi :
- PIPESTATUS
- pipefail
Script automatisation entrées clavier automated input macro
Voir : http://www.thegeekstuff.com/2010/10/expect-examples/
#! /usr/bin/expect set timeout 10 spawn cadaver -p 192.168.56.1:3128 https://www.acme.fr/ expect "Do you wish to accept the certificate? (y/n)" send "y\n" interact
Ou dans un script bash
Exemple
#!/bin/bash # Get password from PAM read password # A few files we use to save and validate the results SHADFILE=/root/newshadow LOGFILE=/root/convpass.log # Let's see if the user has been converted already # The username is provided as an environment variable. CHECK=$(grep ^$PAM_USER $SHADFILE) if [ "x$CHECK" == "x" ]; then # The user has not been migrated already # # First, we need to validate that the provided password # is the correct one. # Since this script is run for ALL password-attempts, and # before the user is actually logged in, any brute force attack, # or wrong password entered by the user will also be sent to the # script. So we can't just blindly accept whatever password # is provided here. We try do a "su" to the provided user # with the provided password, using "expect", if the su succeds # the password is correct. But since su will succeed without a # password for root, we need to sudo the su command as an # unprivileged user - in this case the user "nobody" # # since we use expect inside a bash-script, # we have to escape tcl-$. expect << EOF spawn sudo -u nobody su "$PAM_USER" -c "exit" expect "Password:" send "$password\r" set wait_result [wait] # check if it is an OS error or a return code from our command # index 2 should be -1 for OS erro, 0 for command return code if {[lindex \$wait_result 2] == 0} { exit [lindex \$wait_result 3] } else { exit 1 } EOF # So if the expect-script returns 0, the su succeeded # and we can continue if [ $? == 0 ]; then echo "Password for user $PAM_USER is correct" >> $LOGFILE # Generate a new sha512 hash of the provided password: S512=$(echo "$password" | openssl passwd -6 -stdin) # Here, I simply generate a new shadow-file to replace the # old one later. # But if you need to push this to LDAP, you can of course # easily generate an ldif or whatever. echo "$PAM_USER:$S512:18000:0:99999:7:::" >> $SHADFILE exit 0 fi echo "Password for user $PAM_USER is incorrect" >> $LOGFILE fi # We return a non 0 exit status just in case, # but see the note for pam_exec below exit 1
Source : https://olathoresen.medium.com/linux-users-password-migration-b6bc4fab267d
Screenshot - capture d'écran
Outils graphiques :
- screengrab
- xfce4-screenshooter
lximage-qt -s- scrot
Ça dépend si vous utiliser X11 ou Wayland !
Notes cluster shell parallèle
- clustershell (clush)
- clusterssh (cssh)
- mussh
clush
apt-get install clustershell # ou pip install --user ClusterShell
/etc/clustershell/groups
all: host1 host2
-a pour “all”\ -B pour affichage groupé de STDOUT et STDERR si retour identique
clush -a -B
clush -w lame[1-4] -B
clush -w lame[1-6] --diff dmidecode -s bios-version
--- lame[1-4] (4) +++ lame[5-6] (2) @@ -1 +1 @@ -I36 +I15
Clush copy
Exemple SosRepport
Exemple
Génération du sosreport sur les cibles
clush -B -O ssh_options='-oStrictHostKeyChecking=no -oPort=2222' -l root --hostfile targets.lst sosreport -q --case-id 000000 --since 20230813000000 --batch
Récupération des sosreports
mkdir sosreports clush -B -O ssh_options='-oStrictHostKeyChecking=no -oPort=2222' -l root --hostfile targets.lst --rcopy '/var/tmp/sosreport-*.tar.xz' --dest sosreports/ clush -B -O ssh_options='-oStrictHostKeyChecking=no -oPort=2222' -l root --hostfile targets.lst --rcopy '/var/tmp/sosreport-*.tar.xz.sha256' --dest sosreports/
Renommage
cd sosreports/ # rename -nv '*' ` * rename '*' ` * rename '-' ` *
Nettoyage
clush -B -O ssh_options='-oStrictHostKeyChecking=no -oPort=2222' -l root --hostfile targets.lst rm -f /var/tmp/sosrepor*
List
clush -B --hostfile=hosts.lst
clush -B -O ssh_options='-oStrictHostKeyChecking=no -oPort=2222' -l admin --hostfile hosts.lst
Groupes
mkdir ~/.config/clustershell/ cp /etc/clustershell/groups.conf ~/.config/clustershell/
~/.config/clustershell/groups.d/plop.yaml
plop: www: 'www[1-4]' db: 'db-alpha,db-beta'
clush -B -g plop:www clush -B -g plop:*
mussh
mussh -H list.txt -b -c 'uptime'
mussh -H list.txt -b -C script.sh
mussh -m 7 -H ~/dev/list.txt -b -c 'apt-get -s dist-upgrade | grep "^[[:digit:]]\+ upgraded"'
ClusterSSH cssh
sudo apt-get install clusterssh
cssh c2-bl1 c2-bl2 c2-bl3 c2-bl4 c2-bl5 c2-bl6
sshpass
read -s SSHPASS ; export SSHPASS for ip in $(cat ip_all.lst) ; do sshpass -e ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=10 $ip /bin/true && echo $ip >> ip_ok.lst || echo $ip >> ip_nok.lst ;done for ip in $(cat ip_ok.lst) ; do sshpass -e ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=10 $ip grep 192.168.1.253 /etc/resolv.conf && echo $ip >> dns_ok.lst || echo $ip >> dns_nok.lst ;done
Faire des schémas d’architecture réseau sous GNU/Linux
Diagramme en code :
Voir Inkscape, Dia…
- Calligra_Flow (Kivio / KOffice)
- Les fonctions de diagramme de flux de travail que l'on pouvait retrouver à l'intérieur de Calligra Flow ont été intégré dans Karbon.
