adding object to specific device group via panorama and API

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 
Announcements

adding object to specific device group via panorama and API

L2 Linker
Add addressobject to specific device group through panorama via python

Ok, i will first start by saying ive never attempted anything like this before. Im an old school network engineer but times are a changing and im trying to learn how to automate simple tasks. All I need to do is promt the user to enter and IP address and then add that IP Address to a specific device group with 1 tag on it.  for example i want to add 7.7.7.7 to my firewall with the tag SFTP. So once the object hits the firewall the name would be H-7.7.7.7 and description would simply be the ticket number of the request and the ip would be learned via input and then I would automatically include the tag. ive been reading forums and other items and came up with a little script below.  This is what I have so far, but im kinda stuck now. Ive only been messing around with this for a couple of days... 

 

#This defines the panorama device interface to connect to and the DeviceGroup
device = ["x.x.x.x"]
devicegroup = ["mydevice"]
auth_key = "<my-key>"

 

#This intitaties the panorama connection 
pano = panorama.Panorama(device, api_key=auth_key)

 

#This defines the device group we wil be connecting to
panogrp = panorama.DeviceGroup(devicegroup)
pano.add(panogrp)

 

#This will set the IP address of the SFTP source to add to the Firewall 
ip_address = input('Please enter the ip address you wish to add to the SFTP whitelist, (example x.x.x.x): ')

 

#This will set the description of the node to the Release Ticket number
description = input("Please enter the release ticket number: ")

 

#This formats the name to match the existing standards in the firewall
name = ("H-"+ip_address)

 

#declares an object to create

sftp_server = pandevice.objects.AddressObject()
panogrp.add(sftp_server)

 

any suggestions to make it better and or complete the adding of the node..im not sure im even on the right path so far... thanks for any insight ... 🙂

 

1 accepted solution

Accepted Solutions

L5 Sessionator

You're on the right path, just a few tweaks:

 

  • Both device and devicegroup should be strings like auth_key, not lists
  • When you create the address object, you can pass in the params that you've collected from the user:
    sftp_server = pandevice.objects.AddressObject(name=name, value=ip_address, description=description)
  • Finally, once you've finished setting up your pandevice object tree, remember to invoke create() / apply() / delete() on the object to make the configuration change, depending on if you're trying to create, update, or delete:
    sftp_server.create()

View solution in original post

6 REPLIES 6

L5 Sessionator

You're on the right path, just a few tweaks:

 

  • Both device and devicegroup should be strings like auth_key, not lists
  • When you create the address object, you can pass in the params that you've collected from the user:
    sftp_server = pandevice.objects.AddressObject(name=name, value=ip_address, description=description)
  • Finally, once you've finished setting up your pandevice object tree, remember to invoke create() / apply() / delete() on the object to make the configuration change, depending on if you're trying to create, update, or delete:
    sftp_server.create()

thank you, i am still learning how this all works, but that makes sense. I apprecaite the guidance. Ill let you know my outcome once i get this going.

 

my next goal is doing the commit to panorama and the device group push.

 

Thank You again!!

How did you ever make out with this?  Do you have any running code you care to share?

I did i have a script that today will add a address object, tag it, put a ticket number as the description ( for audit purposes ) and then perform both a panorama commit and device group commit.  let me pull out any private info and i can post it....

#!/usr/bin/env python3

import pandevice
import requests
import json
import urllib3
import time
import sys
import ipaddress
import xml.etree.ElementTree as ET
from requests.exceptions import HTTPError
from pandevice import panorama
from pandevice import objects
from pandevice import policies
from pandevice.base import PanObject
from pandevice.panorama import Panorama

# This ensures you wont see an error about certificate validation for SSL
verify = False
if not verify:
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

# this defines the api calls necessary to perform Palo Alto commits
# palo alto has a two step commit process. The first step is to commit to panorama

commit_panorama_api = "https://<panorama URL>/api/?type=commit&cmd=<commit></commit>&key=<your api key>"

# the second step is to commit the specific device group, in this instance we only plan to commit to Production, so you can commit any enviornment by updating the name production with whatever device group your working wiht.
commit_production_api = "https://<panorama URL>/api/?type=commit&action=all&cmd=<commit-all><shared-policy><device-group><entry%20name=\"Production\"/></device-group></shared-policy></commit-all>&key=<your api key>"

# this defines the current list of address objects. This will be used to populate the current list of static address
# objects, so we can check the user entry to verify it will NOT be a duplicate.


