Skip to content

Instantly share code, notes, and snippets.

@hershkoy
Created November 29, 2020 19:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hershkoy/d64de6f628880b4ef046bf991b5cf6fc to your computer and use it in GitHub Desktop.
Save hershkoy/d64de6f628880b4ef046bf991b5cf6fc to your computer and use it in GitHub Desktop.
WSL2 - Init docker
import os
import re
from ipaddress import IPv4Interface, IPv6Interface
def main():
print("Getting ip")
# WSL_NIC = getWSLInterface()
proc = os.popen("wsl /sbin/ip -o -4 addr list eth0:1")
result = proc.read()
result = result.split('\n')[1].split()
print(result)
ip = result[3].split('/')[0]
print(ip)
pattern = "^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$"
if not re.match(pattern, ip):
print("Error getting IP from wsl. Got: " + ip)
quit()
print("Got ip address: " + ip)
gateway = str((IPv4Interface(ip) ).ip)
#gateway = str((IPv4Interface(ip) + 1).ip)
print("Using gateway: " + gateway)
proc = os.popen("route print -4 | findstr 172.18.0.0")
old_route = proc.read()
if old_route != '':
print("Deleting old route " + old_route)
proc = os.popen("route delete 172.18.0.0")
print(proc.read())
print("Setting route")
#do ipconfig and check IPv4 Address of Ethernet adapter vEthernet (WSL)
#do arp -p, find this ipv4, and convert the hex number of the interface to decimal.
#if you do route print -4 you should see the save interface number in the list (but interface name might be different)
proc = os.popen("route add -p 172.18.0.0 MASK 255.255.0.0 " + gateway+" IF 44")
print(proc.read())
print("route add -p 172.18.0.0 MASK 255.255.0.0 " + gateway)
print("Assigning IP to wsl")
proc = os.popen("wsl sudo sed -i 's/^ address.*$/ address " + gateway + "/g' /etc/network/interfaces")
print(proc.read())
print("Starting docker on WSL")
proc = os.popen("wsl sudo init-docker")
print(proc.read())
print("Testing")
proc = os.popen("ping 172.18.0.1 -c 1")
print(proc.read())
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment