Python 2.7:AIX系统ifconfig十六进制子网掩码转点分十进制
解决AIX系统中带0x前缀的十六进制子网掩码转点分十进制问题
针对你在Python 2.7环境下处理AIX系统ifconfig返回的十六进制子网掩码时遇到的转换错误,这里有两种基于标准库的实用解决方案:
方法1:修正字符串分割思路
核心是先移除0x前缀,再按每两位分割转换,完美适配你最初的思路:
def hex_mask_to_dotted(hex_mask): # 移除前缀,只保留纯十六进制部分 clean_hex = hex_mask.replace('0x', '') # 校验掩码长度是否为标准32位(8位十六进制字符) if len(clean_hex) != 8: raise ValueError("Invalid 32-bit subnet mask format") # 每两位分割为一个字节,转十进制后用点连接 return '.'.join(str(int(clean_hex[i:i+2], 16)) for i in range(0, 8, 2)) # 测试示例 print(hex_mask_to_dotted('0xffffc000')) # 输出:255.255.192.0 print(hex_mask_to_dotted('0xfffff800')) # 输出:255.255.248.0
方法2:利用socket库简化转换
借助socket.inet_ntoa和struct.pack可以跳过手动分割字符串的步骤,代码更简洁高效:
import struct import socket def hex_mask_to_dotted(hex_mask): # 将带0x的十六进制字符串直接转成32位整数 mask_integer = int(hex_mask, 16) # 把整数打包成大端字节流,再转成点分十进制格式 return socket.inet_ntoa(struct.pack('!I', mask_integer)) # 测试示例 print(hex_mask_to_dotted('0xff000000')) # 输出:255.0.0.0 print(hex_mask_to_dotted('0xfffffe00')) # 输出:255.255.254.0
集成到你的原有代码中
把转换方法和你获取ifconfig结果的逻辑结合,就能直接得到带点分十进制掩码的完整网络配置:
import subprocess import re import struct import socket def hex_mask_to_dotted(hex_mask): mask_integer = int(hex_mask, 16) return socket.inet_ntoa(struct.pack('!I', mask_integer)) # 获取ifconfig输出 ifconfig_output = subprocess.check_output(['/usr/sbin/ifconfig', '-a']).decode() # 匹配IP、掩码、广播地址 raw_result = re.findall(r'[\s]+inet ([\d\.]+) netmask ([\w.]+) broadcast ([\d\.]+)', ifconfig_output, re.S | re.M) # 转换掩码并整理结果 formatted_result = [] for ip, hex_mask, broadcast in raw_result: dotted_mask = hex_mask_to_dotted(hex_mask) formatted_result.append((ip, dotted_mask, broadcast)) print(formatted_result) # 输出示例: # [('172.17.14.50', '255.255.248.0', '172.17.15.255'), ('172.16.156.50', '255.255.192.0', '172.16.191.255'), ...]
错误原因说明
你之前的代码报错是因为直接分割带0x前缀的字符串时,第一个分割段是0x,而int()函数在base16模式下不识别这个前缀(需要纯十六进制字符),移除前缀后就能正常转换了。
内容的提问来源于stack exchange,提问作者user11183733
相关产品推荐
相关产品推荐

