Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unable to start WSL via Task Scheduler #8835

Closed
1 of 2 tasks
tvwenger opened this issue Sep 19, 2022 · 55 comments
Closed
1 of 2 tasks

Unable to start WSL via Task Scheduler #8835

tvwenger opened this issue Sep 19, 2022 · 55 comments
Labels
duplicate Store WSL Issue specific to WSL in the Microsoft Store

Comments

@tvwenger
Copy link

Version

22000.978

WSL Version

  • WSL 2
  • WSL 1

Kernel Version

5.15.57.1

Distro Version

Ubuntu 22.04

Other Software

No response

Repro Steps

Create a powershell script with the following:

# start SSH server and other applications in Ubuntu
wsl -d Ubuntu-22.04 -u root service ssh start
Start-Sleep -s 5

# add port forwarding rule (from WSL to host) for port 4242
$wsl_ip = (wsl hostname -I).trim()
Write-Host "WSL Machine IP: ""$wsl_ip"""
netsh interface portproxy add v4tov4 listenport=4242 connectport=4242 connectaddress=$wsl_ip

Create a Task Scheduler task to run the powershell script on boot.

  • Run whether use is logged in or not
  • Run with highest privileges
  • Trigger: at startup (30 second delay)
  • Action: start a program:
    C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
  • Action: Add arguments:
    -ExecutionPolicy Bypass -File C:\Scripts\startwsl.ps1
  • Settings: Allow task to be run on demand

Restart the machine, or manually run the task.

Expected Behavior

Upon reboot or manually running the task, the WSL instance should start and the ssh daemon should be running. This worked in previous versions of WSL (on Windows 10).

Actual Behavior

Either on reboot or on manually executing the task, WSL does not start.

C:\Windows\system32>wsl --list --running
There are no running distributions.

If I manually run the following command via the command prompt, WSL and the ssh daemon start properly.

C:\Windows\system32>C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File C:\Scripts\startwsl.ps1
 * Starting OpenBSD Secure Shell server sshd                                                                                                                      [ OK ]
Starting seafile daemon ...
Started: seafile daemon ...
WSL Machine IP: "172.21.82.221"


C:\Windows\system32>wsl --list --running
Windows Subsystem for Linux Distributions:
Ubuntu-22.04 (Default)

In summary, running the same powershell script to launch WSL works from the command prompt but does not work from the task scheduler.

Diagnostic Logs

No response

@OneBlue
Copy link
Collaborator

OneBlue commented Sep 21, 2022

/logs

@ghost
Copy link

ghost commented Sep 21, 2022

Hello! Could you please provide more logs to help us better diagnose your issue?

To collect WSL logs, download and execute collect-wsl-logs.ps1 in an administrative powershell prompt:

Invoke-WebRequest -UseBasicParsing "https://raw.githubusercontent.com/microsoft/WSL/master/diagnostics/collect-wsl-logs.ps1" -OutFile collect-wsl-logs.ps1
Set-ExecutionPolicy Bypass -Scope Process -Force
.\collect-wsl-logs.ps1

The scipt will output the path of the log file once done.

Once completed please upload the output files to this Github issue.

Click here for more info on logging

Thank you!

@tvwenger
Copy link
Author

tvwenger commented Sep 22, 2022

I have attached two logs. _powershell.zip when I ran my powershell script via the command line to start WSL (success), and _taskscheduler.zip when I ran the powershell script via the task scheduler (failure).
WslLogs-2022-09-21_20-52-49_powershell.zip
WslLogs-2022-09-21_20-54-39_taskscheduler.zip

@ghost ghost removed the needs-author-feedback label Sep 22, 2022
@cheng-chi
Copy link

I have the same problem. This problem seems to be specific to the Microsoft Store version of wsl. If I uninstall the Microsoft Store WSL app, task schedule can properly start wsl. I tried the vbs trick mentioned here without success. This problem seems to be related to the "Unable to start wsl.exe from a Session 0 prompt which users can run into when trying to start WSL from an ssh session" limitation mentioned in the release blogpost.

@tvwenger
Copy link
Author

I can confirm, as @cheng-chi said, that this issue is only apparent in the Microsoft Store version of WSL. I am able to start WSL via the Task Scheduler when I use the non-Microsoft Store version.

@tvwenger
Copy link
Author

