Cisco Support Community
cancel
Showing results for 
Search instead for 
Did you mean: 
Announcements

Welcome to Cisco Support Community. We would love to have your feedback.

For an introduction to the new site, click here. And see here for current known issues.

New Member

Multi Network Object POST

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
Cisco Employee

Hamoud,

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

17 REPLIES
Cisco Employee

Hamoud,

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

New Member

Dear Neipatel,

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

New Member

Hello,

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])

Cisco Employee

Hamoud,

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

New Member

Is there a way to post the

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.

Cisco Employee

It should be posted as a data

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

New Member

Thanks that's better.

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 ?

Cisco Employee

It looks like you are using

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.

New Member

Hey Neil, long time. ;) Hey

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?

New Member

I have one, I used CSV

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.

New Member

Yea, that would be great. Ty.

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()
New Member

Attached. Trying to do a

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()



					
				
			
			
				
			
			
				
New Member

[items.txt]

[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!

New Member

Can someone tell me why

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" }
Looks like you are missing description item
New Member

Nope, originally I thought it

Nope, originally I thought it was the 1.1.1.1/24 so I fixed it to be 1.1.1.0/24 but still will not use it.

New Member

Is not your request data

Is not your request data should look like this?

{ "name": "Test6", "type": "Network", "value": "1.1.1.0/24", "description": "Test Description" }

instead of

{ "name": "test6", "value": "1.1.1.1/24", "type": "Network" }
New Member

/usr/lib/python2.7/dist

/usr/lib/python2.7/dist-packages/urllib3/connectionpool.py:794: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html
InsecureRequestWarning)
{ "name": "Test6", "type": "Network", "value": "1.1.1.0/24", "description": "Test Description" }

Status code is: 422

Nope still doesn't like it. I get this every time.

404
Views
10
Helpful
17
Replies