WSL2使用的一些小技巧汇总

systemd

https://github.com/nullpo-head/wsl-distrod

Option 2: Make your Current Distro Run Systemd

By this installation, systemd is enabled in your WSL 2 distro.

  1. Download and run the latest installer script.

    1
    2
    3
    curl -L -O "https://raw.githubusercontent.com/nullpo-head/wsl-distrod/main/install.sh"
    chmod +x install.sh
    sudo ./install.sh install

    This script installs distrod, but doesn’t enable it yet.

  2. Enable distrod in your distro

    You have two options.
    If you want to automatically start your distro on Windows startup, enable distrod by the following command

    1
    /opt/distrod/bin/distrod enable --start-on-windows-boot

    Otherwise,

    1
    /opt/distrod/bin/distrod enable

    You can run enable with --start-on-windows-boot again if you want to enable autostart later.

  3. Restart your distro

    Close your WSL’s terminal.
    Open a new Command Prompt window, and run the following command.

    1
    wsl --terminate Distrod

    After re-opening a new WSL window, your shell runs in a systemd session.

端口转发

WSLHostPatcher

下载release到一个目录, 比如C:\Users\qwq\WSLHostPatcher\WSLHostPatcher.exe

在wsl2中systemd使其开机自启:

1
sudo vi /lib/systemd/system/wsl-host-patcher.service
1
2
3
4
5
6
7
8
9
10
11
12
13
[Unit]
Description=WSLHostPatcher
After=network.target
Before=ssh.service

[Service]
Type=simple
User=root
Restart=on-abort
ExecStart=/mnt/c/Users/qwq/WSLHostPatcher/WSLHostPatcher.exe

[Install]
WantedBy=multi-user.target

重新加载 systemd 模块

1
sudo systemctl daemon-reload

启动 WSLHostPatcher 服务

1
sudo systemctl start wsl-host-patcher.service

设置开机自启

1
sudo systemctl enable wsl-host-patcher.service

code-server

在wsl2中systemd使其开机自启:

1
sudo vi /lib/systemd/system/code-server@.service
1
2
3
4
5
6
7
8
9
10
11
12
[Unit]
Description=code-server
After=network.target

[Service]
Type=exec
ExecStart=/usr/bin/code-server
Restart=always
User=%i

[Install]
WantedBy=default.target

重新加载 systemd 模块

1
sudo systemctl daemon-reload

启动 WSLHostPatcher 服务

1
sudo systemctl start code-server@usr

设置开机自启

1
sudo systemctl enable code-server@usr
-------------end-------------
  • 本文作者: ouyen
  • 本文链接: https://ouyen.github.io/wsl2/
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!