Infra/Cloud

[Azure] NSG 정책 문서화 - powershell, python

jykim23 2023. 2. 22. 17:28

Azure 고객사 중 인프라 현황자료를 요구합니다.

그중 하나가 방화벽 정책입니다.

 

NSG 한두 개면 수동으로 할 만 한데... 한두 개도 눈 빠질 거 같습니다.

그래서 편하게 하고자 시작했습니다.

 

구조(?)

C:\[고객명]\NSGTOEXCEL
│  jsonDownload.ps1 # json 가공 및 다운로드 
│  nsg_powershell.py # 실행 파일(jsonDownload.ps1 호출 및 json 엑셀 변환)

└─json
        json 파일이 저장될 곳

 

jsonDownload.ps1 # json 가공 및 다운로드 

# powershell 환경 설정
$env:LC_ALL='C.UTF-8'

# 모듈 설치
#Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force # 최초 1회 실행

# 로그인
Connect-AzAccount

# NSG 이름 조회
$nsgList = Get-AzResource -ResourceGroupName [리소스그룹명] -ResourceType Microsoft.Network/networkSecurityGroups

for($i=0; $i -lt $nsgList.count; $i++)
{
    $NAME = $nsgList[$i].Name
    $nsg = (Get-AzNetworkSecurityGroup -Name $NAME).SecurityRules
    $nsg | `
        Select-Object -Property Priority,Name,DestinationPortRange,Protocol,SourceAddressPrefix,DestinationAddressPrefix,Access,Description | `
        ConvertTo-Json | `
        Out-File  -FilePath "C:\[고객명]\nsgToExcel\json\$NAME.json"
}

 

nsg_powershell.py # 실행 파일(jsonDownload.ps1 호출 및 json 엑셀 변환)

# pip install openpyxl pandas

import os
import json
import pandas as pd
import datetime
import zipfile
dt_now = datetime.datetime.now()
today = str(dt_now.date())


# NSG json 다운로드
os.system(r'%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe C:\[고객명]\nsgToExcel\jsonDownload.ps1')

# json 파일 불러오기 
path_dir = 'C:/[고객명]/nsgToExcel/json/'
file_list = os.listdir(path_dir)
file_list_json = [file for file in file_list if file.endswith(".json")] # json 확장자만 추출

# 엑셀 파일 정의
writer=pd.ExcelWriter(f'C:/[고객명]/NSG_{today}.xlsx', engine='openpyxl')

for file in file_list_json:
    with open(path_dir + file, encoding='UTF16') as json_file:
        json_data = json.load(json_file)

        # 시트 초기화
        data = {
        'Priority' : [],
        'Name' : [],
        'Port' : [],
        'Protocol' : [],
        'Source' : [],
        'Destination' : [],
        'Action' : [],
        'Description' : []
        }

        # 각 룰 상세 데이터 추가
        for rule in json_data:
            # Priority
            data['Priority'].append(rule['Priority'])
            # Name
            data['Name'].append(rule['Name'])
            # Port
            if ', '.join(rule['DestinationPortRange']) == '*':
                data['Port'].append('모두')
            else:
                data['Port'].append(', '.join(rule['DestinationPortRange']))
            # Protocol
            if str(rule['Protocol']) == '*':
                data['Protocol'].append('모두')
            else:
                data['Protocol'].append(rule['Protocol'])

            # Source
            if ', '.join(rule['SourceAddressPrefix']) == '*':
                data['Source'].append('모두')
            else:
                data['Source'].append(', '.join(rule['SourceAddressPrefix']))

            # Destination
            if ', '.join(rule['DestinationAddressPrefix']) == '*':
                data['Destination'].append('모두')
            else:
                data['Destination'].append(', '.join(rule['DestinationAddressPrefix']))

            # Action
            if str(rule['Access']) == 'Allow':
                data['Action'].append('허용')
            elif str(rule['Access']) == 'Deny':
                data['Action'].append('거부')
            else:
                data['Action'].append('알고리즘 오류')

            # Description
            data['Description'].append(rule['Description'])
            
        # 시트 저장
        df = pd.DataFrame(data)
        df = df.sort_values(by='Priority') # Priority 오름차순 정렬
        df.to_excel(writer, sheet_name=file.split('.')[0], index=False)

# 엑셀 작성 완료
writer.close()

# json 파일 삭제
os.chdir('C:/[고객명]/nsgToExcel/json/')
json_backup = zipfile.ZipFile(f'json_{today}.zip', 'w')
with zipfile.ZipFile(f'json_{today}.zip', 'w') as _zip:
    for i in file_list_json:
        _zip.write(i)
        os.remove(i)
    _zip.close()

 

각 NSG는 시트로 저장됩니다.

powershell로 json 가공 및 다운로드실행시간은 NSG 개수에 비례합니다.

엑셀 변환은 몇 초..?

 

결과물

 

 

아무도 안 볼 거 알지만 그래도 질문 남겨주시면 최대한 답변드리겠습니다.