cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
36414
Views
30
Helpful
32
Replies

Multi Network Object POST

hamoudud1
Level 1
Level 1

Dear Support,

am trying to use API to push a bulk of configuration to Firepower 6.1 or 6.2 but without success, i tried to POST multi Network Object as shown below :

under network i POST the below configuration:

 

https://xxx.xxx.xxx.xxx/api/fmc_config/v1/domain/e233abec-e0f2-11e3-2321-6d9ed49b625f/object/networks

  Body:

-----------------------

{
"name":"testing",
"type":"Network",
"description": "testing",
"value": "2.2.90.0/24"
},

{
"name":"testing2",
"type":"Network",
"description": "testing2",
"value": "2.2.91.0/24"
}

----------------

it return with Syntax errors.

can you please provide me with right way to POST multi network Object or any kind of configuration through REST API.

BR,

Hamoud Hamdan 

1 Accepted Solution

Accepted Solutions

Hamoud,

An high level pseudo code example would be as follows: 

JSON of the Network Objects:

networks = [{name: objecta,

  value: 10.0.0.0/24,

  type: Network},

{name: objectb,

  value: 20.0.0.0/24,

  type: Network},

{name: objectc,

  value: 30.0.0.0/24,

  type: Network}]

Code to iterate and make posts:

for object in networks:

*post object to fmc

this way the loop will go through each object and post them one at a time.

-Neil

View solution in original post

32 Replies 32

neipatel
Cisco Employee
Cisco Employee

Hamoud,

Multi import will not be possible until the next release. Currently if you want to create multiple objects you need to make individual calls with a single object in each JSON payload.

The best way to do multiple objects, today,  would be to build a large JSON file with all your objects and script iteration over the entire file and make individual calls object in the JSON.

If you haven't already spend some time in the API explorer @ https://<<FMC IP>>/api/api-explorer it is a great place to see the calls you can make as well as gather example scripts/JSON for all the calls.

-Neil

Dear Neipatel,

Thank you for your assist.

Can you share with me small example or more information about building large JSON file with all your objects and script iteration over the entire file and make individual calls object in the JSON. 

BR,

Hamoud Hamdan

Hello,

COuld you post your sample for one POST network ?

After that, I think the idea is to adapt something like this :

for i in file["...""..."]:
 yourPostMethod(i[name];i[value])

Hamoud,

An high level pseudo code example would be as follows: 

JSON of the Network Objects:

networks = [{name: objecta,

  value: 10.0.0.0/24,

  type: Network},

{name: objectb,

  value: 20.0.0.0/24,

  type: Network},

{name: objectc,

  value: 30.0.0.0/24,

  type: Network}]

Code to iterate and make posts:

for object in networks:

*post object to fmc

this way the loop will go through each object and post them one at a time.

-Neil

Is there a way to post the body argument in request :

url = "https://%s/api/fmc_platform/v1/auth/generatetoken" % ipaddr

results=[]

headers = {
'cache-control': "no-cache",
'postman-token': "ff30c506-4739-9d4d-2e53-0dc7efc2036a"
}

response = requests.request("POST", url, headers=headers, auth=(user1,pass1), verify=False)

# Authenicates token used in addiotnal HTTPS CRUD request
auth = response.headers['X-auth-access-token']

body= {
"name":"TEST",
"type":"Network",
"description": "TEST",
"value": "1.2.3.4"
}

headers = {
'x-auth-access-token': auth,
'cache-control': "no-cache",
'postman-token': "ff30c506-4739-9d4d-2e53-0dc7efc2036a"
}

url = "https://%s/api/fmc_config/v1/domain/e276abec-e0f2-11e3-8169-6d9ed49b625f/object/hosts" % ipaddr

querystring = {"limit":"1000"}


print(headers['x-auth-access-token'])


response = requests.request("POST", url, headers=headers, auth=(user1,pass1), body=body, verify=False)

My single network add doens't work.

It should be posted as a data field. I have attached an example function.

Thanks that's better.

I didn't find the way to load in json format correctly this file :

My code :

#Retrieve JSON file passed in execution argument
try:
inputNetworkObjFile = open(sys.argv[1], "rb")
readedFile = inputNetworkObjFile.read()
i = 1


#Troubleshoot test printing readed input file : OK
print(readedFile)



# if logFile :
# for netObj in readedFile
# networkPOST(headers,uuid,server,netObj)
# logFile.write("Network Obj : %d",i)
# i++

# logFile.write("NAME : %s",netObj[0])
# logFile.write("VALUE : %s",netObj[1])
# logFile.write("TYPE : %s",netObj[2])
# logFile.write("DESCRIPTION : %s",netObj[2])

# if inputNetworkObjFile: inputNetworkObjFile.close()
# else

My output :

