WSL2のUbuntuにSSHで接続する方法【systemd対応版】

◆ Live配信スケジュール ◆
サイオステクノロジーでは、Microsoft MVPの武井による「わかりみの深いシリーズ」など、定期的なLive配信を行っています。
⇒ 詳細スケジュールはこちらから
⇒ 見逃してしまった方はYoutubeチャンネルをご覧ください
【5/21開催】Azure OpenAI ServiceによるRAG実装ガイドを公開しました
生成AIを活用したユースケースで最も一番熱いと言われているRAGの実装ガイドを公開しました。そのガイドの紹介をおこなうイベントです!!
https://tech-lab.connpass.com/event/315703/

こんにちは、2023年1月からサイオステクノロジーにjoinした久保です。
今回はWSL2に導入したUbuntuにSSH接続するための方法をご紹介します。
なお、昨年の秋ごろにWSL2がsystemdに対応したので、そのsystemdを有効にしてsshdサービスを起動します。

忙しい人向けの要約

  • Ubuntu上でWSL設定ファイルを作成
cat <<EOF | sudo tee /etc/wsl.conf
[boot]
systemd=true
EOF
  • WSL2を再起動
wsl --shutdown
  • Ubuntu上でSSH関連の作業
# sshdの有効化
sudo systemctl enable ssh
# SSHホスト鍵の生成
sudo ssh-keygen -A
# パスワード認証の有効化(任意)
sudo sed -i -e 's/^PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config
# sshdの起動
sudo systemctl start ssh

目的

WSL上でsshdを動かす必要性は無いように感じますが、筆者はCLI作業は全てログに残したく、
そういった場合、現状のデフォルトのコンソールやWindows Terminalでは手動でコンソール結果を保存するしかありません。
しかし、ssh接続が出来ればTeraTermやRLoginなどのターミナルソフトで自動ログ取得が可能になります。
そのため、目的は自動ログを取得することにあり、ホストOS外部にsshを公開することではないことにご留意ください。
※基本的に作業用のWindowsマシンでそのような用途は推奨しかねますし、もし外部公開するとなるとセキュリティ上の考慮が必要になります。

環境

筆者の環境は以下の通りです。

OS/SWバージョン
ホストOSWindows 10
WSL21.1.6.0
WSL2のLinux DistributionUbuntu 20.04 LTS

内容詳細

特段記載のない限り、ここでの操作はWSL2上のUbuntuでの操作になります。
※「ホストOSで」などの記載がある場合は、それに従ってください。

Ubuntuでsystemdを有効にする

現在のWSL2ではsystemdはデフォルトで有効になっていません。
そのため、systemctlコマンドを実行するとエラーが発生します。

develop@1010-00138:~$ sudo systemctl status ssh
System has not been booted with systemd as init system (PID 1). Can't operate.
Failed to connect to bus: Host is down
develop@1010-00138:~$

systemdを有効にするため、下記のコマンドでWSL用設定ファイルを作成します。
既にwsl.confを作成している方は、内容を追記してください。
参考:systemd のサポート

cat <<EOF | sudo tee /etc/wsl.conf
[boot]
systemd=true
EOF

設定を反映させるため、ホストOSでWSL2の再起動を実施します。
下記の停止コマンドを実行するだけで、自動的にWSL2が起動してきます。

wsl --shutdown

sshdの有効化

これでsystemdが有効になったので、下記の通りsystemctlコマンドでsshdを有効化します。

# sshdの有効化
sudo systemctl enable ssh

実行結果

develop@1010-00138:~$ sudo systemctl enable ssh
Synchronizing state of ssh.service with SysV service script with /lib/systemd/systemd-sysv-install.
Executing: /lib/systemd/systemd-sysv-install enable ssh
Created symlink /etc/systemd/system/sshd.service → /lib/systemd/system/ssh.service.
Created symlink /etc/systemd/system/multi-user.target.wants/ssh.service → /lib/systemd/system/ssh.service.
develop@1010-00138:~$

