How can I enable a service such as OpenSSH server to start when WSL2 is started ? Currently I have to restart it every time WSL2 is started with sudo service ssh start.
- 28,025
- 603
1 Answers
The preferred way of running any service when WSL starts depends on your Windows version:
Windows 11
You can now execute an arbitrary command line when starting an instance by creating/editing /etc/wsl.conf (via sudo) with the following:
[boot]
command="service ssh start"
This command runs as root and generates no output. If you need to run multiple commands, they should be semicolon separated (or something like &&) inside the command= string.
Update: There appears to me to be a bug in this feature that will cause the WSL instance to terminate if it is not in use, even if the process started with the boot.command is still running. This may not be a problem for many users, as you may be running the instance anyway and notice or care if it stops when you exit the shell, but you should be aware of the behavior.
Windows 10
On WSL with Windows 10, you'll need to start the service via one of your user's shell startup scripts.
Use the following syntax in your ~/.bash_profile:
wsl.exe -u root service ssh status || wsl.exe -u root service ssh start
wsl.exe -u root has the advantage of not requiring the sudo password when starting up every time. From PowerShell and CMD, it can be called without the exe, but from within WSL it does require the extension.
Of course, you can also use sudoers to suppress the requirement for the password, but WSL just makes this unnecessary.
Note that this will generate one or two messages every time you start. To suppress this, use syntax such as:
wsl.exe -u root service ssh status > /dev/null || wsl.exe -u root service ssh start > /dev/null
Other options
These methods are for running commands when WSL starts, which is a fairly straightforward case. There are more complicated variations of this in other Super User questions that will:
- Run when the Windows user logs in
- Run when the Windows computer boots
- 28,025