WSL Auto-Start and Persistent Background Execution (via SSH)

This guide provides a solution for WSL2 on Windows 10 (also applicable to Windows 11) to enable automatic startup upon boot and maintain continuous background operation.


**Key Configuration Steps:**

* Install SSH and enable Systemd.
* Local Network Connectivity and Firewall Port Forwarding (required for any local network services).
* WSL2 Auto-Start / Persistent Background Execution (Win10).
  - `sleep infinity`: The core command to keep the instance running.

---

**Example Configuration: Please replace these with your own system details**

* `<WIN_BAT_PATH>`: The Windows path where your `.bat` files are stored; e.g., `E:\WSL\ubuntu\scripts`

* `<WIN_IP>`: Your Windows machine's IP address.

## SSH and Systemd Configuration within WSL Ubuntu

### 1. Install SSH and Enable Systemd

* After entering Ubuntu, execute the following commands:

```bash
# Update and install
sudo apt update && sudo apt install openssh-server -y

# Edit wsl.conf to enable systemd (Required for WSL2)
sudo nano /etc/wsl.conf
```


* Paste the following content into `/etc/wsl.conf`:

```yaml
[boot]
systemd=true

[user]
default=cyadmin
```

### 2. Configure SSH Parameters

* Edit the SSH configuration file:

```bash
sudo nano /etc/ssh/sshd_config
```

* Search for the following keys and update the information (**Port 2222** is recommended to avoid conflicts with Windows services):

```text
Port 2222
ListenAddress 0.0.0.0
PasswordAuthentication yes
```

### 3. Resolve Socket Conflicts and Restart Services

Ubuntu 24.04 uses "socket activation" by default, which often fails in the WSL environment. You must revert to the traditional service mode:

```bash
# Disable and mask the Socket
sudo systemctl disable --now ssh.socket
sudo systemctl mask ssh.socket

# Enable and start the service
sudo systemctl enable ssh
sudo systemctl restart ssh
```

---

## Local Network Connectivity and Firewall Port Forwarding

This step is critical for allowing other devices on your network to access WSL via your Windows IP (`<WIN_IP>`).

### 1. Open Firewall (PowerShell Administrator) - Run Once Only!

```bat
New-NetFirewallRule -DisplayName "WSL SSH Port 2222" -Direction Inbound -Action Allow -Protocol TCP -LocalPort 2222
```

### 2. Create a Batch File to Automatically Update [WSL to Windows] Port Forwarding (Solves the Dynamic WSL IP Issue)

Create the following file in Windows (e.g., `<WIN_BAT_PATH>\update_wsl_ports_by_admin.bat`)

```bat
@echo off
echo ========================================
echo WSL SSH Port Forwarding Updater
echo ========================================

:: Get the WSL IP (take the first one)
for /f "tokens=1" %%i in ('wsl hostname -I') do (
    set WSL_IP=%%i
)

if "%WSL_IP%"=="" (
    echo Unable to obtain WSL IP. Please check if WSL is functioning correctly.
    exit /b 1
)

echo Found WSL IP: %WSL_IP%

echo ====== Processing ssh 2222
:: Delete old portproxy (ignore errors) -> Add port forwarding (Listen on all Windows interfaces, forward to WSL)
netsh interface portproxy delete v4tov4 listenport=2222 >nul 2>&1
netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=2222 connectaddress=%WSL_IP% connectport=2222
if %errorlevel% equ 0 (
    echo V Port forwarding: Done! Internal network connection is available: Windows_IP:2222
) else (
    echo X Port forwarding: Failed. Please run this bat file as a system administrator.
)
echo.
echo Current settings:
netsh interface portproxy show v4tov4 | findstr 2222
echo.
```

### 3. Add `.wslconfig`

* Run the following in PowerShell:

```bat
notepad $env:USERPROFILE\.wslconfig
```

* `.wslconfig` content:

```yaml
[wsl2]
# Mirrored mode and autoMemoryReclaim are not supported on Win10
localhostForwarding=true
```

**Note on Saving:** In Notepad, go to **File** > **Save As**, and ensure the **Encoding** (bottom right) is set to **UTF-8** (do not use UTF-8 with BOM).

---

## WSL2 Auto-Start / Persistent Background Execution (Win10)

### Enable systemd in WSL

* Open Ubuntu (by typing `wsl` or clicking the Ubuntu shortcut).

* Execute the following command to create/edit the config file:

```bash
sudo nano /etc/wsl.conf
```

* Add the following to the bottom of `/etc/wsl.conf` (if the file is empty, just paste this):

```yaml
[boot]
systemd=true
```

* Press `Ctrl + O` $\rightarrow$ Enter to save, then `Ctrl + X` to exit.

* Return to Windows PowerShell and execute:

```bat
wsl --shutdown
```

* Restart Ubuntu and run the following command to verify that systemd is active:

```bash
systemctl status
```

### Configure Windows Auto-Start for WSL (The Core Step)

* Press `Win + R`, type `taskschd.msc` to open **Task Scheduler**.

* Click **"Create Task"** on the right (do NOT use "Create Basic Task").

* **General Tab:**

  - Name: `WSL2 Auto Start Ubuntu`

  - Check **"Run whether user is logged on or not"**

  - Check **"Run with highest privileges"**

  - Configure for: **Windows 10**.

* **Triggers Tab:**

  - New $\rightarrow$ Begin the task: **"At startup"**.

  - (Recommended) Check **"Delay task for"** $\rightarrow$ 30 seconds to avoid boot-up conflicts.

* **Actions Tab:**

  - New $\rightarrow$ Program/script: `<WIN_BAT_PATH>\update_wsl_ports_by_admin.bat`

  - New $\rightarrow$ Program/script: `C:\Windows\System32\wsl.exe`; Add arguments: `-d Ubuntu-24.04 -u root sleep infinity`

  *(Note: `Ubuntu-24.04` is your distribution name; check the correct name by running `wsl -l` in PowerShell).*

* **Conditions Tab:**

  - **Uncheck** "Start the task only if the computer is on AC power" (to avoid issues with laptops).

* **Settings Tab:**

- Check **"Allow task to be run on demand"**.

  - Check **"If the task fails, restart every"** $\rightarrow$ 1 minute $\rightarrow$ Attempts: 3 times.

  - **Uncheck** "Stop the task if it runs longer than".

* Click **"OK"** $\rightarrow$ Enter your Windows account password if prompted.


### Full Restart and Verification


* Run `wsl --shutdown` in PowerShell to close all instances.

* Reboot your computer or manually trigger the scheduled task.

* Run `wsl -l -v` to verify the status is **Running**.


### How to Connect?


* **Local Connection:** `ssh cyadmin@127.0.0.1 -p 2222`

* **LAN Connection:** `ssh cyadmin@<WIN_IP> -p 2222`

Comments

Popular posts from this blog

Essential 4. travel gear for international travel: Compression Bags (to avoid "not enough space")

Essential 5. travel gear for international travel: SIM/eSIM card (to avoid "No Connection")