Functions¶
Cuanto más grandes sean nuestros scripts, más caóticos se volverán. Si usamos las mismas rutinas varias veces en el script, el tamaño del script aumentará en consecuencia.
Método 1 - Funciones¶
function name {
<commands>
}
Método 2 - Funciones¶
name() {
<commands>
}
Podemos elegir el método para definir una función que nos resulte más cómodo. En nuestro script CIDR.sh, utilizamos el primer método porque es más fácil de leer con la palabra clave "función".
<SNIP>
# Identify Network range for the specified IP address(es)
function network_range {
for ip in $ipaddr
do
netrange=$(whois $ip | grep "NetRange\|CIDR" | tee -a CIDR.txt)
cidr=$(whois $ip | grep "CIDR" | awk '{print $2}')
cidr_ips=$(prips $cidr)
echo -e "\nNetRange for $ip:"
echo -e "$netrange"
done
}
<SNIP>
La función se llama únicamente llamando al nombre especificado de la función, como hemos visto en la declaración del caso.
Paso de parámetros¶
Estas funciones deben diseñarse de forma que puedan utilizarse con una estructura fija de valores o al menos sólo con un formato fijo.
#!/bin/bash
function print_pars {
echo $1 $2 $3
}
one="First parameter"
two="Second parameter"
three="Third parameter"
print_pars "$one" "$two" "$three"
Valores de retorno¶
Cuando iniciamos un nuevo proceso, cada proceso hijo (por ejemplo, una función en el script ejecutado) devuelve un código de retorno al proceso padre (shell bash a través del cual ejecutamos el script) al finalizarlo, informándole del estado de la ejecución.
| Return Code | Description |
|---|---|
1 |
Errores generales |
2 |
Mal uso de las funciones integradas del shell |
126 |
El comando invocado no se puede ejecutar |
127 |
Command not found |
128 |
Argumento no válido para salir |
128+n |
Señal de error fatal "n" |
130 |
Script terminated by Control-C |
255\* |
Estado de salida fuera de rango |
#!/bin/bash
function given_args {
if [ $# -lt 1 ]
then
echo -e "Number of arguments: $#"
return 1
else
echo -e "Number of arguments: $#"
return 0
fi
}
# No arguments given
given_args
echo -e "Function status code: $?\n"
# One argument given
given_args "argument"
echo -e "Function status code: $?\n"
# Pass the results of the funtion into a variable
content=$(given_args "argument")
echo -e "Content of the variable: \n\t$content"
Debugging¶
Bash nos brinda una excelente oportunidad para encontrar, rastrear y corregir errores en nuestro código. El término depuración puede tener muchos significados diferentes. Sin embargo, la [[https://tldp.org/LDP/Bash-Beginners-Guide/html/sect_02_03.html | depuración de Bash]] es el proceso de eliminar errores (bugs) de nuestro código. La depuración se puede realizar de muchas formas diferentes. Por ejemplo, podemos usar nuestro código para depurar y verificar errores tipográficos, o podemos usarlo para analizar el código para rastrearlos y determinar por qué ocurren errores específicos.
1i8n@htb[/htb]$ bash -x CIDR.sh
+ '[' 0 -eq 0 ']'
+ echo -e 'You need to specify the target domain.\n'
You need to specify the target domain.
+ echo -e Usage:
Usage:
+ echo -e '\tCIDR.sh <domain>'
CIDR.sh <domain>
+ exit 1
1i8n@htb[/htb]$ bash -x -v CIDR.sh
#!/bin/bash
# Check for given argument
if [ $# -eq 0 ]
then
echo -e "You need to specify the target domain.\n"
echo -e "Usage:"
echo -e "\t$0 <domain>"
exit 1
else
domain=$1
fi
+ '[' 0 -eq 0 ']'
+ echo -e 'You need to specify the target domain.\n'
You need to specify the target domain.
+ echo -e Usage:
Usage:
+ echo -e '\tCIDR.sh <domain>'
CIDR.sh <domain>
+ exit 1
CIDR.sh¶
#!/bin/bash
# Check for given arguments
if [ $# -eq 0 ]
then
echo -e "You need to specify the target domain.\n"
echo -e "Usage:"
echo -e "\t$0 <domain>"
exit 1
else
domain=$1
fi
# Identify Network range for the specified IP address(es)
function network_range {
for ip in $ipaddr
do
netrange=$(whois $ip | grep "NetRange\|CIDR" | tee -a CIDR.txt)
cidr=$(whois $ip | grep "CIDR" | awk '{print $2}')
cidr_ips=$(prips $cidr)
echo -e "\nNetRange for $ip:"
echo -e "$netrange"
done
}
# Ping discovered IP address(es)
function ping_host {
hosts_up=0
hosts_total=0
echo -e "\nPinging host(s):"
for host in $cidr_ips
do
stat=1
while [ $stat -eq 1 ]
do
ping -c 2 $host > /dev/null 2>&1
if [ $? -eq 0 ]
then
echo "$host is up."
((stat--))
((hosts_up++))
((hosts_total++))
else
echo "$host is down."
((stat--))
((hosts_total++))
fi
done
done
echo -e "\n$hosts_up out of $hosts_total hosts are up."
}
# Identify IP address of the specified domain
hosts=$(host $domain | grep "has address" | cut -d" " -f4 | tee discovered_hosts.txt)
echo -e "Discovered IP address:\n$hosts\n"
ipaddr=$(host $domain | grep "has address" | cut -d" " -f4 | tr "\n" " ")
# Available options
echo -e "Additional options available:"
echo -e "\t1) Identify the corresponding network range of target domain."
echo -e "\t2) Ping discovered hosts."
echo -e "\t3) All checks."
echo -e "\t*) Exit.\n"
read -p "Select your option: " opt
case $opt in
"1") network_range ;;
"2") ping_host ;;
"3") network_range && ping_host ;;
"*") exit 0 ;;
esac
![[Pasted image 20250104143722.png]]