LoginSignup
0
2

WSL2 で ssh サーバを動かす(+外部から接続)

Last updated at Posted at 2023-03-05

こんにちは。
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`""
}
  1. 参考:「wsl2でsshサーバを起動し、外部からそこに接続」、「wsl2のsshサーバーに他PCから接続できるよう自動設定する

  2. PC 再起動後は改めて実行が必要です。

0
2
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
0
2