Created
March 8, 2017 16:07
-
-
Save stlehmann/91d577298632059f609873cfdf9feee7 to your computer and use it in GitHub Desktop.
fast switching between network configurations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! c:\miniconda\python | |
from collections import namedtuple | |
import time | |
import sys | |
import click | |
import wmi | |
TIMEOUT_SECONDS = 20 | |
# static configuration | |
Config = namedtuple('Config', 'name dhcp ip subnetmask gateway') | |
configs = { | |
'dhcp': Config('dhcp', True, None, None, None), | |
'static': Config('static', False, '192.168.1.110', '255.255.255.0', '192.168.1.0') | |
} | |
nic_configs = wmi.WMI().Win32_NetworkAdapterConfiguration(IPEnabled=True) | |
nic = nic_configs[0] | |
def ip_address(): | |
ip = nic.wmi_property('IPAddress') | |
return ip.value[0] | |
def subnetmask(): | |
subnet = nic.wmi_property('IPSubnet') | |
return subnet.value[0] | |
def gateway(): | |
gateway = nic.wmi_property('DefaultIPGateway') | |
return gateway.value[0] | |
def dhcp_enabled(): | |
dhcp = nic.wmi_property('DHCPEnabled') | |
return dhcp.value | |
def config_active(config): | |
if config.dhcp: | |
return dhcp_enabled() | |
return (config.ip == ip_address() and | |
config.subnetmask == subnetmask() and | |
config.gateway == gateway()) | |
@click.group() | |
def cli(): | |
pass | |
@cli.command() | |
def list(): | |
""" list available network configurations """ | |
for key, config in configs.items(): | |
s = '{x.name}: {x.ip}'.format(x=config) | |
click.echo(s) | |
@cli.command() | |
def status(): | |
""" show current network status """ | |
click.echo('Status') | |
@cli.command() | |
@click.pass_context | |
def load(config): | |
print(config) | |
@click.command() | |
@click.option('--config', type=click.Choice(configs.keys())) | |
def set_nic(config): | |
config_name = config | |
config = configs[config] | |
if config.dhcp: | |
nic.EnableDHCP() | |
else: | |
nic.EnableStatic(IPAddress=[config.ip],SubnetMask=[config.subnetmask]) | |
nic.SetGateways(DefaultIPGateway=[config.gateway]) | |
t0 = time.perf_counter() | |
while not abs(time.perf_counter() - t0) > TIMEOUT_SECONDS: | |
if config_active(config): | |
click.echo('Successfully changed config to {}.'.format(config_name)) | |
break | |
time.sleep(1) | |
else: | |
click.echo('Timeout') | |
click.echo('IP: {ip}\nSubnetmask: {subnetmask}\n' | |
'Gateway: {gateway}'.format( | |
ip=ip_address(), | |
subnetmask=subnetmask(), | |
gateway=gateway() | |
)) | |
if __name__ == '__main__': | |
set_nic() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment