[英]Python compare two lists of IPs and return the lowest to 0 IP entry in list?
我設法編譯了兩個IP地址列表。 這樣使用和未使用的ip
unused_ips = ['172.16.100.0/32', '172.16.100.1/32', '172.16.100.2/32', '172.16.100.3/32', '172.16.100.4/32', '172.16.100.5/32', '172.16.100.6/32', '172.16.100.7/32', '172.16.100.8/32', '172.16.100.9/32'...]
used_ips = ['172.16.100.1/32','172.16.100.33/32']
我現在想做的是比較這些列表並返回下一個免費IP。 在上面的示例中,下一個IP將是172.16.100.2/32,直到將所有這些從1分發到32,然后再分發34。
我不確定從哪里開始,如果有內置的東西可以將它們轉換為IPv4Network對象,但是我在文檔中找不到任何內容
謝謝
我將保留一set
ipaddress
對象,並操縱它們來分配和取消分配地址,如下所示:
import ipaddress
def massage_ip_lists():
global unused_ips, used_ips
unused_ips = set(ipaddress.ip_address(ip.replace('/32', ''))
for ip in unused_ips)
used_ips = set(ipaddress.ip_address(ip.replace('/32', ''))
for ip in used_ips)
def allocate_next_ip():
new_ip = min(unused_ips - used_ips)
used_ips.add(new_ip)
return new_ip
unused_ips = [
'172.16.100.0/32',
'172.16.100.1/32',
'172.16.100.2/32',
'172.16.100.3/32',
'172.16.100.4/32',
'172.16.100.5/32',
'172.16.100.6/32',
'172.16.100.7/32',
'172.16.100.8/32',
'172.16.100.9/32']
used_ips = ['172.16.100.1/32', '172.16.100.33/32']
massage_ip_lists()
print(allocate_next_ip())
print(allocate_next_ip())
注意:
/32
是IP網絡的名稱,而不是IP主機的名稱。 ipaddress
對象具有可比性,因此像min()
這樣的函數都可以在它們上面工作。 172.16.100.0
是完全有效的IP地址,具體取決於網絡掩碼。 如果您不想分配它,請將其保留在unused_ips
,或者使程序知道正在使用的網絡掩碼。 您想要未使用但未使用的ip:
available_ips = [ip for ip in unused_ips if ip not in used_ips]
您想對它們進行排序以獲得最接近零的那個。 如果您有字符串,則無法進行幼稚排序; 例如,將172.16.xxx.xxx排序為高於172.100.xxx.xxx。 您可以將IP轉換為數字列表,以對它們進行正確排序。
import re
available_ips = sorted(available_ips, key=lambda ip: (int(n) for n in re.split(r'[./]', ip)))
如果您只是嘗試遍歷可用ip列表,則可以執行以下操作:
# Filter unavailable ips from the list of all ips
available_ips = set(unused_ips) - set(used_ips)
# Iterate through list of available ips
for ip in available_ips:
print(ip) # Or whatever you want to do with the next available ip
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.