sábado, 7 de marzo de 2015

Asterisk peer status check

#!/bin/bash
 PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
export DISPLAY=:0.0


declare -a  trunks=('callcentric' 'didlogic' 'perment' 'nick1');

for i in ${trunks[@]}; do


peer_status=$(asterisk -x " sip show peer ${i} " | grep -i status | cut -d' ' -f11 )




if [ "$peer_status" != "OK" ]; then


echo  ${i}  $peer_status


else

echo  ${i}  $peer_status


fi

done
exit 0

Asterisk Registry Monitor

#!/bin/bash
 PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
export DISPLAY=:0.0

declare -a  trunks=('17772651651' 'SMD829235398' '0282091985' '17772709540');

for i in ${trunks[@]}; do


   reg_status=`asterisk -x " sip show registry" | grep -i ${i} |  awk '{print $5}'`




 if [ "${reg_status}" != "Registered" ]; then


alert=`echo "Server  ${i} is not registered since $(date)" | mail -s "red alert for server ${i}  not registered" ambiorixg12@gmail.com `

echo ${i}  is   ${reg_status} $(date) >> /root/noreg.log
else


echo ${i}  is   ${reg_status} $(date) >> /root/reg.log

alert=`echo "Server  ${i} is registered since $(date)" | mail -s "green alert  for server  ${i} registered " ambiorixg12@gmail.com  `

fi
 

done
exit 0





Lineas cronjob
El primer cron corre el scrip cada 3 minutes el segundo borra el log diario 5 minutos despues de  la  media noche


*/3 * * * * /root/monitor.sh
5 0 * * * /bin/echo >  /root/reg.log
 



viernes, 6 de marzo de 2015

Ejemplos de todo tipo de array


#! /bin/bash
declare -A trunks
trunks=([1]=abc [2]=cd [3]=der)

echo ${trunks[3]}

###index array





Unix[0]='Debian'
Unix[1]='Red hat'
Unix[2]='Ubuntu'
Unix[3]='Suse'

echo ${Unix[1]}


####

declare -a  Linux=('Ubuntu' 'Mandriva' 'Centos' 'Linux Mint' 'Debian');


echo ${Linux[4]}

#####


##Print the Whole Bash Array  Linux and Unix array

echo ${Linux[@]}
echo ${Unix[@]}



The Ultimate Bash Array Tutorial with 15 Examples

An array is a variable containing multiple values may be of same type or of different type.  There is no maximum limit to the size of an array, nor any requirement that member variables be indexed or assigned contiguously. Array index starts with zero.
In this article, let us review 15 various array operations in bash.

This article is part of the on-going Bash Tutorial series. For those who are new to bash scripting, get a jump-start from the Bash Scripting Introduction tutorial.

1. Declaring an Array and Assigning values

In bash, array is created automatically when a variable is used in the format like,
name[index]=value
  • name is any name for an array
  • index could be any number or expression that must evaluate to a number greater than or equal to zero.You can declare an explicit array using declare -a arrayname.
$ cat arraymanip.sh
#! /bin/bash
Unix[0]='Debian'
Unix[1]='Red hat'
Unix[2]='Ubuntu'
Unix[3]='Suse'

echo ${Unix[1]}

$./arraymanip.sh
Red hat
To access an element from an array use curly brackets like ${name[index]}.

2. Initializing an array during declaration

Instead of initializing an each element of an array separately, you can declare and initialize an array by specifying the list of elements (separated by white space) with in a curly braces.
Syntax:
declare -a arrayname=(element1 element2 element3)
If the elements has the white space character, enclose it with in a quotes.
#! /bin/bash
$cat arraymanip.sh
declare -a Unix=('Debian' 'Red hat' 'Red hat' 'Suse' 'Fedora');
declare -a declares an array and all the elements in the parentheses are the elements of an array.

3. Print the Whole Bash Array

There are different ways to print the whole elements of the array. If the index number is @ or *, all members of an array are referenced. You can traverse through the array elements and print it, using looping statements in bash.
echo ${Unix[@]}

# Add the above echo statement into the arraymanip.sh
#./t.sh
Debian Red hat Ubuntu Suse
Referring to the content of a member variable of an array without providing an index number is the same as referring to the content of the first element, the one referenced with index number zero.

4. Length of the Bash Array

