Sometime you need a script or a program that can automatic generate a new DNA Center token to let you run your network automation API or query DNA Center.
I wrote a solution for that as Bash Script, simple and easy to understand my coding.
All agree that Bash doesn’t have as many luxuries as one can find in many programming languages such Java, C++, C# etc…
But if…else. it is our best friend. That mean I have added exception handling – Try & Catch as you see from line 18-31.
Script code:
#!/bin/bash
#DNA IP address variable
dna_ip="xx.xx.xx.xx"
#DNAC URL variable for creating of token
dna_token="https://$dna_ip/dna/system/api/v1/auth/token"
#Creating get_token function/methode to get token from Cisco DNA Center
get_token ()
{
#Variable to display HTTP response code (status code)
statuscode=$(curl -k -o /dev/null --silent --head --write-out '%{http_code}\n' "$dna_token" \
-X POST -H "Authorization: Basic YourBasicCode" )
#To generate basic auth use (curl -u username:password -i -H 'Accept:application/json' http://example.com)
#Exception handling - Try if response code equal 200
if [ "$statuscode" -eq 200 ]; then
token_url=$(curl -k "$dna_token" \
-X POST -H "Authorization: Basic YourBasicCode" )
#sed to remove first 10 characters and 2 last characters.
token=$(echo "$token_url" | sed -e 's/^.\{10\}//' -e 's/.\{2\}$//')
echo -e "\nConnetcted successfully and created token!"
echo token
#Exception handling - Catch if response code not equal 200
else
#Error message with response code
echo -e "\nToken can not be creating, please check URL and Base code\nError HTTP Status Code is: $statuscode"
exit
fi #End of exception handling
} #End of get_token function
#Call get_token function
get_token
You can use the same script in a different platform, just need a few small changes!