# This defines the panorama device interface to connect to and the DeviceGroup
device = "x.x.x.x"
devicegroup = "Production"
auth_key = "<Your API KEY>"

# This defines how we will connect to panorama
pano = panorama.Panorama(device, api_key=auth_key)

# This defines the device group we wil be connecting to
palo_device_group = panorama.DeviceGroup(devicegroup)
pano.add(palo_device_group)

# This will set the IP address of the SFTP source to add to the Production Firewall DeviceGroup
ip_address = input('Please enter the ip address you wish to add to the SFTP whitelist, (example: x.x.x.x): ')

#this will validate the user entered a valid IPv4 address or network statement
try:
ip_addr = ipaddress.IPv4Network(ip_address)
except ValueError:
print("this address is not a valid IPv4 address: ", ip_address)
sys.exit()

# This will set the description of the node to the Release Ticket number
description = input('Please enter the release ticket number(just the numbers): ')

# this is the api call to make to get the current list of address objects:
get_address_objects_api = 'https://<panorama URL>/restapi/9.0/Objects/Addresses?location=device-group&device-group=Production&key=<yourapikey>'

try:
current_address_objects_response = requests.get(get_address_objects_api, verify=False)
# if the response was successful, no Exception will be raised
current_address_objects_response.raise_for_status()
except HTTPError as http_err:
print(f'HTTP error occurred: {http_err}')
except Exception as err:
print(f'Other error occurred: {err}')
else:
print("Please wait while your Address Object query processes!")
time.sleep(5)
address_todos_dict = json.loads(current_address_objects_response.text)

# establish the length of the dictionary to loop through
i = 0
length = len(address_todos_dict['result']['entry'])
#validate that the value i am using to key on exists in the data set, if it does execute the lookups and validation
#to see if the IP address is already in the SFTP list.
while i < length:
k = 'ip-netmask'
if k in address_todos_dict['result']['entry'][i].keys():
temp_ip = address_todos_dict['result']['entry'][i]['ip-netmask']
if temp_ip == ip_address:
print("Your address already exists in the SFTP whitelist")
i = length
sys.exit()
i += 1

# This formats the name to match the existing standards in the firewall
name = ("N-" + ip_address)
full_description = ("NETENG-" + description)

# declares an address object to create with the tag SFTP which will automatically put it in the dynamic addrss group
# for SFTP services

sftp_server = pandevice.objects.AddressObject(name=name, value=ip_address, description=full_description, tag="SFTP")
palo_device_group.add(sftp_server)
sftp_server.create()

# this next piece will commit the change to panorama
try:
panorama_commit_response = requests.get(commit_panorama_api, verify=False)
# if the response was successful, no Exception will be raised
panorama_commit_response.raise_for_status()
except HTTPError as http_err:
print(f'HTTP error occurred: {http_err}')
except Exception as err:
print(f'Other error occurred: {err}')
else:
print("Please wait while your panorama commit processes!")
time.sleep(30)
print('Your panorama commit was successful')

# this piece will do the device commit to the production device group
try:
device_commit_response = requests.get(commit_production_api, verify=False)
# if the response was successful, no Exception will be raised
device_commit_response.raise_for_status()
except HTTPError as http_err:
print(f'HTTP error occurred: {http_err}')
except Exception as err:
print(f'Other error occurred: {err}')
else:
print("Please wait while the Production Device group commits!")### i should be checking panorama for job status but i didnt know how when i write this, so i just did a sleep ####
time.sleep(60)
print('Your IP address was successfully added to the Production Firewall and the Device commit was successful')

There may be a few pieces still in that code that im not using, but since it was my first ever script i wrote, I just left a few items in there with notes what it was for... figured at some point i should get the time to go back and make it more effieienct and actually look for the commit job ID and status it before saying it is done..but again..this works for me 100% of the time to add a single object with a tag that gets sucked into a Dynamic Address group which uses that Tag. You shoul be able to add multiple tags pretty easy with this code as a starter 

  • 1 accepted solution
  • 8944 Views
  • 6 replies
  • 0 Likes
Like what you see?

Show your appreciation!

Click Like if a post is helpful to you or if you just want to show your support.

Click Accept as Solution to acknowledge that the answer to your question has been provided.

The button appears next to the replies on topics you’ve started. The member who gave the solution and all future visitors to this topic will appreciate it!

These simple actions take just seconds of your time, but go a long way in showing appreciation for community members and the LIVEcommunity as a whole!

The LIVEcommunity thanks you for your participation!