Created
May 13, 2020 08:13
-
-
Save Double1996/6a2178313b44c6bbdc90f0b9f881981a to your computer and use it in GitHub Desktop.
wsl
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
import subprocess | |
import re | |
# https://github.com/microsoft/WSL/issues/4210 | |
def get_address_info(): | |
s1 = subprocess.Popen(["ifconfig"], stdout=subprocess.PIPE) | |
out_string = s1.stdout.read().decode("utf-8") | |
# address name | |
address_name_list = [] | |
for line in out_string.split("\n"): | |
if line and line.find("flags=") > -1: | |
address_name_list.append(line.split(":")[0]) | |
# ip | |
re_address = re.compile(r"(?<=inet )[\d\.]{3,20}?(?= netmask)") | |
all_address = re_address.findall(out_string) | |
# | |
assert len(address_name_list) == len(all_address) | |
return {address_name_list[i]: ip for i, ip in enumerate(all_address)} | |
def get_wsl_ip() -> str: | |
add_info = get_address_info() | |
return add_info["eth0"] | |
def get_winodws_wsl_ip() -> str: | |
s2 = subprocess.Popen(["cat /etc/resolv.conf | grep 'nameserver' | cut -f 2 -d ' '"], stdout=subprocess.PIPE, shell=True) | |
# s2 = subprocess.Popen(["ipconfig.exe | grep -A 4 WSL | grep IPv4"], stdout=subprocess.PIPE, shell=True) | |
wsl_ip = s2.stdout.read().decode("utf-8") | |
return wsl_ip.strip() | |
def update_wsl_ip(new_ip: str, host: str, host_file: str): | |
""" update ip """ | |
with open(host_file, "r") as f: | |
lines = f.readlines() | |
change = False | |
found = False | |
for i, line in enumerate(lines): | |
if len(line) > 5 and line.find("%s" % host) > -1: | |
found = True | |
if line.find(new_ip) > -1: | |
print("not change: %s ip is same!" % host) | |
else: | |
lines[i] = "%s\t%s\n" % (new_ip, host) | |
print("change: %s ip is different!" % host) | |
change = True | |
break | |
if not found: | |
lines.append("%s\t%s\n" % (new_ip, host)) | |
print("change: %s ip not exists!" % host) | |
change = True | |
if lines and change: | |
with open(host_file, "w") as f: | |
f.write("".join(lines)) | |
if __name__ == "__main__": | |
windows_host_file = "/mnt/c/Windows/System32/drivers/etc/hosts" | |
linux_host_file = "/etc/hosts" | |
update_wsl_ip(new_ip=get_wsl_ip(), host="wsl.ip", host_file=windows_host_file) | |
update_wsl_ip(new_ip=get_winodws_wsl_ip(), host="wsl.ip", host_file=linux_host_file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment