seaswalker / posts

0 stars 0 forks source link

Windows通过Windows虚拟机中的VPN上网 #59

Open seaswalker opened 2 years ago

seaswalker commented 2 years ago

首先虚拟机网卡设置: image 在虚拟机中VPN连好后,VPN也创建了自己的一个网卡: image 将VPN的网卡共享给Host only模式网卡: image 共享后Windows会给host only网卡分配一个新的IP,但这个IP是不对的,手动再把它改回去(和宿主机此网卡IP在一个网段内),如图: image 宿主机侧此网卡IP: image

然后就是IP路由表了,虚拟机中VPN也是通过修改路由表起作用,把虚拟机的路由表搞到宿主机来,Windows虚拟机通过命令: route print -4 获取

写了个python脚本辅助处理:

import os

routes = []

with open('ip_routes.txt', 'r', encoding="utf-8") as file:
    line = file.readline()
    while line:
        routes.append(line.rstrip('\n'))
        line = file.readline()

search_gateway = '10.8.160.1'
target_gateway = '192.168.182.2'
add_route_command = "route add -p {dest_ip} mask {mask} {gateway}"

for route in routes:
    if not route:
        continue

    # 0:目标地址
    # 1: 子网掩码
    # 2: 网关
    # 3: 接口
    # 4: 跃点数
    components = route.split()
    if len(components) != 5:
        continue

    if search_gateway != components[2]:
        continue

    command = add_route_command.format(dest_ip = components[0], mask = components[1], gateway = target_gateway)
    print(command)
    os.system(command=command)

里面ip_routes.txt内容就是从虚拟机获取的路由表内容复制出来。注意这里的gateway是host only网络在虚拟机侧的IP。

到这里就可以在宿主机ping通VPN内网IP了,最后一步是修改宿主机DNS,否则还是不能正确解析VPN内网域名。

首先找到虚拟机VPN的DNS地址,比如可以通过ipconfig /all命令等,配置到宿主机正经网卡的DNS中,但是也要配到host only网卡的DNS上(宿主机和虚拟机两侧都配置下),不然可能会出现宿主机dig命令可以解析内网域名,但ping和浏览器就是不行的情况。

如果系统睡眠/重启后发现不好使了,可以重启host only两侧网卡解决: image 先禁用,再启用。

参考: How to share Guest VM's VPN Connection with Host