Python - 在cidr范围内的ip地址的MySql查询

时间:2013-03-24 18:59:26

标签: python mysql ip-address

好的我在这里需要一点点。我有一个mysql数据库,在db中,我有一个表,其中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 sequence。

我正在努力坚持使用标准的Python 2.7库和Mysql。

我很遗憾,我很确定。如果需要,我也会完全更改我的代码。我必须将许多IP范围从这个IP地址分解为该IP地址,并查看ip是否在该范围内。

0 个答案:

没有答案
相关问题