# L5. Bash Scripting. Answers
#### Excercise 1 - Hello, Bash
1. Написать скрипт, выводящий в консоль строку “Hello, Bash!”
:::info
```bash=
#!/bin/bash
echo "Hello, Bash"
```
:::
3. Написать скрипт, выводящий в новый файл “hello.txt” строку “Hello, Bash!”. Если файл существует, то добавить строку в конец файла.
:::info
```bash=
#!/bin/bash
FILE=hello.txt
echo "Hello, Bash"
if [ -f "$FILE" ]; then
echo "Hello, Bash" >> $FILE"
else
echo "Hello, Bash" > $FILE"
fi
```
:::
---
#### Excercise 2 - While
Create a bash file with the name, ‘while_example.sh’, to know the use of while loop. In the example, while loop will iterate for 5 times. The value of count variable will increment by 1 in each step. When the value of count variable will 5 then the while loop will terminate
:::info
```bash=
#!/bin/bash
valid=true
count=1
while [ $valid ]
do
echo $count
if [ $count -eq 5 ];
then
break
fi
((count++))
done
```
:::
---
#### Excercise 3 - If-else
The use of else if condition is little different in bash than other programming language. ‘elif’ is used to define else if condition in bash. Create a file named, ‘elseif_example.sh’ and add the following script to check how else if is defined in bash script.
:::info
```bash=
#!/bin/bash
echo "Enter your lucky number"
read n
if [ $n -eq 101 ];
then
echo "You got 1st prize"
elif [ $n -eq 510 ];
then
echo "You got 2nd prize"
elif [ $n -eq 999 ];
then
echo "You got 3rd prize"
else
echo "Sorry, try for the next time"
fi
```
:::
---
#### Excercise 4 - For
The basic for loop declaration is shown in the following example. Create a file named ‘for_example.sh’ and add the following script using for loop. Here, for loop will iterate for 10 times and print all values of the variable, counter in single line.
:::info
```bash=
#!/bin/bash
for (( counter=10; counter>0; counter-- ))
do
echo -n "$counter "
done
printf "\n"
```
:::
---
#### Excercise 5 - User Input
‘read’ command is used to take input from user in bash. Create a file named ‘user_input.sh’ and add the following script for taking input from the user. Here, one string value will be taken from the user and display the value by combining other string value.
:::info
```bash=
#!/bin/bash
echo "Enter Your Name"
read name
echo "Welcome $name to LinuxHint"
```
:::
---
#### Excercise 6 - Arguments
Bash script can read input from command line argument like other programming language. For example, $1 and $2 variable are used to read first and second command line arguments. Create a file named “command_line.sh” and add the following script. Two argument values read by the following script and prints the total number of arguments and the argument values as output.
:::info
```bash=
#!/bin/bash
echo "Total arguments : $#"
echo "1st Argument = $1"
echo "2nd argument = $2"
```
:::
---
#### Excercise 7 - Strings
You can easily combine string variables in bash. Create a file named “string_combine.sh” and add the following script to check how you can combine string variables in bash by placing variables together or using ‘+’ operator.
:::info
```bash=
#!/bin/bash
string1="Linux"
string2="Hint"
echo "$string1$string2"
string3=$string1+$string2
string3+=" is a good tutorial blog site"
echo $string3
```
:::
---
#### Excercise 8 - Function
Bash function can pass both numeric and string values. How you can pass a string value from the function is shown in the following example. Create a file named, ‘function_return.sh’ and add the following code. The function, greeting() returns a string value into the variable, val which prints later by combining with other string.
:::info
```bash=
#!/bin/bash
function greeting() {
str="Hello, $name"
echo $str
}
echo "Enter your name"
read name
val=$(greeting)
echo "Return value of the function is $val"
```
:::
---
#### Excercise 9 - Make dir
If you want to check the existence of directory in the current location before executing the ‘mkdir’ command then you can use the following code. ‘-d’ option is used to test a particular directory is exist or not. Create a file named, ‘directory_exist.sh’ and add the following code to create a directory by checking existence.
:::info
```bash=
#!/bin/bash
echo "Enter directory name"
read ndir
if [ -d "$ndir" ]
then
echo "Directory exist"
else
`mkdir $ndir`
echo "Directory created"
fi
```
:::
---
#### Excercise 10 - Read file
You can read any file line by line in bash by using loop. Create a file named, ‘read_file.sh’ and add the following code to read an existing file named, ‘book.txt’.
:::info
```bash=
#!/bin/bash
file='book.txt'
while read line; do
echo $line
done < $file
```
:::
---
#### Excercise 11 - Append to file
New data can be added into any existing file by using ‘>>’ operator in bash. Create a file named ‘append_file.sh’ and add the following code to add new content at the end of the file. Here, ‘Learning Laravel 5’ will be added at the of ‘book.txt’ file after executing the script.
:::info
```bash=
#!/bin/bash
echo "Before appending the file"
cat book.txt
echo "Learning Laravel 5">> book.txt
echo "After appending the file"
cat book.txt
```
:::
---
#### Excercise 12 - Test file
You can check the existence of file in bash by using ‘-e’ or ‘-f’ option. ‘-f’ option is used in the following script to test the file existence. Create a file named, ‘file_exist.sh’ and add the following code. Here, the filename will pass from the command line.
:::info
```bash=
#!/bin/bash
filename=$1
if [ -f "$filename" ]; then
echo "File exists"
else
echo "File does not exist"
fi
```
:::
---
#### Excercise 13 - Ping-Bash*
Determine the ip-addresses of available hosts on the local network using the ping utility. List the available hosts on the screen.
:::info
```bash=
#!/bin/bash
for i in 192.168.1.{1..10}
do
if ping -c1 -w1 $i &>/dev/null
then
echo $i is up;
exit
fi
done
```
:::
---
#### Excercise 14 - If*
Different types of logical conditions can be used in if statement with two or more conditions. How you can define multiple conditions in if statement using AND logic is shown in the following example. ‘&&’ is used to apply AND logic of if statement. Create a file named ‘if_with_AND.sh’ to check the following code. Here, the value of username and password variables will be taken from the user and compared with ‘admin’ and ‘secret’. If both values match then the output will be “valid user”, otherwise the output will be “invalid user”.
:::info
```bash=
!/bin/bash
echo "Enter username"
read username
echo "Enter password"
read password
if [[ ( $username == "admin" && $password == "secret" ) ]]; then
echo "valid user"
else
echo "invalid user"
fi
```
:::
---
#### Excercise 15 - Date*
You can get the current system date and time value using `date` command. Every part of date and time value can be parsed using ‘Y’, ‘m’, ‘d’, ‘H’, ‘M’ and ‘S’. Create a new file named ‘date_parse.sh’ and add the following code to separate day, month, year, hour, minute and second values.
:::info
```bash=
#!/bin/bash
Year=`date +%Y`
Month=`date +%m`
Day=`date +%d`
Hour=`date +%H`
Minute=`date +%M`
Second=`date +%S`
echo `date`
echo "Current Date is: $Day-$Month-$Year"
echo "Current Time is: $Hour:$Minute:$Second"
```
:::
---
#### Excercise 16 - Access Log*
Write a script that analyzes an arbitrary file of access to the Apache web server (access.log) and displays a list of unique ip addresses sorted by the frequency of requests to the server
>https://drive.google.com/file/d/15Y27BxADxRg21etx41oyjGwalOA0bCPg/view?usp=sharing
:::info
```bash=
cat access.log | grep -oE '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' | awk '{print $1}' | sort | uniq -c | sort -r
```
:::
---
#### Excercise 17 - Exploits*
Write a script to search for a given exploit from searchsploit and download all matches.
:::info
```bash=
#!/bin/bash
# Bash script to search for a given exploit and download all matches.
for e in $(searchsploit afd windows -w -t | grep http | cut -f 2 -d "|")
do
exp_name=$(echo $e | cut -d "/" -f 5) url=$(echo $e | sed 's/exploits/raw/')
wget -q --no-check-certificate $url -O $exp_name
done
```
:::
---
#### Excercise 18 - Nmap-parser*
Write a script to parse nmap output for open http/https ports
:::info
```bash=
#!/bin/bash
input="/mnt/e/TEMP/_trash/parse/http_open.txt"
while IFS= read -r line
do
ip=`echo $line | awk -F ' ' '{print $2}'`
echo $line | sed 's/\ /\n/g' > host.tmp
cat host.tmp | while read lln
do
ck=`echo $lln |grep "open/tcp//http"`
if [ -z "$ck" ]
then
:
else
port=`echo $lln | awk -F "/" '{print $1}'`
echo $ip":"$port >> http.lst
fi
sck=`echo $lln |grep "open/tcp//ssl|http"`
if [ -z "$sck" ]
then
:
else
port=`echo $lln | awk -F "/" '{print $1}'`
echo $ip":"$port >> http.lst
fi
done
done < "$input"
```
:::
---
#### Excercise 19 - Nmap-Bash*
Write a script to run Nmap from terminal with specific arguments to find open snmp ports in arbitary network
>-P0 -v -sU -p 161 -oA snmp_scan --max-parallelism=50
:::info
```bash=
#!/bin/bash
sudo nmap -P0 -v -sU -p 161 -oA snmp_scan --max-parallelism=50 $1
```
:::
---
#### Excercise 20 - SNMP-scan*
Write a script to check snmp open ports with default passwords (public|private) and get sysName and sysDescr from devices. The targets for scanning need to be obtained from the nmap output file (*.gnmap). Write results to output file.
>snmpwalk -v2c -c public <ip> SNMPv2-MIB::sysName.0
>snmpwalk -v2c -c public <ip> SNMPv2-MIB::sysDescr.0
:::info
```bash=
#!/bin/bash
for j in $(grep '161/open/' snmp_scan.gnmap | awk '{ print $2 }')
do
echo $j
snmpwalk -v2c -c public $j SNMPv2-MIB::sysName.0 &>> snmpwalk_${j}_public.txt
snmpwalk -v2c -c public $j SNMPv2-MIB::sysDescr.0 &>> snmpwalk_${j}_public.txt
if [ "$?" = "0" ]
then
echo "$j accepts SNMP community string public"
echo "$j accepts SNMP community string public" >> snmp_log.txt
fi
snmpwalk -v2c -c private $j SNMPv2-MIB::sysName.0 &>> snmpwalk_${j}_private.txt
snmpwalk -v2c -c private $j SNMPv2-MIB::sysDescr.0 &>> snmpwalk_${j}_private.txt
if [ "$?" = "0" ]
then
echo "$j accepts SNMP community string private"
echo "$j accepts SNMP community string private" >> snmp_log.txt
fi
done
```
:::