And since I'd like to use WSLg, I need the Microsoft Store version...

@brettus78
Copy link

+1
I have this issue too. Same deal - was working before. Then upgraded Windows to 22H2 & was prompted by WSL to run some WSL Update command for WSL to do with store (sadly I can't recall the exact command or find it - it was something that appeared at the first opening of a WSL terminal post-Windows update) - now Task Scheduler won't run my command anymore. Before that - it worked. Even if I open Task Scheduler, select the task, & click 'Run' - nothing happens.
Same as the above poster, it works when I run exactly the same command that I have in Task Scheduler, directly from UN-elevated CMD or UN-elevated Powershell.
CMD_WslLogs-2022-10-08_10-52-39.zip
Task_Scheduler_WslLogs-2022-10-08_10-50-45.zip
image
At time of posting this - it's 10:55AM AWST on 08 October 2022 - it shows the last run time (even though I've been clicking RUN) as two days ago (06 October 2022) - which is when I installed the new Windows update.
image

@cheng-chi
Copy link

cheng-chi commented Oct 9, 2022

I think I have found a solution. According to this StackOverflow answer, we can escalate a process out of session 0 using psexec.exe.

  1. Download PsTools and extract PsExec.exe to a convenient location.
  2. Replace your command running wsl with C:\<your psexec install path>\PsExec.exe -i 1 <your original command>

@brettus78
Copy link

If the workaround works, it will be very useful until MS can resolve the issue.
I'll give it a test & report back.
Many thanks

@brettus78
Copy link

Sadly the workaround didn't work. Even deleted the task & recreated it from scratch using the workaround, no change.
Must be something to do with the Windows update.

@cheng-chi
Copy link

@brettus78 I have created a GitHub repo for my solution of running wsl at startup. I have also installed the Windows 11 22H2 update so I think it shouldn't be the issue.

@sikhness
Copy link

sikhness commented Oct 9, 2022

I have the same issue. If I try to use the psexec64.exe -i 1 <command> workaround, I keep getting a poweshell.exe exited with error code 0 error.

@brettus78
Copy link

Been flat out - will try the example in the GitHub repo you posted, ASAP. But might be a couple of days before I get a chance.

@seanballais
Copy link

seanballais commented Oct 14, 2022

Just happy to report that using psexec64.exe worked for me. I didn't need to port forward SSH though, so I didn't test that part.

@sikhness, I actually got the same message when I ran the psexec64.exe command in PowerShell. If my memory serves me correctly, WSL 2 should be running in the background by then.

Log for October 15, 2022: I just found that it didn't actually work, after shutting down my system when I went to bed and opening it again hours after I woke up. Tried Distrod, but to no avail. I'm ditching WSL 2 for the moment, until they support having one instance usable by all users.

@brettus78
Copy link

I'll need to do further testing to isolate - but I recently received another Windows update (around features like tabs in File Explorer). As a test triggered by SeanBallais' comment above "having one instance usable by all users" - I thought I should try a Task Scheduler task that only runs when I'm logged in.
I tried it & it works.
Not sure if because I chose to only run once logged in - or if resolved by the Windows update. Suspect the former.
At some point, I'll try again with running without having logged in & see if it works since the update, but for now, it's working, so it's a low priority for me.
image

@craigloewen-msft craigloewen-msft added the Store WSL Issue specific to WSL in the Microsoft Store label Nov 3, 2022
@tvwenger
Copy link
Author

I can confirm that it works if you run the script with "only when user is logged on" and triggered at log on.

@mousumih
Copy link

mousumih commented Nov 17, 2022

I need to use "Run whether user is logged in or not" to start wsl2 from taskScheduler. Is this working for anyone? Also can confirm that this is not only related to wsl2 - tried starting notepad.exe and had the same issue

@GlenC289
Copy link

The only thing I found that worked is to change the user on the task to the group "Users". The downside is that it opens a terminal on the screen. I can't seem to minimize it on execution for some reason. Strange how everyone has a different method that works.

@hammadrauf
Copy link

@GlenC289 solution worked for me on Windows 11. I am copying my Task Scheduler Script. Comments indicate how I setup the Task.
-NoExit argument to pwsh was necessary. I have installed wsl2 Ubuntu and enabled SystemD.

Code from the Filename: start-wsl-forward-ports.ps1 follows.