We can get the length of an array using the special parameter called $#.
${#arrayname[@]} gives you the length of the array.
$ cat arraymanip.sh
declare -a Unix=('Debian' 'Red hat' 'Suse' 'Fedora');
echo ${#Unix[@]} #Number of elements in the array
echo ${#Unix}  #Number of characters in the first element of the array.i.e Debian
$./arraymanip.sh
4
6

5. Length of the nth Element in an Array

${#arrayname[n]} should give the length of the nth element in an array.
$cat arraymanip.sh
#! /bin/bash

Unix[0]='Debian'
Unix[1]='Red hat'
Unix[2]='Ubuntu'
Unix[3]='Suse'

echo ${#Unix[3]} # length of the element located at index 3 i.e Suse

$./arraymanip.sh
4

6. Extraction by offset and length for an array

The following example shows the way to extract 2 elements starting from the position 3 from an array called Unix.
$cat arraymanip.sh
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
echo ${Unix[@]:3:2}

$./arraymanip.sh
Suse Fedora
The above example returns the elements in the 3rd index and fourth index. Index always starts with zero.

7. Extraction with offset and length, for a particular element of an array

To extract only first four elements from an array element . For example, Ubuntu which is located at the second index of an array, you can use offset and length for a particular element of an array.
$cat arraymanip.sh
#! /bin/bash

Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
echo ${Unix[2]:0:4}

./arraymanip.sh
Ubun
The above example extracts the first four characters from the 2nd indexed element of an array.

8. Search and Replace in an array elements

The following example, searches for Ubuntu in an array elements, and replace the same with the word ‘SCO Unix’.
$cat arraymanip.sh
#!/bin/bash
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');

echo ${Unix[@]/Ubuntu/SCO Unix}

$./arraymanip.sh
Debian Red hat SCO Unix Suse Fedora UTS OpenLinux
In this example, it replaces the element in the 2nd index ‘Ubuntu’ with ‘SCO Unix’. But this example will not permanently replace the array content.

9. Add an element to an existing Bash Array

The following example shows the way to add an element to the existing array.
$cat arraymanip.sh
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
Unix=("${Unix[@]}" "AIX" "HP-UX")
echo ${Unix[7]}

$./arraymanip.sh
AIX
In the array called Unix, the elements ‘AIX’ and ‘HP-UX’ are added in 7th and 8th index respectively.

10. Remove an Element from an Array

unset is used to remove an element from an array.unset will have the same effect as assigning null to an element.
$cat arraymanip.sh
#!/bin/bash
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');

unset Unix[3]
echo ${Unix[3]}
The above script will just print null which is the value available in the 3rd index. The following example shows one of the way to remove an element completely from an array.
$ cat arraymanip.sh
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
pos=3
Unix=(${Unix[@]:0:$pos} ${Unix[@]:$(($pos + 1))})
echo ${Unix[@]}

$./arraymanip.sh
Debian Red hat Ubuntu Fedora UTS OpenLinux
In this example, ${Unix[@]:0:$pos} will give you 3 elements starting from 0th index i.e 0,1,2 and ${Unix[@]:4} will give the elements from 4th index to the last index. And merge both the above output. This is one of the workaround to remove an element from an array.

11. Remove Bash Array Elements using Patterns

In the search condition you can give the patterns, and stores the remaining element to an another array as shown below.
$ cat arraymanip.sh
#!/bin/bash
declare -a Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora');
declare -a patter=( ${Unix[@]/Red*/} )
echo ${patter[@]}

$ ./arraymanip.sh
Debian Ubuntu Suse Fedora
The above example removes the elements which has the patter Red*.

12. Copying an Array

Expand the array elements and store that into a new array as shown below.
#!/bin/bash
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
Linux=("${Unix[@]}")
echo ${Linux[@]}

$ ./arraymanip.sh
Debian Red hat Ubuntu Fedora UTS OpenLinux

13. Concatenation of two Bash Arrays

Expand the elements of the two arrays and assign it to the new array.
$cat arraymanip.sh
#!/bin/bash
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
Shell=('bash' 'csh' 'jsh' 'rsh' 'ksh' 'rc' 'tcsh');

UnixShell=("${Unix[@]}" "${Shell[@]}")
echo ${UnixShell[@]}
echo ${#UnixShell[@]}

$ ./arraymanip.sh
Debian Red hat Ubuntu Suse Fedora UTS OpenLinux bash csh jsh rsh ksh rc tcsh
14
It prints the array which has the elements of the both the array ‘Unix’ and ‘Shell’, and number of elements of the new array is 14.

14. Deleting an Entire Array

unset is used to delete an entire array.
$cat arraymanip.sh
#!/bin/bash
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
Shell=('bash' 'csh' 'jsh' 'rsh' 'ksh' 'rc' 'tcsh');

UnixShell=("${Unix[@]}" "${Shell[@]}")
unset UnixShell
echo ${#UnixShell[@]}

$ ./arraymanip.sh
0
After unset an array, its length would be zero as shown above.

15. Load Content of a File into an Array

You can load the content of the file line by line into an array.
#Example file
$ cat logfile
Welcome
to
thegeekstuff
Linux
Unix

$ cat loadcontent.sh
#!/bin/bash
filecontent=( `cat "logfile" `)

for t in "${filecontent[@]}"
do
echo $t
done
echo "Read file content!"

$ ./loadcontent.sh
Welcome
to
thegeekstuff
Linux
Unix
Read file content!

Bash Associative Arrays

The bash man page has long had the following bug listed: "It's too big and too slow" (at the very bottom of the man page). If you agree with that, then you probably won't want to read about the "new" associative arrays that were added in version 4.0 of bash. On the other hand, if you've ever used any modern Office Suite and seen code-bloat at its finest and just think the bash folks are exaggerating a bit, then read on.
There's nothing too surprising about associative arrays in bash, they are as you probably expect:
declare -A aa
aa[hello]=world
aa[ab]=cd
The -A option declares aa to be an associative array. Assignments are then made by putting the "key" inside the square brackets rather than an array index. You can also assign multiple items at once:
declare -A aa
aa=([hello]=world [ab]=cd)
Retrieving values is also as expected:
if [[ ${aa[hello]} == world ]]; then
    echo equal
fi
bb=${aa[hello]}
You can also use keys that contain spaces or other "strange" characters:
aa["hello world"]="from bash"
Note however that there appears to be a bug when assigning more than one item to an array with a parenthesis enclosed list if any of the keys have spaces in them. For example, consider the following script:
declare -A b
b=([hello]=world ["a b"]="c d")

for i in 1 2
do
    if [[ ${b["a b"]} == "c d" ]]; then
        echo $i: equals c d
    else
        echo $i: does not equal c d
    fi
    b["a b"]="c d"
done
At the top, b["a b"] is assigned a value as part of a parenthesis enclosed list of items. Inside the loop the if statement tests to see if the item is what we expect it to be. At the bottom of the loop the same value is assigned to the same key but using a "direct" assignment. Then the loop executes one more time. One would expect that the if test would succeed both times, however it does not:
$ bash ba.sh
1: does not equal c d
2: equals c d
You can see the problem if you add the following to the end of the script to print out all the keys:
for k in "${!b[@]}"
do
    echo "$k"
done
The result you get is:
$ bash ba.sh
1: does not equal c d
2: equals c d
a\ b
a b
hello
You can see here that the first assignment, the one done via the list incorrectly adds the key as a\ b rather than simply as a b.
Before ending I want to point out another feature that I just recently discovered about bash arrays: the ability to extend them with the += operator. This is actually the thing that lead me to the man page which then allowed me to discover the associative array feature. This is not a new feature, just new to me:
aa=(hello world)
aa+=(b c d)
After the += assignment the array will now contain 5 items, the values after the += having been appended to the end of the array. This also works with associative arrays.
aa=([hello]=world)
aa+=([b]=c)           # aa now contains 2 items
Note also that the += operator also works with regular variables and appends to the end of the current value.
aa="hello"
aa+=" world"          # aa is now "hello world"
For more on using bash arrays look at the man page or check out my earlier post.

Array variables


10.2.1. Creating arrays

http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_10_02.html

An array is a variable containing multiple values. Any variable may be used as an array. There is no maximum limit to the size of an array, nor any requirement that member variables be indexed or assigned contiguously. Arrays are zero-based: the first element is indexed with the number 0.
Indirect declaration is done using the following syntax to declare a variable:
ARRAY[INDEXNR]=value
The INDEXNR is treated as an arithmetic expression that must evaluate to a positive number.
Explicit declaration of an array is done using the declare built-in:
declare -a ARRAYNAME
A declaration with an index number will also be accepted, but the index number will be ignored. Attributes to the array may be specified using the declare and readonly built-ins. Attributes apply to all variables in the array; you can't have mixed arrays.
Array variables may also be created using compound assignments in this format:
ARRAY=(value1 value2 ... valueN)
Each value is then in the form of [indexnumber=]string. The index number is optional. If it is supplied, that index is assigned to it; otherwise the index of the element assigned is the number of the last index that was assigned, plus one. This format is accepted by declare as well. If no index numbers are supplied, indexing starts at zero.
Adding missing or extra members in an array is done using the syntax:
ARRAYNAME[indexnumber]=value
Remember that the read built-in provides the -a option, which allows for reading and assigning values for member variables of an array.

10.2.2. Dereferencing the variables in an array

In order to refer to the content of an item in an array, use curly braces. This is necessary, as you can see from the following example, to bypass the shell interpretation of expansion operators. If the index number is @ or *, all members of an array are referenced.
[bob in ~] ARRAY=(one two three)

[bob in ~] echo ${ARRAY[*]}
one two three

[bob in ~] echo $ARRAY[*]
one[*]

[bob in ~] echo ${ARRAY[2]}
three

[bob in ~] ARRAY[3]=four

[bob in ~] echo ${ARRAY[*]}
one two three four
Referring to the content of a member variable of an array without providing an index number is the same as referring to the content of the first element, the one referenced with index number zero.

10.2.3. Deleting array variables

The unset built-in is used to destroy arrays or member variables of an array:
[bob in ~] unset ARRAY[1]

[bob in ~] echo ${ARRAY[*]}
one three four

[bob in ~] unset ARRAY

[bob in ~] echo ${ARRAY[*]}
<--no output-->

10.2.4. Examples of arrays

Practical examples of the usage of arrays are hard to find. You will find plenty of scripts that don't really do anything on your system but that do use arrays to calculate mathematical series, for instance. And that would be one of the more interesting examples...most scripts just show what you can do with an array in an oversimplified and theoretical way.
The reason for this dullness is that arrays are rather complex structures. You will find that most practical examples for which arrays could be used are already implemented on your system using arrays, however on a lower level, in the C programming language in which most UNIX commands are written. A good example is the Bash history built-in command. Those readers who are interested might check the built-ins directory in the Bash source tree and take a look at fc.def, which is processed when compiling the built-ins.
Another reason good examples are hard to find is that not all shells support arrays, so they break compatibility.
After long days of searching, I finally found this example operating at an Internet provider. It distributes Apache web server configuration files onto hosts in a web farm:
#!/bin/bash

if [ $(whoami) != 'root' ]; then
        echo "Must be root to run $0"
        exit 1;
fi
if [ -z $1 ]; then
        echo "Usage: $0 </path/to/httpd.conf>"
        exit 1
fi

httpd_conf_new=$1
httpd_conf_path="/usr/local/apache/conf"
login=htuser

farm_hosts=(web03 web04 web05 web06 web07)

for i in ${farm_hosts[@]}; do
        su $login -c "scp $httpd_conf_new ${i}:${httpd_conf_path}"
        su $login -c "ssh $i sudo /usr/local/apache/bin/apachectl graceful"

done
exit 0
First two tests are performed to check whether the correct user is running the script with the correct arguments. The names of the hosts that need to be configured are listed in the array farm_hosts. Then all these hosts are provided with the Apache configuration file, after which the daemon is restarted. Note the use of commands from the Secure Shell suite, encrypting the connections to remote hosts.
Thanks, Eugene and colleague, for this contribution.
Dan Richter contributed the following example. This is the problem he was confronted with:
"...In my company, we have demos on our web site, and every week someone has to test all of them. So I have a cron job that fills an array with the possible candidates, uses date +%W to find the week of the year, and does a modulo operation to find the correct index. The lucky person gets notified by e-mail."
And this was his way of solving it:
#!/bin/bash
# This is get-tester-address.sh 
#
# First, we test whether bash supports arrays.
# (Support for arrays was only added recently.)
#
whotest[0]='test' || (echo 'Failure: arrays not supported in this version of
bash.' && exit 2)
                                                                                
#
# Our list of candidates. (Feel free to add or
# remove candidates.)
#
wholist=(
     'Bob Smith <bob@example.com>'
     'Jane L. Williams <jane@example.com>'
     'Eric S. Raymond <esr@example.com>'
     'Larry Wall <wall@example.com>'
     'Linus Torvalds <linus@example.com>'
   )
#
# Count the number of possible testers.
# (Loop until we find an empty string.)
#
count=0
while [ "x${wholist[count]}" != "x" ]
do
   count=$(( $count + 1 ))
done
                                                                                
#
# Now we calculate whose turn it is.
#
week=`date '+%W'`     # The week of the year (0..53).
week=${week#0}        # Remove possible leading zero.
                                                                                
let "index = $week % $count"   # week modulo count = the lucky person

email=${wholist[index]}     # Get the lucky person's e-mail address.
                                                                                
echo $email      # Output the person's e-mail address.
This script is then used in other scripts, such as this one, which uses a here document:
email=`get-tester-address.sh`   # Find who to e-mail.
hostname=`hostname`      # This machine's name.
                                                                                
#
# Send e-mail to the right person.
#
mail $email -s '[Demo Testing]' <<EOF
The lucky tester this week is: $email
                                                                                
Reminder: the list of demos is here:
    http://web.example.com:8080/DemoSites
                                                                                
(This e-mail was generated by $0 on ${hostname}.)
EOF