Personal tools

Scripturi BASH

From linux360

Jump to: navigation, search

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

  1. Bind zone remove script
  2. Copyright (C) 2005 Silvian Cretu <silvian86@yahoo.com>
  3. This program is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU General Public License
  5. as published by the Free Software Foundation; either version 2
  6. of the License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, write to the Free Software
  13. 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.

  1. !/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

  1. Copyright (C) 2006 Silvian Cretu <silvian86@yahoo.com>
  2. This program is free software; you can redistribute it and/or
  3. modify it under the terms of the GNU General Public License
  4. as published by the Free Software Foundation; either version 2
  5. of the License, or (at your option) any later version.
  6. This program is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. GNU General Public License for more details.
  10. You should have received a copy of the GNU General Public License
  11. along with this program; if not, write to the Free Software
  12. 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
  1. 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
  1. 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
  1. 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
  1. echo Uptime mai mic de o zi
               if [ `echo $uptimeRecord | grep -c day` == '0' ]; then
  1. echo Uptime record mai mic de o zi, comparam orele
                       compareHrs
  1. else
  2. echo Uptime record mai mare ca uptime curent
               fi
       else
  1. echo Uptime mai mare de o zi
               if [ `echo $uptimeRecord | grep -c day` == '0' ]; then
  1. 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
  1. echo Uptime in zile egal
                               compareHrs
                       else
                               if [ $uptimeCurentZile -gt $uptimeRecordZile ]; then
  1. echo Record nou
                                       uptime > $output
                                       date >> $output
                               fi
                       fi
               fi
       fi

else

  1. 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

  1. Copyright (C) 2005-2007 Silvian Cretu <silvian86@yahoo.com>
  2. This program is free software; you can redistribute it and/or
  3. modify it under the terms of the GNU General Public License
  4. as published by the Free Software Foundation; either version 2
  5. of the License, or (at your option) any later version.
  6. This program is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. GNU General Public License for more details.
  10. You should have received a copy of the GNU General Public License
  11. along with this program; if not, write to the Free Software
  12. Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  1. 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

  1. 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