# WSL Start and Port Forwarding Script
# Task Scheduler Setup:
# 	Run as user: Users
#	Run with highest privileges
# 	Triggers: Startup delay 30 seconds
#	Action: script: "C:\Program Files\PowerShell\7\pwsh.exe"
#		  Arguments: -NoExit -WindowStyle hidden -ExecutionPolicy Bypass -File "C:\scripts\wsl2\start-wsl-forward-ports.ps1"
#	        Start in: C:\scripts\wsl2\
#	Settings: (2 only) 1) Allow task to be run on demand, 2) if the running task does not end......
#
Get-Date | Out-File -FilePath "C:\scripts\wsl2\output.log" -Append
Echo "Start WSL and port forwarding..." | Out-File -FilePath "C:\scripts\wsl2\output.log" -Append
$wsl_ip = (C:\Windows\system32\wsl.exe -d "Ubuntu-22.04" --shell-type login hostname -I).split(" ")[0]
# Following line runs an infinite long running job, so that WSL does not time out and exit.
C:\Windows\system32\wsl.exe -d "Ubuntu-22.04" tail -n 1 -f /dev/null &
Echo "WSL Machine IP: ""$wsl_ip""" | Out-File -FilePath "C:\scripts\wsl2\output.log" -Append
# Put Your Ports Forwarding below and uncomment
#netsh interface portproxy add v4tov4 listenport=4505 connectport=32377 connectaddress=$wsl_ip
#netsh interface portproxy add v4tov4 listenport=4506 connectport=32378 connectaddress=$wsl_ip
#netsh interface portproxy add v4tov4 listenport=8092 connectport=32380 connectaddress=$wsl_ip
#Write-Host "Completed - Start WSL and port forwarding..."
Echo "Completed - Start WSL and port forwarding..." | Out-File -FilePath "C:\scripts\wsl2\output.log" -Append

@GlenC289
Copy link

GlenC289 commented Nov 23, 2022

@hammadrauf Thanks, I appreciate you taking the time to post your solution. I finally decided to remove the Microsoft Store version (as reported by cheng-chi) above and it has been working normally for me so far. I will keep your post in mind though, just in case MS carries the problem over to the windows version.

@adepierre
Copy link

Just ran in the same issue with windows store version trying to start WSL at startup on W10 "whether user is logged in or not".

I need to use the Store version to have systemd, but can't manage to make it start automatically :/

My workaround at the moment is launching it manually everytime the machine restarts, which is not ideal.

@tvwenger
Copy link
Author

@adepierre

I can confirm that it works if you run the script with "only when user is logged on" and triggered at log on.

@adepierre
Copy link

@adepierre

I can confirm that it works if you run the script with "only when user is logged on" and triggered at log on.

Yeah that's what I do. But you still need to manually log in at each restart of the machine

@aki-k
Copy link

aki-k commented Dec 20, 2022

The psexec trick seems to work but not with the -s option. I put pstools into C:\pstools and then in the task scheduler start

Program/script: C:\PSTools\psexec64.exe
Add arguments: -i 0 C:\PSTools\psexec64.exe -i 1 C:\Windows\System32\wsl.exe -d Ubuntu-20.04

I added a 30 second delay to the task startup and WSL starts without me logging into the system.
There's still something that makes it stop, probably logging into the system with the user that WSL is running on.

Edit: I needed to change the startup delay from 30 seconds to 1 minute because only vmcompute.exe did start. vmwp.exe and vmmemWSL had trouble starting.

Edit 2: There's a console window appearing on my main account desktop during login. When I logout, WSL running in the other user session is closed so this is not working after all.

@wangyoucao577
Copy link

+1

My task scheduler breaks after I run wsl --update and reboot the system. Currently I have to use the startup workaround: create a shortcut in the C:\Users\<USER>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup to run the commands when login.

Waiting for Microsoft to solve the issue..

@aki-k
Copy link

aki-k commented Jan 25, 2023

I'm unable to start WSL on either Win10 Pro or Win11 Pro through Task Scheduler.
Task Scheduler history shows that the task started successfully but just wslservice.exe is running when I run "tasklist | findstr /i "vm wsl".

Task Scheduler successfully completed task "\start wsl" , instance "{db255c35-7af5-4ba4-ac84-57996065ccb4}" , action "C:\Windows\SYSTEM32\cmd.exe" with return code 0.

My action for the task is C:\Users\username\Scripts\startwsl.cmd which content is:

@echo off

C:\Windows\System32\wscript.exe //B C:\Users\username\Scripts\startwsl.vbs

C:\Users\username\Scripts\startwsl.vbs content is:

set object = createobject("wscript.shell")
object.run "C:\Windows\System32\wsl.exe --distribution Ubuntu-20.04", 0

I installed WSL with the command "wsl --install --web-download --no-distribution" and then imported the backup of the VM filesystem with:

mkdir C:\Users\siroadmin\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu20.04onWindows
wsl --import Ubuntu-20.04 C:\Users\siroadmin\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu20.04onWindows d:\WSL\Ubuntu-20.04.tar

I added the Windows feature Windows Subsystem for Linux because the filesystem import wouldn't work without it.

I also changed the default username to match the username username defined for the Task Scheduler task.

I have systemd running inside WSL VM so it should keep running even though I'm not using it.

Could it be that I somehow installed the Microsoft Store version of WSL that is known not to work with the Task Scheduler and session 0? This is baffling as I'm sure I had it working in Win11 Pro already.

Edit: Here's the process list that should be running when WSL VM starts up correctly:

C:\>tasklist | findstr /i "vm wsl"
wslservice.exe                6004 Services                   0     24 216 K
wsl.exe                      12204 Console                    1     11 012 K
wsl.exe                      10288 Console                    1     10 372 K
wslhost.exe                  11508 Console                    1      9 216 K
vmcompute.exe                11784 Services                   0     11 980 K
vmwp.exe                     12016 Services                   0     25 028 K
vmmemWSL                     12976 Services                   0  1 144 888 K
wslhost.exe                   7348 Console                    1      7 572 K
wslhost.exe                  14096 Console                    1     10 840 K
wslhost.exe                  12944 Console                    1      9 140 K
wslhost.exe                  10248 Console                    1      9 020 K

@DesktopECHO
Copy link

Windows Task Scheduler previously returned success code 0, but for several months now is returning 2147942401.

I don’t think it’s related to the version of WSL at all. If you create a new user, does the task also fail for that user? I’ve observed this issue doesn’t appear when a user is created after the 22H2 upgrade.

@aki-k
Copy link

aki-k commented Mar 26, 2023

@aGrimRepoMan

I see same issue with WSL1 on Windows 10 when running Windows Task Scheduler task
with program set to "C:\WINDOWS\System32\wsl.exe" and arguments set to
"-d Debian-BackupPC -u root service ssh start", i.e. without invoking intermediate
powershell or batch command file. Windows Task Scheduler previously
returned success code 0, but for several months now is returning 2147942401.

Try if these steps help:

  1. remove admin rights from the user running that scheduled task

  2. define the scheduled task program as:

C:\Windows\System32\cmd.exe /k start "" /wait C:\Windows\System32\wsl.exe -d Ubuntu-20.04 -u WSL_username

Edit: You might have to add "Log on as a batch job" permissions for the user running the task in:

secpol.msc: Security Settings/Local Policies/User Rights Assignment/Log on as a batch job

Edit 2: Log on as a batch job

When you use the Add Scheduled Task Wizard to schedule a task to run under a particular user name and password,
that user is automatically assigned the Log on as a batch job user right.

@cheng-chi
Copy link

See also this insideous bug affecting my WSL projects. Applies to Windows 10 and Windows 11 22H2:

Windows 11 22H2 upgrade breaks "Run whether user is logged on or not" scheduled tasks

Windows Version:

21H2 -> Scheduled Task OK!
22H2 -> Clean OS install -> Scheduled Task OK!
22H2 -> Upgrade from 21H2, user profile is present before upgrading to 22H2 -> TASK FAILED
22H2 -> Upgrade from 21H2, new user profile created after upgrade and new task created -> Scheduled Task OK!
It appears that something in the 21H2 -> 22H2 upgrade process causes existing profiles to have this trouble.
Creating a NEW user profile and Scheduled Task to "run whether the user is logged on or not" works reliably!
This is not a fix for what looks like a bug in the Windows upgrade process, but it does help narrow down the issue.

I encountered the same issue. It was resolved by

  1. Go to your task in Task Scheduler -> Properties -> General Change User or Group
  2. Enter "Administrators" in "Enter the object name to select" box
  3. Click "Check Names"
  4. Click Ok
  5. Click Ok (for properties)

