Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
import subprocess
import re
def get_address_info():
s1 = subprocess.Popen(["ifconfig"], stdout=subprocess.PIPE)
out_string ="utf-8")
# address name
address_name_list = []
for line in out_string.split("\n"):
if line and line.find("flags=") > -1:
# 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 ="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)
lines[i] = "%s\t%s\n" % (new_ip, host)
print("change: %s ip is different!" % host)
change = True
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:
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
You can’t perform that action at this time.