WSL内のサーバへ外部PCから接続

ssh serviceの自動起動設定

https://buzz-server.com/tech/ubuntu-ssh/

echo 'none none rc defaults 0 0' | sudo tee -a /etc/fstab
echo '#!/bin/bash' | sudo tee /sbin/mount.rc
echo 'sudo service ssh start' | sudo tee -a /sbin/mount.rc
sudo chmod +x /sbin/mount.rc

$sudo ssh-keygen -A を実行

password認証を有効にするには、/etc/ssh/sshd_configを修正する。

ポート転送の設定PowerShell スクリプト

https://neos21.net/blog/2021/07/20-01.html

if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole("Administrators")) { Start-Process powershell.exe "-File `"$PSCommandPath`"" -Verb RunAs; exit }

$ip = bash.exe -c "ip r |tail -n1|cut -d ' ' -f9"
if( ! $ip ){
  echo "The Script Exited, the ip address of WSL 2 cannot be found";
  exit;
}

# All the ports you want to forward separated by comma
$ports=@(22,8501,8888);
$ports_a = $ports -join ",";

# Remove Firewall Exception Rules
iex "Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' ";

# Adding Exception Rules for inbound and outbound Rules
iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Outbound -LocalPort $ports_a -Action Allow -Protocol TCP";
iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Inbound -LocalPort $ports_a -Action Allow -Protocol TCP";

for( $i = 0; $i -lt $ports.length; $i++ ){
  $port = $ports[$i];
  iex "netsh interface portproxy add v4tov4 listenport=$port listenaddress=* connectport=$port connectaddress=$ip";
}

# Show proxies
iex "netsh interface portproxy show v4tov4";

ポート転送の削除  netsh.exe interface portproxy delete v4tov4 listenport=22

Windows FireWallの設定(解放)

https://qiita.com/DR623G/items/20e1d95e25e4ae658a33

netsh advfirewall firewall add rule name="WSL2" dir=in action=allow protocol=TCP localport=22

設定の確認

netsh advfirewall firewall show rule name="WSL2" verbose

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です