@AdamDanischewski
Copy link

AdamDanischewski commented Apr 11, 2023

Same as cheng-chi, had something similar but fixed it eventually by modifying the user - also be careful about run only when user is logged in. If you choose administrator, make sure that isn't checked off. Also I didn't have much luck running wsl.exe directly from Task Scheduler - instead create a ps1 powershell wrapper script to call. Put the full path to Powershell (PS> gcm powershell), then add options -executionpolicy bypass -F "c:\path\to\your\wsl_run_script.ps1".

@eur2fe
Copy link

eur2fe commented Apr 17, 2023

also be careful about run only when user is logged in

The whole point of this ticket is to be able to run WSL2 in session 0, i.e. like a service without a console or GUI. This implies that the task scheduler option Run whether user is logged in or not is checked, as stated in the issue.

As a minimal repo, run the following commands in PowerShell:

$action = New-ScheduledTaskAction -Execute "C:\Windows\System32\wsl.exe" -Argument "-- touch ~/i-exist-so-i-ran"
Register-ScheduledTask -TaskName "Test WSL session 0" -User "NT AUTHORITY\SYSTEM" -Action $action
Start-ScheduledTask -TaskName "Test WSL session 0"

When you then look at the task status, it will indicate failure (error code 1):

PS C:\Windows\system32> Get-ScheduledTaskInfo -TaskName "Test WSL session 0"

LastTaskResult     : 1

Just confirmed that using the current WSL-Version: 1.2.0.0

@aki-k
Copy link

aki-k commented Apr 17, 2023

@eur2fe

Try defining the program to start as:

C:\Windows\System32\cmd.exe /k start "" /wait C:\Windows\System32\wsl.exe -d Ubuntu-20.04 -u WSL_username

