gpt4 book ai didi

python - 如何在 python 子列表中填写未使用的 ip 地址?

转载 作者:行者123 更新时间:2023-11-28 16:46:07 29 4
gpt4 key购买 nike

我已经创建了一个 python 脚本来尝试让我作为系统管理员的生活变得更轻松。此脚本的目的是将 Microsoft DHCP 服务器转储文件转换为排序的 CSV 文件。

我将在此处包含代码,并感谢各种改进。

我的问题

我的脚本创建了一个列表列表(每个 dhcp 预留一个)。例如:

[
# [DHCP SERVER, IP ADDRESS, MAC ADDRESS, HOSTNAME, DESCRIPTION]
[server1,172.16.0.120,31872fcefa33,wks120.domain.net,Description of client]
[server1,172.16.0.125,4791ca3d7279,wks125.domain.net,Description of client]
[server1,172.16.0.132,6035a71c930c,wks132.domain.net,Description of client]
...
]

没有列出未使用的 ip 地址。但我希望我的脚本自动为所有未使用的 IP 地址添加子列表,并给他们一个评论,说“未注册”或其他东西。

我什至不知道如何开始在谷歌上搜索如何完成这项任务,所以任何帮助将不胜感激:)

脚本

#!/usr/bin/python
import sys, shlex
from operator import itemgetter

# Function: get_dhcp_reservations
#
# Extracts a list of ip reservations from a Microsoft DHCP server dump file
# then it stores the processed reservations them in a nested list

def get_dhcp_reservations(dmpFile):

# Setup empty records list
records = []

# Open dump file for reading
dmpFile = open(dmpFile,"r")

# Iterate dump file line by line
for line in dmpFile:

# Only user lines with the word "reservedip" in it
if "reservedip" in line:

# Split the line into fields excluding quoted substrings
field = shlex.split(line)

# Create a list of only the required fields
result = [field[2][1:9], field[7], field[8], field[9], field[10]]

# Append each new record as a nested list
records.append(result)

# Return the rendered data
return records


# Function: sort_reservations_by_ip
#
# Sorts all records by the IPv4 address field

def sort_reservations_by_ip(records):

# Temporarily convert dotted IPv4 address to tuples for sorting
for record in records:
record[1] = ip2tuple(record[1])

# Sort sublists by IP address
records.sort(key=itemgetter(1))

# Convert tuples back to dotted IPv4 addresses
for record in records:
record[1] = tuple2ip(record[1])

return records


# Function: ip2tuple
#
# Split ip address into a tuple of 4 integers (for sorting)

def ip2tuple(address):
return tuple(int(part) for part in address.split('.'))


# Function: tuple2ip
#
# Converts the tuple of 4 integers back to an dotted IPv4 address

def tuple2ip(address):

result = ""

for octet in address:
result += str(octet)+"."

return result[0:-1]


# Get DHCP reservations
records = get_dhcp_reservations(sys.argv[1])

# Sort reservations by IP address
records = sort_reservations_by_ip(records)

# Print column headings
print "DHCP Server,Reserved IP,MAC Address,Hostname,Description"

# Print in specified format records
for record in records:
print record[0]+","+record[1]+",\""+record[2]+"\","+record[3]+","+record[4]

注意:我还尝试使用 python socket.inet_ntoa 对 IPv4 进行排序正如本网站其他主题中所建议的那样,但没有成功使其正常工作。

转储文件示例

根据请求,这里是一些转储文件

[Ommited content]

# ======================================================================
# Start Add ReservedIp to the Scope : 172.16.0.0, Server : server1.domain.net
# ======================================================================


Dhcp Server \\server1.domain.net Scope 172.16.0.0 Add reservedip 172.16.0.76 0800278882ae "wks126devlin.domain.net" "Viana (VM)" "BOTH"
Dhcp Server \\server1.domain.net Scope 172.16.0.0 Add reservedip 172.16.0.118 001e37322202 "WKS18.domain.net" "Kristof (linux)" "BOTH"
Dhcp Server \\server1.domain.net Scope 172.16.0.0 Add reservedip 172.16.0.132 000d607205a5 "WKS32.domain.net" "Lab PC" "BOTH"
Dhcp Server \\server1.domain.net Scope 172.16.0.0 Add reservedip 172.16.0.156 338925b532ca "wks56.domain.net" "Test PC" "BOTH"
Dhcp Server \\server1.domain.net Scope 172.16.0.0 Add reservedip 172.16.0.155 001422a7d474 "WKS55.domain.net" "Liesbeth" "BOTH"
Dhcp Server \\server1.domain.net Scope 172.16.0.0 Add reservedip 172.16.0.15 0800266cfe31 "xpsystst.domain.net" "Pascal (VM)" "BOTH"

[Ommited content]

最佳答案

我首先创建了一个包含所有空预订的列表,然后用您开始时使用的非空列表覆盖它:

#!/usr/bin/env python

reservations = [
# [DHCP SERVER, IP ADDRESS, MAC ADDRESS, HOSTNAME, DESCRIPTION]
['server1','172.16.0.120','31872fcefa33','wks120.domain.net','Description of client'],
['server1','172.16.0.125','4791ca3d7279','wks125.domain.net','Description of client'],
['server1','172.16.0.132','6035a71c930c','wks132.domain.net','Description of client'],
]

