1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

WindowsのネットワークアダプターをWSLへ自動でブリッジする

Last updated at Posted at 2024-09-29

はじめに

まず、最新のWindows11環境であれば、wslへのネットワークアダプタのブリッジは .wslconfigに数行記入するだけでよく、複雑な作業を行う必要はない

.wslcomfig
[wsl2]
networkingMode=bridged
vmSwitch=External
dhcp=true

今回どうしてもWindows10を使わねばならず、起動時に自動的に指定のネットワークアダプターをWSLにブリッジしたかった。Windows10環境では上記の.wslconfigでの自動化は対応しておらず、かなり苦労したので方法を共有しておく。

ブリッジの自動化スクリプト

結論から言うと、こちらのようなPowrShellスクリプトで自動化できる。

if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
{
    $argsToAdminProcess = ""
    $Args.ForEach{ $argsToAdminProcess += " `"$PSItem`"" }
    Start-Process powershell.exe "-File `"$PSCommandPath`" $argsToAdminProcess" -Verb RunAs
    exit
}
wsl -d Ubuntu-22.04 -- echo 'hello hello how row?'
Disable-NetAdapterBinding -Name "イーサネット"
Set-VMSwitch -Name "WSL" -NetAdapterName "イーサネット" -AllowManagementOS $true

こちらの例では、後半3行でWSL2のUbuntu22.04を起動後、"イーサネット"という名前のアダプターを"WSL"という仮想スイッチにブリッジしているので、この辺りは適宜使用環境に合わせて変更してほしい。

前半の部分は、ネットワークのブリッジは管理者権限でないと行えないため、管理者のシェルに昇格している。
最初から管理者権限で起動するなどできればそれでもいいのだが、自分の環境ではうまくいかなかったため、この手法をとることにした。

このスクリプトを、タスクスケジューラやスタートアップに登録すれば、OS起動後に自動的にネットワークがWSLにブリッジされる。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?