0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

CIDR表記で書かれたIPをネットワークアドレスに変更するpythonプログラム

Last updated at Posted at 2021-12-09
import ipaddress
import os
current_dir = os.getcwd()
read_file_name = '/NWアドレスに変更前.txt' 
output_file_name = '/NWアドレスに変更後.txt'

read_file = current_dir + read_file_name
output_file = current_dir + output_file_name

before_ip_list = []
after_ip_list = []
with open(read_file, mode='r') as f:
    before_ip_list = f.readlines()

for ip in before_ip_list:
    ip = ipaddress.ip_interface(ip.replace('\n', ''))
    after_ip_list.append(ip.network)


with open(output_file, mode='w') as f:
    for ip in after_ip_list:
        f.write(str(ip))
        f.write('\n')

##使い方
本pythonプログラムと同じフォルダに以下2つのファイルを作成し、プログラムを実行
NWアドレスに変更前.txtとNWアドレスに変更後.txt

##使用例

NWアドレスに変更前
192.168.0.155/24
192.168.0.155/25
192.168.0.155/26
192.168.0.155/27
192.168.0.155/28
192.168.0.155/29
NWアドレスに変更後.txt
192.168.0.0/24
192.168.0.128/25
192.168.0.128/26
192.168.0.128/27
192.168.0.144/28
192.168.0.152/29
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?