windows_dnat_mapping_with_python

#coding: utf-8
import os
import re

def execute_cmd(cmd):
    out = os.popen(cmd)
    return out.read()

def dnat_list():
    cmd = 'netsh interface portproxy show all'
    mapping = execute_cmd(cmd)
    dnat_rules = []
    for rule in mapping.split('
'):
        if '0.0.0.0' in rule:
            print(rule)
            dnat_rules.append(re.split(r'[ ]+', rule))
    return dnat_rules

def dnat_create(listen, connect_to):
    print('adding rule: {} -> {}'.format(listen, connect_to))
    listenaddress, listenport = listen.split(':')
    connectaddress, connectport = connect_to.split(':')
    if not listenaddress:
        listenaddress = '0.0.0.0'
    cmd = 'netsh interface portproxy add v4tov4 listenaddress={} listenport={} connectaddress={} connectport={}'.format(listenaddress, listenport, connectaddress, connectport)
    print('execute: {}'.format(cmd))
    execute_cmd(cmd)
    return dnat_list()

def dnat_delete(listen):
    print('del rule: {}'.format(listen))
    listenaddress, listenport = listen.split(':')
    if not listenaddress:
        listenaddress = '0.0.0.0'
    cmd = 'netsh interface portproxy delete v4tov4 listenaddress={} listenport={}'.format(listenaddress, listenport)
    print('execute: {}'.format(cmd))
    execute_cmd(cmd)
    return dnat_list()

if __name__ == "__main__":
    print (dnat_list())
    print dnat_create(':8080', '1.2.3.4:80')
    print dnat_delete(':8080')

原文地址:https://www.cnblogs.com/sixloop/p/windows_dnat_mapping_with_python.html