2013-05-02 24 views
1

我們的網絡團隊使用InfoBlox來存儲有關IP範圍(位置,國家等)的信息。 有一個API可用,但Infoblox的文檔和示例不太實用。Infoblox WAPI:如何搜索IP

我想通過API搜索有關IP的詳細信息。首先 - 我很樂意從服務器上取回任何東西。我修改the only example I found

import requests 
import json 

url = "https://10.6.75.98/wapi/v1.0/" 
object_type = "network"  
search_string = {'network':'10.233.84.0/22'} 

response = requests.get(url + object_type, verify=False, 
    data=json.dumps(search_string), auth=('adminname', 'adminpass')) 

print "status code: ", response.status_code 
print response.text 

它返回一個錯誤400

status code: 400 
{ "Error": "AdmConProtoError: Invalid input: '{\"network\": \"10.233.84.0/22\"}'", 
    "code": "Client.Ibap.Proto", 
    "text": "Invalid input: '{\"network\": \"10.233.84.0/22\"}'" 
} 

我希望從別人誰設法得到這個API的Python工作的指針。


UPDATE:在解決方案的後續行動,下面是一段代碼(它的工作原理,但它是不是很好,流線型的,不完全的錯誤,等檢查),如果有人一天之罰都是有需要像我一樣做。

def ip2site(myip): # argument is an IP we want to know the localization of (in extensible_attributes) 
    baseurl = "https://the_infoblox_address/wapi/v1.0/" 

    # first we get the network this IP is in 
    r = requests.get(baseurl+"ipv4address?ip_address="+myip, auth=('youruser', 'yourpassword'), verify=False) 
    j = simplejson.loads(r.content) 
    # if the IP is not in any network an error message is dumped, including among others a key 'code' 
    if 'code' not in j: 
     mynetwork = j[0]['network'] 
     # now we get the extended atributes for that network 
     r = requests.get(baseurl+"network?network="+mynetwork+"&_return_fields=extensible_attributes", auth=('youruser', 'youpassword'), verify=False) 
     j = simplejson.loads(r.content) 
     location = j[0]['extensible_attributes']['Location'] 
     ipdict[myip] = location 
     return location 
    else: 
     return "ERROR_IP_NOT_MAPPED_TO_SITE" 

回答

3

通過使用requests.get和json.dumps,你是不是發送GET請求,而JSON添加到查詢字符串?從本質上講,做一個

GET https://10.6.75.98/wapi/v1.0/network?{\"network\": \"10.233.84.0/22\"} 

我一直在使用的Perl,而不是Python的的WebAPI,但如果這是你的代碼試圖做事情的方式,它可能會無法很好地工作。要JSON發送到服務器,做一個POST,並添加一個「_method」的說法與「GET」作爲值:

POST https://10.6.75.98/wapi/v1.0/network 

Content: { 
    "_method": "GET", 
    "network": "10.233.84.0/22" 
} 

Content-Type: application/json 

或者不JSON發送到服務器併發送

GET https://10.6.75.98/wapi/v1.0/network?network=10.233.84.0/22 

我猜你會通過從代碼中刪除json.dumps並直接將search_string傳遞給requests.get來實現。

+0

確實,刪除'json.dumps()'會讓'requests'處理查詢編碼。 – 2013-05-14 17:45:17

+0

非常感謝 - 直接的方式(沒有JSON)很好。 – WoJ 2013-05-15 15:02:08