Table des matières
3 billet(s) pour janvier 2026
| Notes rsh rcp | 2026/01/21 18:08 | Jean-Baptiste |
| Git - Duplication d'un dépôt | 2026/01/19 10:22 | Jean-Baptiste |
| Exemple simple de conf Nagios | 2026/01/14 10:07 | 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:-}" == "" ] then return 0 # TRUE else return 1 # FALSE fi } 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" # check if directory exists dir_exists() { if [ -d "$1" ] then return 0 else return 1 fi } 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
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 !
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.
Installer les pilotes scanner Canon LiDE30 sur MacOSX
Apparemment LiDE30 est comme N1240U
I Installation des pilotes SANE / TWAIN
Aller sur http://www.ellert.se/twain-sane/
Télécharger les 5 paquages “Binary” (les SDK sont destinés au développeurs)
Pour MacOSX Yosemite
Sha256sum (pour information)
4da70865b827f4972db8cc92bc9389139b26f2e949e8d0719548051c2e845c19 gettext.pkg 079dfcbf1e3026ec447a5bb390a6f08272eb5c0af8641692d6feb2a8a7cc5a67 libusb.pkg d9a079d3ce86b42647eaa9573ba24a3970d9ed3561b8f90d58401f5c21667fdd sane-backends.pkg 0c970e9ca1be19f20365e155aa9f59edd60a33d295b5cd2c39b4cff6f33cb4d3 SANE-Preference-Pane.pkg 5623ef7fac5c033f5f9eb934b1f11a47db27d7285d77119eb048d8bf9cfa0485 TWAIN-SANE-Interface.pkg
2 Installation TWAIN Bridge
Aller sur http://janegil.net/2014/01/twain-scanners-in-os-x-maverick/
Télécharger TwainBridge Maverick Fix.pkg http://files.janegil.net/TwainBridge%20Maverick%20Fix.pkg
Sha256sum (pour information)
330c12d336315f9f416d31710264000a88392e210cb29a5332f5d0df37a28a35 TwainBridge Maverick Fix.pkg
3 Utilisation
On peut utiliser Transfert d’images (Image Capture app) inclus dans MacOSX.
Certaines résolutions sont mal acceptés créant des images entrelacées
Obsolète et pas Libre. Marche plus sur MacOSX Yosemite
Marche sans rien faire sur Debian/Ubuntu mais sous MacOSX voici la manip.
1) Installer le canoScan Toolbox
2) Installer ScanGear CS dans Applications/CanoScan Toolbox 4.1/Plug-Ins
Fichier lide20lide30n670un676un1240uosx7011aen.dmg
Vérifier la présence de du fichier suivant à l’emplacement indiqué :
Applications/CanoScan Toolbox 4.1/Plug-Ins/ScanGear CS 7.0X
3) Lancer CanoScan Toolbox X présent dans Applications.
4) Cliquez sur Scan-1
5) Dans Link scanned image to cliquez sur Set…
6) Indiquez le fichier et l’emplacement suivant :
Applications/CanoScan Toolbox 4.1/Plug-Ins/ScanGear CS 7.0X
7) Cliquer sur Scan et ca marche