def reservationlist(reservations, serverpattern, addresspattern, hostpattern,
start, end):
result = []
for i in range(start, end + 1):
result.append([
serverpattern % i,
addresspattern % i,
'[no mac]',
hostpattern % i,
'Unregistered'])

for reservation in reservations:
index = int(reservation[1].split('.')[3]) - start
result[index] = reservation

return result

print reservationlist(
reservations,
'server%d',
'172.16.0.%d',
'wks%d.domain.net',
120,
132)

最终结果如下:

[['server1', '172.16.0.120', '31872fcefa33', 'wks120.domain.net', 'Description of client'],
['server121', '172.16.0.121', '[no mac]', 'wks121.domain.net', 'Unregistered'],
['server122', '172.16.0.122', '[no mac]', 'wks122.domain.net', 'Unregistered'],
['server123', '172.16.0.123', '[no mac]', 'wks123.domain.net', 'Unregistered'],
['server124', '172.16.0.124', '[no mac]', 'wks124.domain.net', 'Unregistered'],
['server1', '172.16.0.125', '4791ca3d7279', 'wks125.domain.net', 'Description of client'],
['server126', '172.16.0.126', '[no mac]', 'wks126.domain.net', 'Unregistered'],
['server127', '172.16.0.127', '[no mac]', 'wks127.domain.net', 'Unregistered'],
['server128', '172.16.0.128', '[no mac]', 'wks128.domain.net', 'Unregistered'],
['server129', '172.16.0.129', '[no mac]', 'wks129.domain.net', 'Unregistered'],
['server130', '172.16.0.130', '[no mac]', 'wks130.domain.net', 'Unregistered'],
['server131', '172.16.0.131', '[no mac]', 'wks131.domain.net', 'Unregistered'],
['server1', '172.16.0.132', '6035a71c930c', 'wks132.domain.net', 'Description of client']]

呸!我情不自禁。此版本接受 IP 地址作为开始值和结束值:

#!/usr/bin/env python

reservations = [
# [DHCP SERVER, IP ADDRESS, MAC ADDRESS, HOSTNAME, DESCRIPTION]
['server1','172.16.0.120','31872fcefa33','wks120.domain.net','Description of client'],
['server1','172.16.0.125','4791ca3d7279','wks125.domain.net','Description of client'],
['server1','172.16.0.132','6035a71c930c','wks132.domain.net','Description of client'],
]

def addr_to_int(address):
"""Convert an IP address to a 32-bit int"""
a, b, c, d = map(int, address.split('.'))
return a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d

def int_to_addr(value):
"""Convert a 32-bit int into a tuple of its IPv4 byte values"""
return value >> 24, value >> 16 & 255, value >> 8 & 255, value & 255

def reservationlist(reservations, serverpattern, addresspattern, hostpattern,
start, end):

reservationdict = dict((addr_to_int(item[1]), item)
for item in reservations)
startint = addr_to_int(start)
endint = addr_to_int(end)
for i in range(startint, endint + 1):
try:
item = reservationdict[i]
except KeyError:
addressbytes = int_to_addr(i)
item = [
serverpattern.format(*addressbytes),
addresspattern.format(*addressbytes),
'[no mac]',
hostpattern.format(*addressbytes),
'Unregistered']
yield item

for entry in reservationlist(
reservations,
'server{3}',
'172.16.{2}.{3}',
'wks{3}.domain.net',
'172.16.0.120',
'172.16.1.132'):
print entry

此版本使用 yield 关键字将 reservationlist() 变成生成器。它不是一次将所有值保存在 RAM 中,而是每次只发出一个值,直到循环完成。对于每次通过循环,它都会尝试从您的预订列表中获取实际值(使用 dict 进行快速访问)。如果不能,它会使用 string.format 方法用 IPv4 地址字节填充字符串模板。

关于地址操作的快速说明

int_to_addr 函数采用 32 位 IP 地址,例如:

AAAAAAAABBBBBBBBCCCCCCCCDDDDDDDD

并返回 0-255 范围内的 4 个字节,例如:

AAAAAAAA, BBBBBBBB, CCCCCCCC, DDDDDDDD

在该函数中,>> 表示“将值向右旋转那么多位”,“& 255”表示“只返回最后 8 位(128 + 64 + 32 + 16 + 8 + 4 + 2 + 1)”。

因此,如果我们传入上面的“AAAA...DDDD”数字:

  • 值 >> 24 => AAAAAAAA
  • value >> 16 => AAAAAAAABBBBBBBBB。该值 & 255 => BBBBBBBB
  • value >> 8 => AAAAAAAABBBBBBBCCCCCCCC。该值 & 255 => CCCCCCCC
  • value & 255 => DDDDDDDD

这是将 32 位 IPv4 地址转换为 4 字节列表的或多或少的标准方法。当您将这些值与点连接在一起时,您将获得正常的“A.B.C.D”地址格式。

关于python - 如何在 python 子列表中填写未使用的 ip 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13589638/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com