sshホスト鍵の作成

さて、これでsshdを起動したいところですが、初期状態だと下記のエラーが発生します。

develop@1010-00138:~$ sudo systemctl start ssh
Job for ssh.service failed because the control process exited with error code.
See "systemctl status ssh.service" and "journalctl -xe" for details.
develop@1010-00138:~$

systemctlでstatusを見てみますが、起動が失敗したという情報くらいしか出力されていません。

develop@1010-00138:~$ sudo systemctl status ssh
● ssh.service - OpenBSD Secure Shell server
     Loaded: loaded (/lib/systemd/system/ssh.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since Tue 2023-04-11 11:52:31 JST; 1s ago
       Docs: man:sshd(8)
             man:sshd_config(5)
    Process: 825 ExecStartPre=/usr/sbin/sshd -t (code=exited, status=1/FAILURE)
        CPU: 4ms

Apr 11 11:52:31 1010-00138 systemd[1]: ssh.service: Scheduled restart job, restart counter is at 5.
Apr 11 11:52:31 1010-00138 systemd[1]: Stopped OpenBSD Secure Shell server.
Apr 11 11:52:31 1010-00138 systemd[1]: ssh.service: Start request repeated too quickly.
Apr 11 11:52:31 1010-00138 systemd[1]: ssh.service: Failed with result 'exit-code'.
Apr 11 11:52:31 1010-00138 systemd[1]: Failed to start OpenBSD Secure Shell server.
develop@1010-00138:~$

そのため、”journalctl -xe”を見て行きます。

develop@1010-00138:~$ journalctl -xe | tail -n 100
~省略~
-- The job identifier is 1425.
Apr 11 11:52:31 1010-00138 sshd[825]: sshd: no hostkeys available -- exiting.
Apr 11 11:52:31 1010-00138 systemd[1]: ssh.service: Control process exited, code=exited, status=1/FAILURE
-- Subject: Unit process exited
-- Defined-By: systemd
~省略~
develop@1010-00138:~$

そうすると「sshd: no hostkeys available — exiting.」とホスト鍵がない、というエラーが出ていますので、下記コマンドでホスト鍵を生成します。
コマンドが正常に完了すると、「/etc/ssh/」配下にssh_host*のホスト鍵ファイル群が作成されます。

# SSHホスト鍵の生成
sudo ssh-keygen -A

実行結果

develop@1010-00138:~$ sudo ssh-keygen -A
ssh-keygen: generating new host keys: RSA DSA ECDSA ED25519
develop@1010-00138:~$
develop@1010-00138:~$ ls -la /etc/ssh/
total 584
drwxr-xr-x  4 root root   4096 Apr 11 11:59 .
drwxr-xr-x 99 root root   4096 Apr 11 11:46 ..
-rw-r--r--  1 root root 535195 Mar 30  2022 moduli
-rw-r--r--  1 root root   1603 Mar 30  2022 ssh_config
drwxr-xr-x  2 root root   4096 Mar 30  2022 ssh_config.d
-rw-------  1 root root   1381 Apr 11 11:59 ssh_host_dsa_key
-rw-r--r--  1 root root    605 Apr 11 11:59 ssh_host_dsa_key.pub
-rw-------  1 root root    505 Apr 11 11:59 ssh_host_ecdsa_key
-rw-r--r--  1 root root    177 Apr 11 11:59 ssh_host_ecdsa_key.pub
-rw-------  1 root root    411 Apr 11 11:59 ssh_host_ed25519_key
-rw-r--r--  1 root root     97 Apr 11 11:59 ssh_host_ed25519_key.pub
-rw-------  1 root root   2602 Apr 11 11:59 ssh_host_rsa_key
-rw-r--r--  1 root root    569 Apr 11 11:59 ssh_host_rsa_key.pub
-rw-r--r--  1 root root    342 Aug 30  2022 ssh_import_id
-rw-r--r--  1 root root   3289 Mar 30  2022 sshd_config
drwxr-xr-x  2 root root   4096 Mar 30  2022 sshd_config.d
develop@1010-00138:~$

パスワード認証の有効化(任意)

この作業は任意ですが、ローカル接続だけなので利便性向上のためパスワード認証を有効にします。(sshdのデフォルトは無効)
下記コマンドでsshdの設定ファイルを変更します。

# パスワード認証の有効化
sudo sed -i -e 's/^PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config

実行結果

develop@1010-00138:~$ sudo sed -i -e 's/^PasswordAuthentication no/PasswordAuthentication yes/' /etc/ssh/sshd_config
develop@1010-00138:~$
develop@1010-00138:~$ cat /etc/ssh/sshd_config | grep PasswordAuthentication
PasswordAuthentication yes
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication, then enable this but set PasswordAuthentication
develop@1010-00138:~$

sshdの起動

それでは、下記コマンドでsshdを起動しましょう。

# sshdの起動
sudo systemctl start ssh

テスト接続

ホストOSから接続できることを確認します。
今回はPowerShellからsshコマンドで疎通確認します。
※指定するユーザーは各自の環境に読み替えてください。(筆者のUbuntu環境ではdevelopというユーザーを作成済み)

PS C:\Users\stuser00138> ssh develop@localhost
The authenticity of host 'localhost (::1)' can't be established.
ECDSA key fingerprint is SHA256:z6i6oK7VuZeCL7im2MPQu8fXjhhpJiuBDpSXmCWsYzk.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'localhost' (ECDSA) to the list of known hosts.
develop@localhost's password:
Welcome to Ubuntu 20.04.5 LTS (GNU/Linux 5.15.90.1-microsoft-standard-WSL2 x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Tue Apr 11 12:32:17 JST 2023

  System load:  0.0                 Processes:             38
  Usage of /:   0.2% of 1006.85GB   Users logged in:       1
  Memory usage: 5%                  IPv4 address for eth0: 172.27.12.233
  Swap usage:   0%

 * Strictly confined Kubernetes makes edge and IoT secure. Learn how MicroK8s
   just raised the bar for easy, resilient and secure K8s cluster deployment.

   https://ubuntu.com/engage/secure-kubernetes-at-the-edge

34 updates can be applied immediately.
To see these additional updates run: apt list --upgradable


Last login: Tue Apr 11 11:46:56 2023
develop@1010-00138:~$

終わりに

WSL2のsystemd対応は昨年の秋ごろにリリースされた0.67.6からです。(MS Store版から)
参考:WSL Releases 0.67.6

そのため、それまでWSL2起動時にサービス(今回だと、sshd)を自動起動させるためにはmountの仕組みを駆使するなどして、裏技的にサービスを起動させる必要がありましたが、今後そのような必要はありません。

また今後の執筆予定ですが、VSCode Dev ContainerとRancher Desktopを利用したコンテナ環境、Azure CLIについて、kubeadmを使ったKubernetes構築シリーズなどを書こうかな~と思っています。

それでは、良きWSLライフを!

アバター画像
About 久保雄平 5 Articles
2023年にjoin。主にバックエンドの開発、保守運用をしてきた男。趣味は美味しいお酒・ご飯を食べることと、ボードゲーム・マーダーミステリー・脱出ゲームばかりやっていますが、最近は古のゲームであるメイジナイトをやり始めて人生迷走中・・・
ご覧いただきありがとうございます! この投稿はお役に立ちましたか?

役に立った 役に立たなかった

5人がこの投稿は役に立ったと言っています。


ご覧いただきありがとうございます。
ブログの最新情報はSNSでも発信しております。
ぜひTwitterのフォロー&Facebookページにいいねをお願い致します!



>> 雑誌等の執筆依頼を受付しております。
   ご希望の方はお気軽にお問い合わせください!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


質問はこちら 閉じる