Created
March 24, 2018 03:03
-
-
Save kevinjqiu/7a03223746dcd4a9fd78087ac0c840fe to your computer and use it in GitHub Desktop.
This file contains 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
#! /bin/env python3 | |
import sys | |
import subprocess | |
import re | |
''' | |
default route looks like the following: | |
default via 192.168.200.1 dev enp0s20f0u3u4u2 proto dhcp src 192.168.200.54 metric 209 | |
default via 192.168.1.1 dev wlp1s0 src 192.168.1.125 metric 302 | |
''' | |
DEFAULT_ROUTE_EXTRACTOR = re.compile(r'^default via [\d.]+ dev ([\w\d]+).+src ([\d./]+)') | |
''' | |
ip address line looks like the following: | |
inet 192.168.1.125/24 brd 192.168.1.255 scope global wlp1s0 | |
''' | |
IPADDR_EXTRACTOR = re.compile(r'^\s+inet ([\d./]+)') | |
def get_default_route(): | |
routes = subprocess.check_output("ip route list", shell=True).decode('utf8') | |
routes = routes.splitlines() | |
for route in routes: | |
match = DEFAULT_ROUTE_EXTRACTOR.search(route) | |
if match: | |
return (match[1], match[2]) | |
return None | |
def get_unused_ipaddr(interface, ipaddr): | |
output = subprocess.check_output( | |
'ip addr show {} scope global | grep inet | grep -v {} || true'.format(interface, ipaddr), | |
shell=True).decode('utf8') | |
match = IPADDR_EXTRACTOR.search(output) | |
if not match: | |
return None | |
return match[1] | |
if __name__ == '__main__': | |
interface, ipaddr = get_default_route() | |
unused_ipaddr = get_unused_ipaddr(interface, ipaddr) | |
if not unused_ipaddr: | |
print('Nothing to do') | |
sys.exit(0) | |
command = 'ip addr del {} dev {}'.format(unused_ipaddr, interface) | |
print(command) | |
print(subprocess.check_output('sudo {}'.format(command), shell=True)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment