Difference between revisions of "Scripturi BASH"
From linux360
(Ca sa arate mai colorat...) |
|||
(11 intermediate revisions by 3 users not shown) | |||
Line 1: | Line 1: | ||
== Exemple scripturi BASH == | == Exemple scripturi BASH == | ||
− | === Scripturi care | + | === Scripturi care permit schimbarea rapida a MAC+IP === |
[[User:Raptor360|Raptor360]] 12:33, 8 June 2006 (EEST) | [[User:Raptor360|Raptor360]] 12:33, 8 June 2006 (EEST) | ||
Line 9: | Line 9: | ||
Primeste ca parametru un IP si returneaza MAC-ul acestuia sau "" daca nu exista in retea nodul cu pricina. | Primeste ca parametru un IP si returneaza MAC-ul acestuia sau "" daca nu exista in retea nodul cu pricina. | ||
− | ''/usr/local/bin/getmac''<code | + | ''/usr/local/bin/getmac''<code bash>#!/bin/sh |
if [[ ! $IFDEVICE ]]; then | if [[ ! $IFDEVICE ]]; then | ||
Line 19: | Line 19: | ||
====be==== | ====be==== | ||
+ | Primeste ca parametru un IP si schimba MAC-ul si IP-ul pentru un device. | ||
− | + | ''/usr/local/bin/be''<code bash>#!/bin/bash | |
− | |||
− | ''/usr/local/bin/be''<code | ||
if [[ ! $IFDEVICE ]]; then | if [[ ! $IFDEVICE ]]; then | ||
Line 46: | Line 45: | ||
Schimba MAC-ul si IP-ul aleator conform unuia stocat in /etc/stored folosind scripturile anterioare. | Schimba MAC-ul si IP-ul aleator conform unuia stocat in /etc/stored folosind scripturile anterioare. | ||
− | ''/usr/local/bin/switchuser''<code | + | ''/usr/local/bin/switchuser''<code bash>#!/bin/bash |
notfound=1 | notfound=1 | ||
Line 77: | Line 76: | ||
silent. (output-ul nu este salvat, pentru aceasta puteti folosi nohup) | silent. (output-ul nu este salvat, pentru aceasta puteti folosi nohup) | ||
− | <code | + | <code bash>#!/bin/bash |
echo "Executing \"$*\"" | echo "Executing \"$*\"" | ||
Line 92: | Line 91: | ||
până la acolada închisă asociată acoladei deschise de mai sus. | până la acolada închisă asociată acoladei deschise de mai sus. | ||
− | Scriptul este:<code | + | Scriptul este:<code bash>#!/bin/bash |
# Bind zone remove script | # Bind zone remove script | ||
Line 133: | Line 132: | ||
=== Cautarea unui fisier ce contine un anumit string === | === Cautarea unui fisier ce contine un anumit string === | ||
− | <code | + | <code bash>find /path -name "*" -exec grep -H "<string>" '{}' \;</code> |
sau | sau | ||
− | <code | + | <code bash>grep -Hr "<string>" /path/</code> |
Fireste, <tt><string></tt> poate fi atat un sir de caractere cat si orice fel de expresie regulata suportata de versiunea particulara de <tt>grep</tt> disponibila pe masina in cauza.<br /> | Fireste, <tt><string></tt> poate fi atat un sir de caractere cat si orice fel de expresie regulata suportata de versiunea particulara de <tt>grep</tt> disponibila pe masina in cauza.<br /> | ||
Line 141: | Line 140: | ||
Daca doriti ca in output-ul comenzii <tt>grep</tt> expresia cautata sa fie cautata sa fie evidentiata puteti folosi parametrul <tt>--color</tt> astfel: | Daca doriti ca in output-ul comenzii <tt>grep</tt> expresia cautata sa fie cautata sa fie evidentiata puteti folosi parametrul <tt>--color</tt> astfel: | ||
− | <code | + | <code bash>grep --color -Hr "<string>" /path/</code> |
=== Stergerea fisierelor backup === | === Stergerea fisierelor backup === | ||
Line 148: | Line 147: | ||
Nu ar fi prea placut sa aveti un <tt>index.php~</tt> in <tt>DocumentRoot</tt> | Nu ar fi prea placut sa aveti un <tt>index.php~</tt> in <tt>DocumentRoot</tt> | ||
− | <code | + | <code bash>find /path -name "*~" | xargs -n 20 rm -f</code> |
=== Probleme cu spatiul pe disc? === | === Probleme cu spatiul pe disc? === | ||
Line 155: | Line 154: | ||
Linia urmatoare va ajuta, facand totodata si o sortare. | Linia urmatoare va ajuta, facand totodata si o sortare. | ||
− | <code | + | <code bash>du --max-depth=1 /path | sort -rn</code> |
+ | |||
+ | === Gasirea fisierelor duplicate intr-un director === | ||
+ | Aveti prea multe mp3-uri si majoritatea sunt duplicate dar cu alt nume sau orice de genul folositi scriptul de mai jos:D Eventual adaugati si un -maxdepth 1 sa nu fie recursiv. | ||
+ | <code bash> | ||
+ | #!/bin/sh | ||
+ | if [ ! -d "$1" ]; then | ||
+ | echo "Usage $0 <dir>" | ||
+ | exit 1 | ||
+ | fi | ||
+ | find "$1" -type f -print0 | xargs -0 -n1 md5sum | sort --key=1,32 | uniq -w 32 -d --all-repeated=prepend \ | ||
+ | |cut -f3- -d' '|sed 's/^$/Fisiere identice:/' | ||
+ | </code> | ||
+ | |||
+ | === Calcularea recordului de uptime === | ||
+ | |||
+ | Scriptul urmator va trebui plasat in crontab astfel incat sa ruleze periodic, de exemplu, din ora in ora. El va afisa in fisierul ''$output'' (initial ''/var/log/uptimeRecord.log'') output-ul comenzilor ''uptime'' si ''date'' (adica uptime-ul record si data la care a fost inregistrat). | ||
+ | |||
+ | <code bash>#!/bin/bash | ||
+ | |||
+ | # Copyright (C) 2006 Silvian Cretu <silvian86@yahoo.com> | ||
+ | # | ||
+ | # This program is free software; you can redistribute it and/or | ||
+ | # modify it under the terms of the GNU General Public License | ||
+ | # as published by the Free Software Foundation; either version 2 | ||
+ | # of the License, or (at your option) any later version. | ||
+ | # | ||
+ | # This program is distributed in the hope that it will be useful, | ||
+ | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
+ | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
+ | # GNU General Public License for more details. | ||
+ | # | ||
+ | # You should have received a copy of the GNU General Public License | ||
+ | # along with this program; if not, write to the Free Software | ||
+ | # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. | ||
+ | |||
+ | output='/var/log/uptimeRecord.log' | ||
+ | |||
+ | function compareHrs | ||
+ | { | ||
+ | uptimeCurent=`uptime` | ||
+ | if [ `echo $uptimeCurent | grep -c day` == '0' ]; then | ||
+ | # echo Uptime mai mic de o zi | ||
+ | uptimeCurentOre=`uptime | awk '{print $3}'` | ||
+ | uptimeRecordOre=`cat $output | head -1 | awk '{print $3}'` | ||
+ | else | ||
+ | uptimeCurentOre=`uptime | awk '{print $5}'` | ||
+ | uptimeRecordOre=`cat $output | head -1 | awk '{print $5}'` | ||
+ | fi | ||
+ | if [ `expr length $uptimeCurentOre` \> `expr length $uptimeRecordOre` ]; then | ||
+ | # echo Nou record - Uptime curent mai mare cu cateva ore decat uptime-ul record 1 | ||
+ | uptime > $output | ||
+ | date >> $output | ||
+ | else | ||
+ | if [ `expr length $uptimeCurentOre` == `expr length $uptimeRecordOre` ]; then | ||
+ | uptimeCurentOra=`echo $uptimeCurentOre | cut -d":" -f1` | ||
+ | uptimeRecordOra=`echo $uptimeRecordOre | cut -d":" -f1` | ||
+ | if [ $uptimeCurentOra -gt $uptimeRecordOra ]; then | ||
+ | # echo Nou record - Uptime curent mai mare cu cateva ore decat uptime-ul record 2 | ||
+ | uptime > $output | ||
+ | date >> $output | ||
+ | fi | ||
+ | fi | ||
+ | fi | ||
+ | } | ||
+ | |||
+ | if [ -a $output ]; then | ||
+ | uptimeCurent=`uptime` | ||
+ | uptimeRecord=`cat $output | head -1` | ||
+ | if [ `echo $uptimeCurent | grep -c day` == '0' ]; then | ||
+ | # echo Uptime mai mic de o zi | ||
+ | if [ `echo $uptimeRecord | grep -c day` == '0' ]; then | ||
+ | # echo Uptime record mai mic de o zi, comparam orele | ||
+ | compareHrs | ||
+ | # else | ||
+ | # echo Uptime record mai mare ca uptime curent | ||
+ | fi | ||
+ | else | ||
+ | # echo Uptime mai mare de o zi | ||
+ | if [ `echo $uptimeRecord | grep -c day` == '0' ]; then | ||
+ | # echo Uptime record mai mic de o zi | ||
+ | uptime > $output | ||
+ | date >> $output | ||
+ | else | ||
+ | uptimeCurentZile=`uptime | awk '{print $3}'` | ||
+ | uptimeRecordZile=`cat $output | head -1 | awk '{print $3}'` | ||
+ | if [ $uptimeCurentZile -eq $uptimeRecordZile ]; then | ||
+ | # echo Uptime in zile egal | ||
+ | compareHrs | ||
+ | else | ||
+ | if [ $uptimeCurentZile -gt $uptimeRecordZile ]; then | ||
+ | # echo Record nou | ||
+ | uptime > $output | ||
+ | date >> $output | ||
+ | fi | ||
+ | fi | ||
+ | fi | ||
+ | fi | ||
+ | else | ||
+ | # echo Fisierul nu exista, deci trebuie creat. Recordul e uptime-ul curent | ||
+ | uptime > $output | ||
+ | date >> $output | ||
+ | fi | ||
+ | |||
+ | exit 0 | ||
+ | |||
+ | </code> | ||
+ | |||
+ | === Stergere directoare vechi de pe o partiţie pentru salvarea spaţiului === | ||
+ | |||
+ | Scriptul următor poate fi plasat în cron şi rulat cam din oră în oră pentru a şterge directoare vechi. Un exemplu clasic este ştergerea jpeg-urilor generate de cameră de supraveghere conectată la un server Linux: | ||
+ | |||
+ | <code bash>#!/bin/bash | ||
+ | |||
+ | # Copyright (C) 2005-2007 Silvian Cretu <silvian86@yahoo.com> | ||
+ | # | ||
+ | # This program is free software; you can redistribute it and/or | ||
+ | # modify it under the terms of the GNU General Public License | ||
+ | # as published by the Free Software Foundation; either version 2 | ||
+ | # of the License, or (at your option) any later version. | ||
+ | # | ||
+ | # This program is distributed in the hope that it will be useful, | ||
+ | # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
+ | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
+ | # GNU General Public License for more details. | ||
+ | # | ||
+ | # You should have received a copy of the GNU General Public License | ||
+ | # along with this program; if not, write to the Free Software | ||
+ | # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. | ||
+ | |||
+ | # Constante: | ||
+ | partitie=/var/www # partitia monitorizata | ||
+ | procentMaxim="97%" # procentul maxim de ocupare acceptat pt partitia monitorizata | ||
+ | X=1 # se vor sterge directoarele mai vechi de X zile | ||
+ | director=/var/www/html/camera/events/2 # directorul din care se vor sterge subdirectoarele | ||
+ | |||
+ | # Cat de ocupata este partitia monitorizata (in procente): | ||
+ | procentOcupare=$(df -h | grep $partitie | awk '{print $5}') | ||
+ | |||
+ | if [[ "$procentMaxim" < "$procentOcupare" ]] || [ "$procentOcupare" == "100%" ]; | ||
+ | then # trebuie sterse directoarele mai vechi de X zile | ||
+ | find $director -type d -mtime +$X -exec rm -rf {} \; | ||
+ | fi | ||
+ | exit | ||
+ | </code> | ||
[[Category:Collection]] | [[Category:Collection]] | ||
[[Category:Programming]] | [[Category:Programming]] |
Latest revision as of 00:17, 31 January 2007
Contents
- 1 Exemple scripturi BASH
- 1.1 Scripturi care permit schimbarea rapida a MAC+IP
- 1.2 Script care lanseaza in fundal o anumita comanda data ca parametru de intrare
- 1.3 Script ce elimina zona asociata unui domeniu dat ca parametru de intrare
- 1.4 Cautarea unui fisier ce contine un anumit string
- 1.5 Stergerea fisierelor backup
- 1.6 Probleme cu spatiul pe disc?
- 1.7 Gasirea fisierelor duplicate intr-un director
- 1.8 Calcularea recordului de uptime
- 1.9 Stergere directoare vechi de pe o partiţie pentru salvarea spaţiului
Exemple scripturi BASH
Scripturi care permit schimbarea rapida a MAC+IP
Raptor360 12:33, 8 June 2006 (EEST)
getmac
Primeste ca parametru un IP si returneaza MAC-ul acestuia sau "" daca nu exista in retea nodul cu pricina.
/usr/local/bin/getmac#!/bin/sh
if ! $IFDEVICE ; then
IFDEVICE="eth0";
fi
mac=`arping -I $IFDEVICE $1 -c 3 | grep reply | cut -f2 -d\[ | cut -f1 -d\] | uniq` echo $mac
be
Primeste ca parametru un IP si schimba MAC-ul si IP-ul pentru un device.
/usr/local/bin/be#!/bin/bash
if ! $IFDEVICE ; then
IFDEVICE="eth0"
fi
gip=`echo -e "$1\t"` echo -e " IP is $1." mac=`cat /etc/stored | grep "$gip" | cut -f2` echo -e "MAC is $mac." if $mac != "" ; then
ifconfig $IFDEVICE down ifconfig $IFDEVICE hw ether $mac ifconfig $IFDEVICE $1 netmask 255.255.248.0 broadcast 10.10.17.255 route add default gw 10.10.17.1 # echo "nameserver 10.10.17.1" > /etc/resolv.conf
else
echo "$1 has not an associated MAC."
fi
switchuser
Schimba MAC-ul si IP-ul aleator conform unuia stocat in /etc/stored folosind scripturile anterioare.
/usr/local/bin/switchuser#!/bin/bash
notfound=1 while $notfound -eq 1 ; do
rip=`echo "$RANDOM % 252 + 3" | bc` for i in `seq $rip 254`; do randip="10.10.17.$i" gip=`echo -e "$randip\t"` if grep "$gip" | cut -f2` != "" ; then if `getmac $randip` == "" ; then be $randip exit 0 notfound=1 else echo "IP $randip is already active." fi else echo "$randip has no MAC associated." fi done
done
Scripturile folosesc fisierul de configurare /etc/stored in care se adauga perechi de forma: IP\tMAC, e.g. 10.10.17.241 00:20:ED:95:2A:A1
10.10.17.242 4C:00:10:53:BF:A5
precum si variabila din enviroment IFDEVICE daca este definita. e.g. daca vrem sa schimbam ip-ul doar pentru device-ul eth1 atunci apelam la:
# IFDEVICE=eth1 switchuser
Script care lanseaza in fundal o anumita comanda data ca parametru de intrare
Puteti lasa o comanda sa se execute in fundal fara ca ea sa fie intrerupta la iesirea dumneavoastra din sistem folosind urmatorul script pe care l-am numit silent. (output-ul nu este salvat, pentru aceasta puteti folosi nohup)
#!/bin/bash
echo "Executing \"$*\"" setsid bash -c $* 2>>/dev/null 1>>/dev/null < /dev/null &
Scriptul il puteti folosi de exemplu:
$ silent wget -c -t 0 www.bigfiles.com/ubuntu.iso
Script ce elimina zona asociata unui domeniu dat ca parametru de intrare
Puteţi elimina porţiunea din named.conf de la zone "nume.domeniu.dat.ca.parametru.de.intrare" { până la acolada închisă asociată acoladei deschise de mai sus.
Scriptul este:#!/bin/bash
- Bind zone remove script
- Copyright (C) 2005 Silvian Cretu <silvian86@yahoo.com>
- This program is free software; you can redistribute it and/or
- modify it under the terms of the GNU General Public License
- as published by the Free Software Foundation; either version 2
- of the License, or (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
if [ ! $# = 1 ]; then
echo "Usage: $0 domain"; echo "The path to named.conf is defined inside the script"; else
pathToNamedDotConf=/etc/named.conf
x=$(grep -n "zone \"$1\" {" $pathToNamedDotConf | cut -f1 -d:) sed $x,/\}\;/d $pathToNamedDotConf > temp c=$(sed -n $x'p' < temp) if [ "x`echo $c | grep "zone"`" = "x" ] then sed $x' d' temp > $pathToNamedDotConf else cat temp > $pathToNamedDotConf fi rm -f temp exit fi
Cautarea unui fisier ce contine un anumit string
find /path -name "*" -exec grep -H "<string>" '{}' \;
sau
grep -Hr "<string>" /path/
Fireste, <string> poate fi atat un sir de caractere cat si orice fel de expresie regulata suportata de versiunea particulara de grep disponibila pe masina in cauza.
Deasemenea, pentru a cauta fara a face diferenta intre majuscule si minuscule, adaugati parametrul -i la grep.
Daca doriti ca in output-ul comenzii grep expresia cautata sa fie cautata sa fie evidentiata puteti folosi parametrul --color astfel:
grep --color -Hr "<string>" /path/
Stergerea fisierelor backup
Asa cum stiti, prin traditie in *NIX, editoarele text fac o copie de siguranta fisierelor editate, copie de siguranta ce este denumita identic cu fisierul initial plus caracterul tilda (~). Ei bine... in cazul aplicatiilor web, acest backup mai mult dauneaza decat sa ajute. Nu ar fi prea placut sa aveti un index.php~ in DocumentRoot
find /path -name "*~" | xargs -n 20 rm -f
Probleme cu spatiul pe disc?
Nu stiti unde "vi s-a dus" spatiul de pe disc si e cam greu sa verificati fiecare director in parte?
Linia urmatoare va ajuta, facand totodata si o sortare.
du --max-depth=1 /path | sort -rn
Gasirea fisierelor duplicate intr-un director
Aveti prea multe mp3-uri si majoritatea sunt duplicate dar cu alt nume sau orice de genul folositi scriptul de mai jos:D Eventual adaugati si un -maxdepth 1 sa nu fie recursiv.
- !/bin/sh
if [ ! -d "$1" ]; then
echo "Usage $0 <dir>" exit 1
fi find "$1" -type f -print0 | xargs -0 -n1 md5sum | sort --key=1,32 | uniq -w 32 -d --all-repeated=prepend \
|cut -f3- -d' '|sed 's/^$/Fisiere identice:/'
Calcularea recordului de uptime
Scriptul urmator va trebui plasat in crontab astfel incat sa ruleze periodic, de exemplu, din ora in ora. El va afisa in fisierul $output (initial /var/log/uptimeRecord.log) output-ul comenzilor uptime si date (adica uptime-ul record si data la care a fost inregistrat).
#!/bin/bash
- Copyright (C) 2006 Silvian Cretu <silvian86@yahoo.com>
- This program is free software; you can redistribute it and/or
- modify it under the terms of the GNU General Public License
- as published by the Free Software Foundation; either version 2
- of the License, or (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
output='/var/log/uptimeRecord.log'
function compareHrs {
uptimeCurent=`uptime` if [ `echo $uptimeCurent | grep -c day` == '0' ]; then
- echo Uptime mai mic de o zi
uptimeCurentOre=`uptime | awk '{print $3}'` uptimeRecordOre=`cat $output | head -1 | awk '{print $3}'` else uptimeCurentOre=`uptime | awk '{print $5}'` uptimeRecordOre=`cat $output | head -1 | awk '{print $5}'` fi if [ `expr length $uptimeCurentOre` \> `expr length $uptimeRecordOre` ]; then
- echo Nou record - Uptime curent mai mare cu cateva ore decat uptime-ul record 1
uptime > $output date >> $output else if [ `expr length $uptimeCurentOre` == `expr length $uptimeRecordOre` ]; then uptimeCurentOra=`echo $uptimeCurentOre | cut -d":" -f1` uptimeRecordOra=`echo $uptimeRecordOre | cut -d":" -f1` if [ $uptimeCurentOra -gt $uptimeRecordOra ]; then
- echo Nou record - Uptime curent mai mare cu cateva ore decat uptime-ul record 2
uptime > $output date >> $output fi fi fi
}
if [ -a $output ]; then
uptimeCurent=`uptime` uptimeRecord=`cat $output | head -1` if [ `echo $uptimeCurent | grep -c day` == '0' ]; then
- echo Uptime mai mic de o zi
if [ `echo $uptimeRecord | grep -c day` == '0' ]; then
- echo Uptime record mai mic de o zi, comparam orele
compareHrs
- else
- echo Uptime record mai mare ca uptime curent
fi else
- echo Uptime mai mare de o zi
if [ `echo $uptimeRecord | grep -c day` == '0' ]; then
- echo Uptime record mai mic de o zi
uptime > $output date >> $output else uptimeCurentZile=`uptime | awk '{print $3}'` uptimeRecordZile=`cat $output | head -1 | awk '{print $3}'` if [ $uptimeCurentZile -eq $uptimeRecordZile ]; then
- echo Uptime in zile egal
compareHrs else if [ $uptimeCurentZile -gt $uptimeRecordZile ]; then
- echo Record nou
uptime > $output date >> $output fi fi fi fi
else
- echo Fisierul nu exista, deci trebuie creat. Recordul e uptime-ul curent
uptime > $output date >> $output
fi
exit 0
Stergere directoare vechi de pe o partiţie pentru salvarea spaţiului
Scriptul următor poate fi plasat în cron şi rulat cam din oră în oră pentru a şterge directoare vechi. Un exemplu clasic este ştergerea jpeg-urilor generate de cameră de supraveghere conectată la un server Linux:
#!/bin/bash
- Copyright (C) 2005-2007 Silvian Cretu <silvian86@yahoo.com>
- This program is free software; you can redistribute it and/or
- modify it under the terms of the GNU General Public License
- as published by the Free Software Foundation; either version 2
- of the License, or (at your option) any later version.
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
- You should have received a copy of the GNU General Public License
- along with this program; if not, write to the Free Software
- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
- Constante:
partitie=/var/www # partitia monitorizata procentMaxim="97%" # procentul maxim de ocupare acceptat pt partitia monitorizata X=1 # se vor sterge directoarele mai vechi de X zile director=/var/www/html/camera/events/2 # directorul din care se vor sterge subdirectoarele
- Cat de ocupata este partitia monitorizata (in procente):
procentOcupare=$(df -h | grep $partitie | awk '{print $5}')
if [[ "$procentMaxim" < "$procentOcupare" ]] || [ "$procentOcupare" == "100%" ]; then # trebuie sterse directoarele mai vechi de X zile find $director -type d -mtime +$X -exec rm -rf {} \; fi
exit