ip_change.py
import os
import re
#pythonファイルが置かれているフォルダの絶対パスを取得
current_path = os.getcwd()
#読み込むCIDR表記のIPアドレスがかかれたファイル名を指定
ip_read = '/IP.txt'
ip_write = '/サブネットマスク表記に変更後.txt'
path_w = current_path + ip_write
path_r = current_path + ip_read
mask = {"/8": "255.0.0.0",
"/9": "255.128.0.0",
"/10": "255.192.0.0",
"/11": "255.224.0.0",
"/12": "255.240.0.0",
"/13": "255.248.0.0",
"/14": "255.252.0.0",
"/15": "255.254.0.0",
"/16": "255.255.0.0",
"/17": "255.255.128.0",
"/18": "255.255.192.0",
"/19": "255.255.224.0",
"/20": "255.255.240.0",
"/21": "255.255.248.0",
"/22": "255.255.252.0",
"/23": "255.255.254.0",
"/24": "255 255 255 0",
"/25": "255 255 255 128",
"/26": "255 255 255 192",
"/27": "255.255.255.224",
"/28": "255.255.255.240",
"/29": "255.255.255.248",
"/30": "255.255.255.252",
"/31": "255.255.255.254",
"/32": "255.255.255.255"}
ip_changed_list = []
with open(path_r, mode='r') as f:
iplist = f.readlines()
for ip in iplist:
# [/][0-9]+
cidr = re.search('[/][0-9]+', ip)
# mask[cidr.group()] ⇦にてサブネットマスクを取得
ip_changed = ip.replace(cidr.group(), ' ').replace('\n', '')
ip_changed += mask[cidr.group()]
ip_changed_list.append(ip_changed)
with open(path_w, mode='w') as f:
for d in ip_changed_list:
f.write("%s\n" % d)
#使用方法
pythonプログラムとIP.txtを同じフォルダにして下記コマンドを実行
python3 ip_change.py
#OUTPUT
IP.txt
192.168.0.133/24
192.168.0.134/25
192.168.0.135/26
192.168.0.135/26
192.168.0.135/24
192.168.0.135/26
192.168.0.135/26
192.168.0.135/30
192.168.0.135/31
192.168.0.135/32
サブネットマスク表記に変更後.txt
192.168.0.133 255 255 255 0
192.168.0.134 255 255 255 128
192.168.0.135 255 255 255 192
192.168.0.135 255 255 255 192
192.168.0.135 255 255 255 0
192.168.0.135 255 255 255 192
192.168.0.135 255 255 255 192
192.168.0.135 255.255.255.252
192.168.0.135 255.255.255.254
192.168.0.135 255.255.255.255