WSL2设置静态ip

WSL2设置静态ip

1.新建wsl.bat文件

文件内容为:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -c "Get-NetAdapter 'vEthernet (WSL)' | Get-NetIPAddress | Remove-NetIPAddress -Confirm:$False; New-NetIPAddress -IPAddress 172.22.0.1 -PrefixLength 24 -InterfaceAlias 'vEthernet (WSL)'; Get-NetNat | ? Name -Eq WSLNat | Remove-NetNat -Confirm:$False; New-NetNat -Name WSLNat -InternalIPInterfaceAddressPrefix 172.22.0.0/24;"

注意:powershell.exe脚本的路径以实际情况为主

2.wsl中设置

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Byrkmmed-1692203240801)(D:\Software\Typora\image\image-20230816234311635.png)]

在用户的家目录.profile文件添加如下内容

if [ "$(ip addr show eth0 | grep 'inet\b' | awk '{print $2}' | head -n 1)" != "172.22.0.2/24" ];
then
        sudo ip addr del $(ip addr show eth0 | grep 'ine' | awk '{print $2}' | head -n 1) dev eth0
        sudo ip addr add 172.22.0.2/24 broadcast 172.22.0.255 dev eth0
        sudo ip route add 0.0.0.0/0 via 172.22.0.1 dev eth0
fi

2.免密sudo权限
为了执行上一步,需要这个权限。
在 /etc/sudoers 里添加:

UserName ALL=(ALL) NOPASSWD:ALL

3.配置DNS
在 /etc/wsl.conf 文件写入

[network]
generateResolvConf = false 

在 /etc/resolv.conf 文件写入

nameserver 192.168.1.1 # 写入网关ip

注:在cmd中ipconfig查看网关

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在WSL 2中设置静态IP,需要进行以下步骤: 1. 打开Windows Terminal或其他终端应用程序,并在其中启动WSL 2。 2. 运行以下命令以安装所需的软件包: ``` sudo apt update sudo apt install net-tools ``` 3. 通过运行以下命令,查找要配置静态IP网络接口的名称: ``` ip link ``` 通常情况下,该接口的名称类似于“eth0”或“wsl0”。 4. 运行以下命令以编辑网络接口的配置文件: ``` sudo nano /etc/network/interfaces ``` 5. 在文件中添加以下行,替换为您要使用的IP地址、网关和DNS服务器的值: ``` auto <接口名称> iface <接口名称> inet static address <IP地址> netmask <子网掩码> gateway <网关地址> dns-nameservers <DNS服务器地址> ``` 例如,如果要将静态IP地址设置为“192.168.1.100”、“255.255.255.0”子网掩码、“192.168.1.1”网关和“8.8.8.8”DNS服务器,则应添加以下行: ``` auto eth0 iface eth0 inet static address 192.168.1.100 netmask 255.255.255.0 gateway 192.168.1.1 dns-nameservers 8.8.8.8 ``` 6. 保存文件并退出编辑器。 7. 运行以下命令以重启网络服务: ``` sudo service networking restart ``` 8. 确认静态IP地址是否已成功设置,可以通过运行以下命令来检查: ``` ip addr show <接口名称> ``` 例如,如果要检查名为“eth0”的接口,则应运行以下命令: ``` ip addr show eth0 ``` 如果一切正常,则应该看到接口已配置为使用静态IP地址。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值