こんにちは。
WSL2 で ssh サーバを動かし、外部から接続可能としました1。下記のスクリプトを Powershell 上で動かします2。
動作例
管理者権限下で、
PS> Set-ExecutionPolicy RemoteSigned -Force
PS> .\portproxy_ssh.ps1
OpenSSH_8.9p1 Ubuntu-3ubuntu0.1, OpenSSL 3.0.2 15 Mar 2022
* Starting OpenBSD Secure Shell server sshd [ OK ]
Ok.
コマンドライン上で動かす場合の例
> %Systemroot%\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy RemoteSigned c:\temp\portproxy_ssh.ps1
スクリプトソース
portproxy_ssh.ps1
# Encoding::Shift-JIS
# ip service
sc.exe query iphlpsvc | findstr -i state | findstr -i stopped
if ( $? ) {
sc.exe start iphlpsvc
sc.exe config iphlpsvc start= auto
}
# network (WSL2)
$Distribution = "Ubuntu"
$Port = 22
wsl -d $Distribution -- ssh -V
if ( $? ) {
wsl -d $Distribution -u root -- service ssh restart
$IP = (wsl -d $Distribution exec hostname -I).Trim()
netsh advfirewall firewall add rule name="sshd" dir=in action=allow protocol=TCP localport=$Port
netsh interface portproxy add v4tov4 listenport=$Port connectaddress=$IP connectport=22
} else {
echo "Please install openssh into $($Distribution): `"sudo apt install openssh-server`""
}
-
参考:「wsl2でsshサーバを起動し、外部からそこに接続」、「wsl2のsshサーバーに他PCから接続できるよう自動設定する」 ↩
-
PC 再起動後は改めて実行が必要です。 ↩