1

好的,我在这里需要一点点。我有一个 mysql 数据库,在数据库中,我有一个 ip 地址存储为 inet_aton 的表。我在表中有 ip cidr 范围。比如 192.168.0.0/24 或 /8 等。我正在使用 Python 查询数据库以查看数据库中是否有单个 /32 ip 地址。我正在尝试这样的代码:

def ip_in_networks(ip, networks):

    found_net_type = ''
    found_template = ''


    ip_as_int = unpack('!I', inet_aton(ip))[0]

    for (network, netmask, net_type, template) in networks:


        if (ip_as_int & netmask) == network:

            # we are, awesome
            found_net_type = net_type
            found_template = template
            break
def fetch_networks(r_conn):
    '''This returns a list of networks as [[network, netmask], ...]'''
    nets = []
    r_cur = r_conn.cursor()
    sql = 'SELECT n.network, n.netmask, l.lookup_value, l.template '
    sql += 'FROM network n, lookup l '
    sql += 'WHERE n.network_type_id = l.id'
    r_cur.execute(sql)
    for row in r_cur:
        nets.append([row[0], row[1], row[2], row[3]])
    return nets

if __name__ == '__main__':
 ''' some code removed'''

  "connect to the db"
  networks = fetch_networks(r_conn)
  ip = sys.argv[1]

  net_type, template = ip_in_networks(ip, networks)

  if net_type:
    '''If net_type which means found the ip address ini the db, do something, in this case 
       just log the found message''

我得到的错误是 Type Error Unpack Non 序列。

我试图坚持使用标准的 Python 2.7 库和 Mysql。

我确定我错过了一些简单的东西。如果需要,我也会完全更改我的代码。我必须有很多 IP 范围才能将它们从这个 IP 地址分解到那个 IP 地址,然后查看 IP 是否在那个范围内。

4

0 回答 0