1

我们的网络团队使用InfoBlox来存储有关 IP 范围(位置、国家等)的信息。有一个可用的 API,但 Infoblox 的文档和示例不是很实用。

我想通过 API 搜索有关 IP 的详细信息。首先-我很乐意从服务器上取回任何东西。我修改了我找到的唯一示例

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 一起工作,我将不胜感激。


更新:跟进解决方案,下面是一段代码(它可以工作,但它不是很好,简化,不能完美检查错误等)如果有一天有人需要像我一样做.

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"
4

1 回答 1

3

通过使用requests.get和json.dumps,你不是在将JSON添加到查询字符串时发送GET请求吗?本质上,做一个

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

我一直在将 WebAPI 与 Perl 一起使用,而不是 Python,但如果这是您的代码尝试做事的方式,它可能不会很好地工作。要将 JSON 发送到服务器,请执行 POST 并添加以 'GET' 作为值的 '_method' 参数:

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 来实现。

于 2013-05-14T10:50:45.983 回答