I was able to start it automatically as a Windows service (#8835 (comment))

@eur2fe
Copy link

eur2fe commented Apr 18, 2023

@aki-k Thank you for your suggestion, but it does not work.

Using cmd /k leaves a dangling cmd.exe in session 0 behind, which may have tricked you into reasoning that wsl.exe is running (which it is not).

BTW: /dupe #9231

@aki-k
Copy link

aki-k commented Apr 18, 2023

reasoning that wsl.exe is running

Yes it's running automatically after boot, when started through a Windows service.

@eur2fe
Copy link

eur2fe commented Apr 18, 2023

Yes it's running automatically after boot, when started through a Windows service

I think you are using an old version of WSL. Can you post your wsl --version details? The current version is 1.2.0.0.

@aki-k
Copy link

aki-k commented Apr 18, 2023

@eur2fe I'm using that v1.2.4 that was just released a few days ago.

I seem to have skipped one important step in the setup process. You have to install the WSL2 Linux kernel update package for x64 machines from https://aka.ms/wsl2kernel

I did the install of wsl_update_x64.msi as the non-admin Windows user that is running the startwsl Windows service. Because I've removed local admin rights from the user running the service, the msi installer asks for the Administrator password.

There's still an issue with this kind of setup. If you login to Windows with that non-admin user account, its Ubuntu-20.04 WSL 2 instance will be shut down. You can still use "runas /profile /env /user:accountname cmd.exe" from another account to access it.

Now both sshd and tailscaled start automatically on boot in the WSL 2 Ubuntu VM and I can access the VM remotely.

@Irupt
Copy link

Irupt commented May 12, 2023

Hello, any news on this important bug?

I tried all the suggested solutions, none worked.

This is a core feature, keep us posted

@luffjr
Copy link

luffjr commented May 31, 2023

I also cannot get WSL2 running on system startup, Windows Server 2022 + WSL (1.1.3) + Ubuntu 20.04 LTS

I didn't use the Microsoft Store version, afaik, I just did wsl --install in powershell.

@eggachecat
Copy link

+1

@ghost
Copy link

ghost commented Jun 20, 2023

/dupe #9231

@microsoft-github-policy-service
Copy link
Contributor

Hi! We've identified this issue as a duplicate of another one that already exists in this repository. This specific instance is being closed in favor of tracking the concern over on the referenced thread.

Thanks for your report!

@astuomi
Copy link

astuomi commented Sep 27, 2023

For anyone who ends up finding this as the Google top search hit:

There is a fix in the WSL September 2023 update.

Steps to solve the issue:

  1. Upgrade WSL to the latest (pre-release) version with wsl --update --pre-release
  2. Point the Task Scheduler executable directly at "C:\Program Files\WSL\wsl.exe". IMPORTANT: There are multiple locations for the WSL executable with this update - the one under Program Files is the only one that will work. ¯\_(ツ)_/¯

Confirmed working for me on Win10 and WSL 2.0.1.

@mnpenner
Copy link

mnpenner commented Sep 28, 2023

Thanks @astuomi.

I tried this several times but whenever I manually ran the task like this:

image

The status would change to "Running" but it didn't seem to be doing anything at all.

It wasn't until I went back into Properties and used the "Browse" button to pick wsl.exe that it actually worked:

image

Copy-and-pasting "C:\Program Files\WSL\wsl.exe" does not work, despite the path being exactly the same.


Actually, Task Scheduler doesn't show the job as finished. My script seems to have finished because I can see the last line has finished executing, but Task Scheduler thinks it's still running. So it's still a bit sketchy but... we'll see if it works.

Edit: Seems to be working.

@D3vil0p3r
Copy link

D3vil0p3r commented Nov 9, 2023

@aGrimRepoMan

I see same issue with WSL1 on Windows 10 when running Windows Task Scheduler task
with program set to "C:\WINDOWS\System32\wsl.exe" and arguments set to
"-d Debian-BackupPC -u root service ssh start", i.e. without invoking intermediate
powershell or batch command file. Windows Task Scheduler previously
returned success code 0, but for several months now is returning 2147942401.

Try if these steps help:

  1. remove admin rights from the user running that scheduled task
  2. define the scheduled task program as:
C:\Windows\System32\cmd.exe /k start "" /wait C:\Windows\System32\wsl.exe -d Ubuntu-20.04 -u WSL_username

Edit: You might have to add "Log on as a batch job" permissions for the user running the task in:

secpol.msc: Security Settings/Local Policies/User Rights Assignment/Log on as a batch job

Edit 2: Log on as a batch job

When you use the Add Scheduled Task Wizard to schedule a task to run under a particular user name and password,
that user is automatically assigned the Log on as a batch job user right.

I'm using Windows Server 2022
I used this approach by creating a task directly on Task Scheduler application by using:

image

where, as test, in Add arguments I typed:

/k start "" /wait C:\Windows\System32\wsl.exe -d Ubuntu -u myuser sh -c "touch $HOME/test"

It keeps open due to /k. If I replace it by /c it turns to Ready state after running but the WSL distro is not started... I also tried by using a .cmd script called by the scheduled task containg cmd /k start "" /wait C:\Windows\System32\wsl.exe -d Ubuntu or cmd /c start "" /wait C:\Windows\System32\wsl.exe -d Ubuntu but WSL does not start (I check it by wsl -l --running.

@evvic
Copy link

evvic commented Feb 1, 2024

I read through this thread and almost gave up but I watched this tutorial and it just took a quick fix to get wsl command working for my scheduled task: https://www.youtube.com/watch?v=knA6JXOoJkE&ab_channel=BonGuides

@hilbix
Copy link

hilbix commented Feb 27, 2024

Actually two problems seem to have come together at my side:

  • Half of the solution was @cheng-chi
    • This started WSL2 before login
    • However SystemD stopped WSL after a few seconds again
  • The other half was the piece from @hammadrauf
    • By keeping the ugly terminal window open this way, WSL continues to run
    • This window shows up after login
    • If the window is closed, WSL2 shuts down a few seconds later
    • I do not know how to hide this window (because I do not care)

My settings are:

  • General
    • Change User or Group Administrators
      (With my German Windows it is Administratoren)
      (this is @cheng-chi)
    • Run with highest privileges
    • Note that the options to run on logon etc. are greyed out,
      so it runs when the machine boots up
  • Triggers
    • Run at system start
    • Delayed 30 seconds
    • Active
  • Actions
    • Start a program
    • Program: C:\Windows\System32\wsl.exe
    • Arguments: read
      (this is @hammadrauf)
  • Conditions
    • Everything unchecked except "run on power"
      ("Aufgabe nur starten, falls Computer im Netzbetrieb ausgeführt wird" in German Windows)
      (I only need WSL as a bridge when I am at home and the Laptop is docked)
  • Settings
    • Except for the first option everything else unchecked
      ("Ausführung der Aufgabe bei Bedarf zulassen" in German Windows)

With the settings above, WSL starts after boot right before login,
and allows me to fully control the Laptop (including login to Windows) from remote,
even that I am paranoied and hence no incoming connections are allowed at all.

wsl --version
WSL-Version: 2.0.9.0
Kernelversion: 5.15.133.1-1
WSLg-Version: 1.0.59
MSRDC-Version: 1.2.4677
Direct3D-Version: 1.611.1-81528511
DXCore-Version: 10.0.25131.1002-220531-1700.rs-onecore-base2-hyp
Windows-Version: 10.0.22631.3155
systeminfo

(excerpt)

Betriebssystemname:                            Microsoft Windows 11 Pro
Betriebssystemversion:                         10.0.22631 Nicht zutreffend Build 22631
Betriebssystemhersteller:                      Microsoft Corporation
Betriebssystemkonfiguration:                   Eigenständige Arbeitsstation
Betriebssystem-Buildtyp:                       Multiprocessor Free
Ursprüngliches Installationsdatum:             11.10.2022, 12:51:07
Systemstartzeit:                               27.02.2024, 13:05:32
Systemtyp:                                     x64-based PC
/etc/wsl.conf 

(excerpt)

[network]
generateHosts = false

[boot]
command = /etc/init.d/cron start
crontab -l
@reboot	bin/autostart.sh >/dev/null
* * * * * bin/autostart.sh >/dev/null

(autostart.sh is my way of autostarting things. It only needs cron and thus is completely agnostic to init.
It happend to work under WSL out of the box, too. Of course you can use your own favorite way
to start and keep things running, too.)

This is an example how it looks after a login into WSL via ssh:

debian:~$ pstree
init(Debian)─┬─SessionLeader───Relay(12)───bash
             ├─cron
             ├─init───{init}
             ├─ptybuffer───ssh
             ├─sshd─┬─sshd───sshd───bash───pstree
             │      └─sshd───sshd
             └─{init(Debian)}
  • The bash behind the Relay(12) is the ugly window.
  • ptybuffer is from my autostart.sh which was started by cron
  • The ssh is from the autostart script which initiates an outgoing ssh connect to allow to tunnel to the sshd
  • the sshd incoming connection without anything is from Remmina connecting to the VNC running under Windows

The only problem left is, that a logout on Windows closes the ugly window and hence WSL stops. However I think this can be corrected with Task Scheduler if I really need it.

@hisune
Copy link

hisune commented Apr 22, 2024

Actually two problems seem to have come together at my side:实际上,我身边似乎有两个问题同时出现:

  • Half of the solution was 解决方案的一半是@cheng-chi

    • This started WSL2 before login这在登录之前启动了 WSL2
    • However SystemD stopped WSL after a few seconds again然而 SystemD 在几秒钟后再次停止了 WSL
  • The other half was the piece from 另一半是来自@hammadrauf

    • By keeping the ugly terminal window open this way, WSL continues to run通过以这种方式保持丑陋的终端窗口打开,WSL 可以继续运行
    • This window shows up after login登录后出现此窗口
    • If the window is closed, WSL2 shuts down a few seconds later如果窗口关闭,WSL2 会在几秒后关闭
    • I do not know how to hide this window (because I do not care)我不知道如何隐藏这个窗口(因为我不在乎)

My settings are: 我的设置是:

  • General
     一般的
    • Change User or Group Administrators更改用户或组 Administrators
      (With my German Windows it is Administratoren) (对于我的德语 Windows,它是 Administratoren
      (this is @cheng-chi)  (这是 )
    • Run with highest privileges以最高权限运行
    • Note that the options to run on logon etc. are greyed out,请注意,登录时运行的选项等呈灰色显示,
      so it runs when the machine boots up 所以它会在机器启动时运行
  • Triggers
     触发器
    • Run at system start在系统启动时运行
    • Delayed 30 seconds 延迟30秒
    • Active 积极的
  • Actions
     行动
    • Start a program
    • Program: C:\Windows\System32\wsl.exe 程序: C:\Windows\System32\wsl.exe
    • Arguments: read 参数: read
      (this is @hammadrauf)  (这是 )
  • Conditions
     状况
    • Everything unchecked except "run on power"除了“依靠电源运行”之外,一切都未经检查
      ("Aufgabe nur starten, falls Computer im Netzbetrieb ausgeführt wird" in German Windows)(德语 Windows 中“仅当计算机在网络模式下运行时才启动任务”)
      (I only need WSL as a bridge when I am at home and the Laptop is docked)(当我在家并且笔记本电脑已连接时,我只需要 WSL 作为桥梁)
  • Settings
     设置
    • Except for the first option everything else unchecked除了第一个选项外,其他所有选项均未选中
      ("Ausführung der Aufgabe bei Bedarf zulassen" in German Windows)(德语 Windows 中“允许任务按需运行”)

With the settings above, WSL starts after boot right before login,通过上述设置,WSL 在启动后、登录前启动, and allows me to fully control the Laptop (including login to Windows) from remote,并允许我从远程完全控制笔记本电脑(包括登录 Windows), even that I am paranoied and hence no incoming connections are allowed at all. 即使我很偏执,因此根本不允许传入连接。

wsl --version
WSL-Version: 2.0.9.0
Kernelversion: 5.15.133.1-1
WSLg-Version: 1.0.59
MSRDC-Version: 1.2.4677
Direct3D-Version: 1.611.1-81528511
DXCore-Version: 10.0.25131.1002-220531-1700.rs-onecore-base2-hyp
Windows-Version: 10.0.22631.3155
systeminfo

(excerpt) (摘抄)

Betriebssystemname:                            Microsoft Windows 11 Pro
Betriebssystemversion:                         10.0.22631 Nicht zutreffend Build 22631
Betriebssystemhersteller:                      Microsoft Corporation
Betriebssystemkonfiguration:                   Eigenständige Arbeitsstation
Betriebssystem-Buildtyp:                       Multiprocessor Free
Ursprüngliches Installationsdatum:             11.10.2022, 12:51:07
Systemstartzeit:                               27.02.2024, 13:05:32
Systemtyp:                                     x64-based PC
/etc/wsl.conf 

(excerpt) (摘抄)

[network]
generateHosts = false

[boot]
command = /etc/init.d/cron start
crontab -l
@reboot	bin/autostart.sh >/dev/null
* * * * * bin/autostart.sh >/dev/null

(autostart.sh is my way of autostarting things. It only needs cron and thus is completely agnostic to init.( autostart.sh 是我自动启动的方式。它只需要 cron ,因此与 init 完全无关。 It happend to work under WSL out of the box, too. Of course you can use your own favorite way它也恰好可以在 WSL 下开箱即用。当然你可以用你自己喜欢的方式 to start and keep things running, too.) 也可以启动并保持运行。)

This is an example how it looks after a login into WSL via ssh:这是通过 ssh 登录 WSL 后的外观示例:

debian:~$ pstree
init(Debian)─┬─SessionLeader───Relay(12)───bash
             ├─cron
             ├─init───{init}
             ├─ptybuffer───ssh
             ├─sshd─┬─sshd───sshd───bash───pstree
             │      └─sshd───sshd
             └─{init(Debian)}
  • The bash behind the Relay(12) is the ugly window. Relay(12) 后面的 bash 是丑陋的窗口。
  • ptybuffer is from my autostart.sh which was started by cron ptybuffer 来自我的 autostart.sh ,它是由 cron 启动的
  • The ssh is from the autostart script which initiates an outgoing ssh connect to allow to tunnel to the sshd ssh 来自自动启动脚本,该脚本启动传出 ssh 连接以允许通过隧道连接到 sshd
  • the sshd incoming connection without anything is from Remmina connecting to the VNC running under Windows sshd 没有任何内容的传入连接来自 Remmina 连接到在 Windows 下运行的 VNC

The only problem left is, that a logout on Windows closes the ugly window and hence WSL stops. However I think this can be corrected with Task Scheduler if I really need it.剩下的唯一问题是,Windows 上的注销会关闭丑陋的窗口,因此 WSL 会停止。不过,我认为如果我确实需要的话,可以使用任务计划程序来纠正这个问题。

Not work for me

wsl version:  2.1.5.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
duplicate Store WSL Issue specific to WSL in the Microsoft Store
Projects
None yet
Development

No branches or pull requests