Fetching data from Switch using Bash scripting
I was introduced to bash scripting in the course Google IT Automation with Python Professional Certificate. I finished the course 2 months back but did not get a chance to try out automating tasks using bash scripting.
Today I was working on a bug and was trying to get data from the switch(Juniper EX2300) for DHCP security binding for a wired client. The goal was to connect a wired client on the switch and get the DHCP binding status.
Now the one way to get continuous output for "show dhcp-security binding" command was to hit up arrow and then enter. That's boring and hectic. And of course, you will lose the previous output
Another way is to use the refresh keyword, which will refresh the output of the command automatically after the specified time.
e.g
root@Deepika_VC1> show dhcp-security binding | refresh 5
Then I thought let's try bash scripting to automate this work. I wrote a simple bash script. It will automatically login into the switch, get me the output for the "show dhcp-security binding" with time. Shows the output on the terminal and also saves it in a file.
And next time if I want to perform the same task it will override the file with new values.
#!/bin/bash
adddate() {
while IFS= read -r line; do
printf '%s %s\n' "$(date +"%H:%M.%S") " "$line";
done
}
read -p "Overwriting log file if you hit enter..."
echo Updating every 5 seconds
echo "Time IP address MAC address Vlan Expires State Interface" > log.txt
while true;
do
echo Getting info...
curl -s http://172.16.1.6:3001/rpc/get-dhcp-security-binding -u "<username>:<password>" -H "Content-Type: application/xml" -H "Accept: text/plain" | adddate > log.txt
sleep 5
done;
Below is the document that helped me in learning REST API and RPC for JUNOS.
https://www.juniper.net/documentation/us/en/software/junos/rest-api/rest-api.pdf
Now this I can use!
That’s very useful Deepika, thanks for sharing.