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