b'networkObjects = \r\n[\r\n\t{"name": "network_A",\r\n\t"value": "10.0.0.0/8",\
r\n\t"type": "Network",\r\n\t"description":"objecta"},\r\n\r\n\t{"name": "networ
k_B",\r\n\t"value": "172.16.0.0/12",\r\n\t"type": "Network",\r\n\t"description":
"objecta"},\r\n\t\r\n\t{"name": "network_C",\r\n\t"value": "192.168.0/16",\r\n\t
"type": "Network",\r\n\t"description":"objecta"}\r\n]'

I also try to get this way for my code :

#Retrieve JSON file passed in execution argument
try:
inputNetworkObjFile = open(sys.argv[1], "rb")
readedFile = inputNetworkObjFile.read()

datas = json.dumps(readedFile)
i = 1


#Troubleshoot test printing readed input file : OK
print(readedFile)

then mak a call to the datas variable in the for loop but always this kind of error :

File "test3.py", line 102
for netObj in readedFile
                                    ^
SyntaxError: invalid syntax

Do you have an example parsing JSON file code ?

It looks like you are using some sort of log file write and populating it with tabs/new lines to create your JSON. It is much easier and recommended to used the built in Python JSON handling libraries to ensure there are not formatting errors in it.

https://docs.python.org/2/library/json.html

This way when you read the json back again it will be index-able as it should like a dictionary.

Hey Neil, long time. ;) Hey is the bulk post working in 6.2.1 of FPM? Is there a script anyone has lying around for this?

I have one, I used CSV containing host objects as input and used the loop to post each row (Object) to FMC API, but could not make more than 120 requests per minute, which is currently registered as enhancement bug. Let me know if this is something you are looking for.

Yea, that would be great. Ty. Can someone tell me why having the data in a file called items that looks like this doesn't work? I keep getting 422 errors:
[items.txt]
{ "name": "test6", "value": "1.1.1.1/24", "type": "Network" }
Post operation inside of my python script.
post_data = open("items.txt","r")
for line in post_data:
        print line
        try:
                # REST call with SSL verification turned off:
                r = requests.post(url, data=json.dumps(line), headers=headers, verify=False)
                # REST call with SSL verification turned on:
                #r = requests.post(url, data=json.dumps(post_data), headers=headers, verify='/path/to/ssl_certificate')
                status_code = r.status_code
                resp = r.text
                print("Status code is: "+str(status_code))
                if status_code == 201 or status_code == 202:
                        print ("Post was successful...")
                        json_resp = json.loads(resp)
                        print(json.dumps(json_resp,sort_keys=True,indent=4, separators=(',', ': ')))
                else :
                        r.raise_for_status()
                        print ("Error occurred in POST --> "+resp)
        except requests.exceptions.HTTPError as err:
                        print ("Error in connection --> "+str(err))
        finally:
                        if r: r.close()

Attached. Trying to do a similar script for network group, have been challenging because of my little python knowledge. 

Let me know if this one works for you, I tested it first, which I would recommend. 

# to run from terminal, type <Python test.py sample.csv>
# use at your own risk
#sample.csv
#name,type,value,description
#test,Host,10.20.19.235,test

import json
import requests
import csv
import sys
server = "https://FMC IP"
username = "Fill here"
password = "Fill Here"

r = None
headers = {'Content-Type': 'application/json'}
api_auth_path = "/api/fmc_platform/v1/auth/generatetoken"
auth_url = server + api_auth_path
try:
# 2 ways of making a REST call are provided:
# One with "SSL verification turned off" and the other with "SSL verification turned on".
# The one with "SSL verification turned off" is commented out. If you like to use that then
# uncomment the line where verify=False and comment the line with =verify='/path/to/ssl_certificate'
# REST call with SSL verification turned off:
r = requests.post(auth_url, headers=headers, auth=requests.auth.HTTPBasicAuth(username, password), verify=False)
# REST call with SSL verification turned on: Download SSL certificates from your FMC first and provide its path for verification.
# r = requests.post(auth_url, headers=headers, auth=requests.auth.HTTPBasicAuth(username,password), verify='/path/to/ssl_certificate')
auth_headers = r.headers
auth_token = auth_headers.get('X-auth-access-token', default=None)
if auth_token == None:
print("auth_token not found. Exiting...")
sys.exit()
except Exception as err:
print ("Error in generating auth token --> " + str(err))
sys.exit()
headers['X-auth-access-token'] = auth_token
api_path = "/api/fmc_config/v1/domain/e276abec-e0f2-11e3-8169-6d9ed49b625f/object/hosts" # param
url = server + api_path
if (url[-1] == '/'):
url = url[:-1]

# POST OPERATION
# Function to convert a csv file to a list of dictionaries. Takes in one variable called "variables_file"
def csv_dict_list(variables_file):
# Open variable-based csv, iterate over the rows and map values to a list of dictionaries containing key/value pairs
reader = csv.DictReader(open(variables_file, 'rb'))
dict_list = []
for line in reader:
dict_list.append(line)
return dict_list

