LoginSignup
2
4

More than 5 years have passed since last update.

pythonでコンフィグ情報からネットワーク図を書くために

Last updated at Posted at 2019-01-09

Interface Descriptionがプロジェクトの財産になる日
https://www.janog.gr.jp/meeting/janog41/application/files/3615/1723/1065/janog41-sp06if-miyazaki-04.pdf

プログラミングの勉強として成果物を出したかったので
↑を作ってみたかった。

前提

 ・the初心者な内容ですがあしからず
 ・pythonの勉強として作りました
 ・コンフィグからホスト名と対向先を取るだけの内容
 ・コンフィグは事前にあるものとします
 ・もっと簡単にできる。ってのがあれば教えてほしいです。

環境

 ・Mac sierra
 ・python3.6

内容

機能としては
 コンフィグのテキストを読み込んで
 ホスト名と対向先ホスト名を抽出→リストへ格納
 リストをJSON形式で書き出す
というイメージです。

 正規表現のところはアレがそれなのでお察しください。
  色々いじってできたので変数は雑です・・・


#! python
import re,json

# 格納先を用意
node_list = []
link_list = []

#フォルダのログをすべて読み込む
for log_read in os.listdir('.'):
    if not log_read.endswith('.txt'):
        continue
    print ("コンフィグ" + log_read +"を読み込んでいます")
#1行ずつリストに格納する
    with open(log_read) as f:
        lines = f.readlines()
#端末名とDescriptionを探す
        host = [line for line in lines if "hostname" in line]
        des = [line for line in lines if "description" in line]
#正規表現化
        x = str(des)
        host = str(host)
        des_name = re.findall(r"description (正規表現)",x)
        host_name = re.findall(r"hostname (正規表現)",host)
        #ホスト名だけ弄る
        host_rename = ",".join(host_name)
        host_name2 = {"name":host_rename}
        node_list.append(host_name2)
        #対向先をリストに格納
        for DC in des_name:
            node = {"name":DC}
            link = {"source":host_name2,"target":DC}
            node_list.append(node)
            link_list.append(link)
            node = sorted(node)
            full = {"nodes":node_list,"links":link_list}

#JSONファイルへ書き出す
    with open('show-net.json', 'w') as u:
        json.dump(full,u, indent=4, separators=(',', ': '))
    f.close()
print ( "完了")

あとはJSONファイルを読み込ませてブラウザで確認するだけ。

結果

 きちんと動いていたけどDescriptionの記載の有無とパターンがバラバラで
 整理されていなかった(プログラム以前の問題)
 
 →よって、 全く線が引けてなかった・・・という残念なオチ

 でも思ったとおり動く物ができるといいですね。
 すごく勉強になりました。

参考

inet-henge で、好みのネットワーク図を描くヒント
https://codeout.hatenablog.com/entry/2018/04/02/232327

Pythonでファイルの読み込み、書き込み(作成・追記)
https://note.nkmk.me/python-file-io-open-with/

オンラインで正規表現をテスト
https://qiita.com/ken1ma/items/85d9a35e9a4f18587eeb

2
4
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
2
4