# Calls the csv_dict_list function, passing the named csv
object_dict = csv_dict_list(sys.argv[1])
for post_data in object_dict:
try:
# REST call with SSL verification turned off:
r = requests.post(url, data=json.dumps(post_data), headers=headers, verify=False)
# REST call with SSL verification turned on:
# r = requests.post(url, data=json.dumps(post_data), headers=headers, verify='/path/to/ssl_certificate')
status_code = r.status_code
resp = r.text
print("Status code is: " + str(status_code))
if status_code == 201 or status_code == 202:
print ("Post was successful...")
json_resp = json.loads(resp)
print(json.dumps(json_resp, sort_keys=True, indent=4, separators=(',', ': ')))
else:
r.raise_for_status()
print ("Error occurred in POST --> " + resp)
except requests.exceptions.HTTPError as err:
print ("Error in connection --> " + str(err))
finally:
if r: r.close()



					
				
			
			
				
			
			
				
			
			
			
			
			
			
		

[items.txt]

{ "name":"Test29","value":"1.1.1.0/24","type":"Network" }
{ "name":"Test28","value":"1.1.2.0/24","type":"Network" }

with open('items.txt') as f:

for line in f:

j_content = json.loads(line)

try:
# REST call with SSL verification turned off:
r = requests.post(url, data=json.dumps(j_content), headers=headers, verify=False)
# REST call with SSL verification turned on:

This works iterating through the lines in the text file. Enjoy!

Hello.

 

I have the next issue, when I run the next commands:

python prueba.py Prueba.csv

 

File "prueba.py", line 59
reader = csv.DictReader(open(variables_file, 'rb'))
^
IndentationError: expected an indented block

 

***************************************************************

This is the code of python, the file "prueba.csv" contains the next:

 

prueba.CSV

name type value description
test Network 6.6.6.0/24 test

 

prueba.py

# to run from terminal, type <Python test.py sample.csv>
# use at your own risk
#sample.csv
#name,type,value,description
#test,Host,10.20.19.235,test

import csv
import sys
import json
import requests
import time

server = "https://192.168.90.181"

# Modify the username as required
username = "admin"
if len(sys.argv) > 1:
username = sys.argv[1]

#Modify the password as required
password = "securesoft"
if len(sys.argv) > 2:
password = sys.argv[2]

r = None
headers = {'Content-Type': 'application/json'}

#Create the URL
api_auth_path = "/api/fmc_platform/v1/auth/generatetoken"
auth_url = server + api_auth_path
try:
# Download SSL certificates from your FMC first and provide its path for verification.
r = requests.post(auth_url, headers=headers, auth=requests.auth.HTTPBasicAuth(username,password), verify=False)
auth_headers = r.headers
auth_token = auth_headers.get('X-auth-access-token', default=None)
if auth_token == None:
print("auth_token not found. Exiting...")
print(auth_headers)
sys.exit()
except Exception as err:
print ("Error in generating auth token --> "+str(err))
sys.exit()

headers['X-auth-access-token'] = auth_token

api_path = "/api/fmc_config/v1/domain/e276abec-e0f2-11e3-8169-6d9ed49b625f/object/networks" # param
url = server + api_path
if (url[-1] == '/'):
url = url[:-1]

# POST OPERATION
# Function to convert a csv file to a list of dictionaries. Takes in one variable called "variables_file"
def csv_dict_list(variables_file):

# Open variable-based csv, iterate over the rows and map values to a list of dictionaries containing key/value pairs
#print ("Prueba2 --> ")
#sys.exit()

reader = csv.DictReader(open(variables_file, 'rb'))
dict_list = []
for line in reader:
dict_list.append(line)
return dict_list

#print ("Prueba3 --> ")
#sys.exit()

# Calls the csv_dict_list function, passing the named csv
object_dict = csv_dict_list(sys.argv[1])
#pprint.pprint(object_dict)

for post_data in object_dict:
try:
# REST call with SSL verification turned off:
r = requests.post(url, data=json.dumps(post_data), headers=headers, verify=False)
# REST call with SSL verification turned on:
# r = requests.post(url, data=json.dumps(post_data), headers=headers, verify='/path/to/ssl_certificate')
status_code = r.status_code
resp = r.text
print("Status code is: " + str(status_code))
if status_code == 201 or status_code == 202:
print ("Post was successful...")
json_resp = json.loads(resp)
print(json.dumps(json_resp, sort_keys=True, indent=4, separators=(',', ': ')))
else:
r.raise_for_status()
print ("Error occurred in POST --> " + resp)
except requests.exceptions.HTTPError as err:
print ("Error in connection --> " + str(err))
finally:
if r: r.close()

 

Review Cisco Networking for a $25 gift card