How to run a command on WSL startup using WSL config files? - bash

I added these lines in my WSL settings files
C:\Users\reynadan\.wslconfig:
[boot]
command=bash /home/reynadan/scripts/startup.sh
/etc/wsl.conf:
[boot]
command=bash /home/reynadan/scripts/startup.sh
/home/reynadan/scripts/startup.sh
#!/bin/bash
# Run wsl-vpnkit if not already connected or running
currentlyRunningWsl=$(wsl.exe -l --running | iconv -f UTF16 -t UTF8 | grep wsl-vpnkit | wc -l)
if [[ $currentlyRunningWsl -eq 0 ]]; then
wsl.exe -d wsl-vpnkit service wsl-vpnkit start
fi
# Start Docker daemon automatically when logging in if not running.
RUNNING=`ps aux | grep dockerd | grep -v grep`
if [ -z "$RUNNING" ]; then
sudo dockerd > /dev/null 2>&1 &
disown
fi
NOW=$(date)
echo WSL booted at $(/bin/date +'%Y-%m-%d %H:%M:%S') >> /home/reynadan/wslBootHistory.txt
echo 'startup lanched'
I closed with wsl --shutdown and waited more than 8 seconds before running it again, but /home/reynadan/wslBootHistory.txt is still empty and docker is not running.
How do I make sure WSL runs my script on startup?

As noted in the comments, you are on Windows 10. However, the information in the comments is a bit outdated -- The boot.command feature does now work on Windows 10, but you need the absolute latest release (including optional updates) of both Windows 10 and WSL installed.
First, confirm that your system is running the November "Cumulative Update Preview". If you are, then your UBR (update-build-revision) will be at 2311 or higher. From PowerShell:
(Get-ComputerInfo).WindowsUBR
If it is lower than 2311, then:
First, make sure your system is otherwise completely up-to-date.
Go to Settings -> Check for Updates and press the Check for Updates button.
If you are fully updated on Windows 10 (but still running less than UBR 2311) you should see "2022-11 Cumulative Update Preview for Windows 10 Version 22H2 for x64-based Systems (KB5020030)" available as an optional update. Install it and reboot when prompted.
With that in place, you should now be able to update to the Store version of WSL with a simple:
wsl --update
wsl --version
After the update, you should be at:
WSL version: 1.0.0.0
... or later.
A reboot at this point is recommended for all features to work properly, but not strictly required.
At this point, you should have access to the /etc/wsl.conf's [boot].command feature.
If for some reason it's still not working, then I would recommend removing the script from the equation to troubleshoot. Try something like command=service cron start and see if the Cron service starts when you restart WSL.
Note that this new update also brings a number of other new WSL2 features to Windows 10 users, including:
Systemd support
WSLg: The ability to run Linux GUI applications in WSL2
The --mount argument for adding additional Windows's drives and partitions (including those with other filesystems or even raw partitions).

Related

How to launch WSL as if I've logged in?

I have a WSL Ubuntu distro that I've set up so that when I login 4 services start working, including a web API that I can test via Swagger to verify it is up and working.
I'm at the point where what I want to do now is start WSL via a script - that is, launch my distro, have all of the services start, and do it from Python. The problem is I cannot even figure out the correct syntax to get WSL to start from PowerShell in a manner where my services start.
Side note: "services" != systemctl (or similar) calls, but just executing bash CLI commands from either my .bashrc or .profile at login.
I've put the commands to execute in .profile & .bashrc. I've configured it both for root execution and non-root user execution. I've taken the commands out of those 2 files and put it into a script in the Windows file system that I pass in on the start of wsl. And I've put that shell script in the WSL file system as well. Nothing seems to work, and sometimes the distro starts and then stops after about 30 seconds.
Some of the PS CLI commands I've tried:
Start-Job -ScriptBlock{ wsl -d distro -u root }
Start-Job -ScriptBlock{ wsl -d distro -u root 'bash -i -l -c /root/bin/start.sh'
Start-Job -ScriptBlock{ wsl -d distro -u root 'bash -i -l -c .\start.sh'
wsl -d distro -u root -- bash -i -l -c /root/bin/start.sh
wsl -d distro -u root -- bash -i -l -c .\start.sh
wsl -d distro -u root -- /root/bin/start.sh
Permutations of the above that I've tried: replace root with my default login, and turning all of the Start-Job bash options into a comma-separated list of single-quoted strings (Ex: 'bash', '-i', '-l', ... ). Nothing I launch from the CLI will allow me access to the web API that is supposed to be hosted on my distro.
Any advice on what to try next?
Not necessarily an answer here as much as troubleshooting tips which will hopefully lead to an answer:
First, most of the forms that you are using seem to be correct. The only ones that absolutely shouldn't work are those that attempt to run the script from the Windows filesystem.
Make sure that you have a shebang line starting your script. I'm assuming you do, but other readers may come across this as well. For the moment, try this form:
#!/usr/bin/env -S bash -li
That's going to have the same effect as the bash -li you tried -- It will source both both interactive startup files such as ~/.bashrc as well as login profiles such as ~/.bash_profile (and /etc/profile.d/*, etc.).
Note that preferably, you won't need the -li. Best practice would be to move anything necessary for the services over from the startup scripts to your start.sh script, and avoid parsing the profile and rc. I need to go update some of my answers, since I just realized I've been guilty of giving some potentially bad advice ...
Specifically, though, I'm wondering if your interactive Bash config has something truly, well, "interactive" in it that might be preventing the automatic running of the script itself. Again, best practice would be for ~/.bashrc to only hold configuration that is needed for interactive shell sessions.
Make sure the script is set as executable (chmod +x start.sh). Again, I'm assuming this is the case for you.
With a shebang line and an executable script, use something like:
wsl -d distro -u root -e /root/bin/start.sh
The -e tells WSL to launch the script directly. Since it has a shebang line, it will be parsed by Bash. Most of the other forms you use above actually run Bash twice - Once when launching WSL and another when it finds the shebang line in the script.
Try some basic troubleshooting for your script like:
Add set -x to the top (right under the shebang line) to turn on script debugging.
Add a ps -efH at the end to show the processes that are running when the script completes
If needed, resort to quick-and-dirty echo statements to show where things have progressed in the script.
I'm hopeful that the above will at least show you the problem, but if not, add the debugging info that you gain from this to your question, and we can troubleshoot further.

Using Chocolatey VS Code from within WSL Ubuntu

I cannot get VS Code code.exe to run properly within WSL. (I found a connected question here, but it does not solve this issue - Launch VS Code from WSL Bash).
Within WSL (any distro) we can access any executables on Windows. e.g.
alias chrome="\"/mnt/c/Program Files/Google/Chrome/Application/chrome.exe\"" # Open Chrome from WSL
alias notepad++="\"/mnt/c/Program Files/Notepad++/notepad++.exe\"" # Open Notepad++
Typing chrome in bash will open Chrome and notepad++ ~/.bashrc would open .bashrc in Notepad++
This all works great.
However, I have hit a problem with code.exe provided by the choco inst VisualStudioCode installation. When I try:
alias vscode="\"/mnt/c/ProgramData/chocolatey/bin/code.exe\""
This fails really badly.
[main 2021-01-24T18:44:17.966Z] update#setState idle
(node:20404) Electron: Loading non-context-aware native module in renderer: '\\?\C:\tools\vscode\resources\app\node_modules.asar.unpacked\vscode-sqlite3\build\Release\sqlite.node'. This is deprecated, see https://github.com/electron/electron/issues/18397.
(node:20404) Electron: Loading non-context-aware native module in renderer: '\\?\C:\tools\vscode\resources\app\node_modules.asar.unpacked\spdlog\build\Release\spdlog.node'. This is deprecated, see https://github.com/electron/electron/issues/18397.
(node:18692) Electron: Loading non-context-aware native module in renderer: '\\?\C:\tools\vscode\resources\app\node_modules.asar.unpacked\spdlog\build\Release\spdlog.node'. This is deprecated, see https://github.com/electron/electron/issues/18397.
So, I can ignore that and just use code.exe within Ubuntu (as WSL will scan the path for executables). This sort of works but with the following error:
'\\wsl$\Ubuntu-20.04\home\boss'
CMD.EXE was started with the above path as the current directory.
UNC paths are not supported. Defaulting to Windows directory.
VS Code does open, but if put a filename as an argument that file fails to open (while noting that for the notepad++ example, all files open perfectly run with the above alias).
It seems to be saying that code.exe can't support UNC paths, but it does support UNC paths as I can see from PowerShell. code.exe \\HPEnvy\Drive-D\test.txt opens perfectly.
It would really round out my WSL setup to be able to open code that I'm working on seamlessly with VS Code. Does anyone have an idea why this might be happening / how to fix?
My installation has a shell script for launching VSCode in ../Microsoft VS Code/bin/code. I'm fairly certain that it is installed with VSCode, but there's a chance it comes from the "Remote - WSL" extension.
Is that present in your installation? If so, add that bin directory to your path (the full installer does this automatically). Then just use code rather than code.exe to launch from within WSL.
If not, first make sure the "Remote - WSL" extension is installed in VSCode (or better yet, the "Remote Development" extension pack, which includes the WSL support). If it's still not there after that, here are the contents of the script that should live in VSCode/bin/code:
#!/usr/bin/env sh
#
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
if [ "$VSCODE_WSL_DEBUG_INFO" = true ]; then
set -x
fi
COMMIT="ea3859d4ba2f3e577a159bc91e3074c5d85c0523"
APP_NAME="code"
QUALITY="stable"
NAME="Code"
DATAFOLDER=".vscode"
VSCODE_PATH="$(dirname "$(dirname "$(realpath "$0")")")"
ELECTRON="$VSCODE_PATH/$NAME.exe"
IN_WSL=false
if [ -n "$WSL_DISTRO_NAME" ]; then
# $WSL_DISTRO_NAME is available since WSL builds 18362, also for WSL2
IN_WSL=true
else
WSL_BUILD=$(uname -r | sed -E 's/^[0-9.]+-([0-9]+)-Microsoft.*|.*/\1/')
if [ -n "$WSL_BUILD" ]; then
if [ "$WSL_BUILD" -ge 17063 ]; then
# WSLPATH is available since WSL build 17046
# WSLENV is available since WSL build 17063
IN_WSL=true
else
# If running under older WSL, don't pass cli.js to Electron as
# environment vars cannot be transferred from WSL to Windows
# See: https://github.com/microsoft/BashOnWindows/issues/1363
# https://github.com/microsoft/BashOnWindows/issues/1494
"$ELECTRON" "$#"
exit $?
fi
fi
fi
if [ $IN_WSL = true ]; then
export WSLENV="ELECTRON_RUN_AS_NODE/w:$WSLENV"
CLI=$(wslpath -m "$VSCODE_PATH/resources/app/out/cli.js")
# use the Remote WSL extension if installed
WSL_EXT_ID="ms-vscode-remote.remote-wsl"
ELECTRON_RUN_AS_NODE=1 "$ELECTRON" "$CLI" --locate-extension $WSL_EXT_ID >/tmp/remote-wsl-loc.txt 2>/dev/null </dev/null
WSL_EXT_WLOC=$(cat /tmp/remote-wsl-loc.txt)
if [ -n "$WSL_EXT_WLOC" ]; then
# replace \r\n with \n in WSL_EXT_WLOC
WSL_CODE=$(wslpath -u "${WSL_EXT_WLOC%%[[:cntrl:]]}")/scripts/wslCode.sh
"$WSL_CODE" "$COMMIT" "$QUALITY" "$ELECTRON" "$APP_NAME" "$DATAFOLDER" "$#"
exit $?
fi
elif [ -x "$(command -v cygpath)" ]; then
CLI=$(cygpath -m "$VSCODE_PATH/resources/app/out/cli.js")
else
CLI="$VSCODE_PATH/resources/app/out/cli.js"
fi
ELECTRON_RUN_AS_NODE=1 "$ELECTRON" "$CLI" "$#"
exit $?
Permissions on the file are 0777. And, as mentioned above, it should be in your path.

Mac Installer : How to determine if pkg installation is intercative

Mac Installer: I want to do something (popup dialog) in the postinstall script ONLY if it is an interactive installation. (not through MDM or command line)
How can I determine in my postinstall script if the installation is interactive or not?
Maybe will help to someone in the future:
There are 2 options:
(one can combine those 2 options to have full solutions, depends on its needs)
One of the environment variables set by macos installer is a flag COMMAND_LINE_INSTALL that is set to 1 in case of installer being executed from the terminal.
In my case I just had to check if COMMAND_LINE_INSTALL exists, if not - it means that this is interactive installation.
IMPORTANT: this environment variable exist and value=1 ONLY in case of installation from terminal(command line).
During installation from MDM this variable doesn't exist
=========================================================================
Another solution (that helps me determine if installation is from MDM or not):
From the post install script: run ps and check the existence of "/System/Library/CoreServices/Installer.app/Contents/MacOS/Installer"
If it exists- it means the installation is interactive (via mac installer app).
The lines I used:
INSTALLER_APP_PATH ="/System/Library/CoreServices/Installer.app/Contents/MacOS/Installer"
if ps aux | grep -v grep | grep -q "$INSTALLER_APP_PATH"
then
echo "Interactive installation"
else
echo "Not an interactive installation"
fi

How to resume cfn-init commands after reboot in linux - redhat 7.4?

Is it possible to resume cfn-init in Redhat linux after reboot?
I have cfn-hup and cfn-auto-reloader setup correctly. And I have 'reboot' as one of the commands. All the commands run perfectly till this reboot command. And after the machine comes back from reboot it does not resume the rest of the cfn-init commands. In windows there's 'WaitAfterCompletion' option. Is there anything as such in linux? Just wondering if I'm missing something here. Thanks!!
Overall, in linux, you shouldn't have to reboot within a script unless it is something like a kernel update. That being said,
Don't think cfn-init has a direct way to resume operation after reboot in linux, but you can use this linux workaround (using a file to resume script) and call it in your user-data to resume your remaining portion of cfn-init post reboot.
https://unix.stackexchange.com/questions/145294/how-to-continue-a-script-after-it-reboots-the-machine
I usually handle linux reboot with user-data, this is an example with amazon linux 2 but it should work with redhat as well.
UserData:
Fn::Base64: !Sub |
#!/bin/bash -xe
exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1
# update the system
yum update -y
# Check if kernel update requires a reboot, if yes it does reboot
needs-restarting -r ||
{
# reset user data so it processes again after reboot
rm -f /var/lib/cloud/instances/*/sem/config_scripts_user
echo rebooting ... $(date)
reboot
exit
}
# commands that run after reboot ...

How do you run a crontab in Cygwin on Windows?

Some cygwin commands are .exe files, so you can run them with the standard Windows Scheduler, but others don't have an .exe extension so can't be run from DOS (it seems like).
For example I want updatedb to run nightly.
How do I make cron work?
You need to also install cygrunsrv so you can set cron up as a windows service, then run cron-config.
If you want the cron jobs to send email of any output you'll also need to install either exim or ssmtp (before running cron-config.)
See /usr/share/doc/Cygwin/cron-*.README for more details.
Regarding programs without a .exe extension, they are probably shell scripts of some type. If you look at the first line of the file you could see what program you need to use to run them (e.g., "#!/bin/sh"), so you could perhaps execute them from the windows scheduler by calling the shell program (e.g., "C:\cygwin\bin\sh.exe -l /my/cygwin/path/to/prog".)
You have two options:
Install cron as a windows service, using cygrunsrv:
cygrunsrv -I cron -p /usr/sbin/cron -a -n
net start cron
Note, in (very) old versions of cron you need to use -D instead of -n
The 'non .exe' files are probably bash scripts, so you can run them via the windows scheduler by invoking bash to run the script, e.g.:
C:\cygwin\bin\bash.exe -l -c "./full-path/to/script.sh"
hat tip http://linux.subogero.com/894/cron-on-cygwin/
Start the cygwin-setup and add the “cron” package from the “Admin” category.
We’ll run cron as a service by user SYSTEM. Poor SYSTEM therefore needs a home directory and a shell. The “/etc/passwd” file will define them.
$ mkdir /root
$ chown SYSTEM:root /root
$ mcedit /etc/passwd
SYSTEM:*:......:/root:/bin/bash
The start the service:
$ cron-config
Do you want to remove or reinstall it (yes/no) yes
Do you want to install the cron daemon as a service? (yes/no) yes
Enter the value of CYGWIN for the daemon: [ ] ntsec
Do you want the cron daemon to run as yourself? (yes/no) no
Do you want to start the cron daemon as a service now? (yes/no) yes
Local users can now define their scheduled tasks like this (crontab will start your favourite editor):
$ crontab -e # edit your user specific cron-table HOME=/home/foo
PATH=/usr/local/bin:/usr/bin:/bin:$PATH
# testing - one per line
* * * * * touch ~/cron
#reboot ~/foo.sh
45 11 * * * ~/lunch_message_to_mates.sh
Domain users: it does not work. Poor cron is unable to run scheduled tasks on behalf of domain users on the machine. But there is another way: cron also runs stuff found in the system level cron table in “/etc/crontab”. So insert your suff there, so that SYSTEM does it on its own behalf:
$ touch /etc/crontab
$ chown SYSTEM /etc/crontab
$ mcedit /etc/crontab
HOME=/root
PATH=/usr/local/bin:/usr/bin:/bin:$PATH
* * * * * SYSTEM touch ~/cron
#reboot SYSTEM rm -f /tmp/.ssh*
Finally a few words about crontab entries. They are either environment settings or scheduled commands. As seen above, on Cygwin it’s best to create a usable PATH. Home dir and shell are normally taken from “/etc/passwd”.
As to the columns of scheduled commands see the manual page.
If certain crontab entries do not run, the best diagnostic tool is this:
$ cronevents
Just wanted to add that the options to cron seem to have changed. Need to pass -n rather than -D.
cygrunsrv -I cron -p /usr/sbin/cron -a -n
Applied the instructions from this answer and it worked
Just to point out a more copy paste like answer ( because cygwin installation procedure is kind of anti-copy-paste wise implemented )
Click WinLogo button , type cmd.exe , right click it , choose "Start As Administrator". In cmd prompt:
cd <directory_where_i_forgot_the setup-x86_64.exe> cygwin installer:
set package_name=cygrunsrv cron
setup-x86_64.exe -n -q -s http://cygwin.mirror.constant.com -P %package_name%
Ensure the installer does not throw any errors in the prompt ... If it has - you probably have some cygwin binaries running or you are not an Windows admin, or some freaky bug ...
Now in cmd promt:
C:\cygwin64\bin\cygrunsrv.exe -I cron -p /usr/sbin/cron -a -D
or whatever full file path you might have to the cygrunsrv.exe and
start the cron as windows service in the cmd prompt
net start cron
Now in bash terminal run
crontab -e
set up you cron entry an example bellow:
#sync my gdrive each 10th minute
*/10 * * * * /home/Yordan/sync_gdrive.sh
# * * * * * command to be executed
# - - - - -
# | | | | |
# | | | | +- - - - day of week (0 - 6) (Sunday=0)
# | | | +- - - - - month (1 - 12)
# | | +- - - - - - day of month (1 - 31)
# | +- - - - - - - hour (0 - 23)
# +--------------- minute
I figured out how to get the Cygwin cron service running automatically when I logged on to Windows 7. Here's what worked for me:
Using Notepad, create file C:\cygwin\bin\Cygwin_launch_crontab_service_input.txt with content no on the first line and yes on the second line (without the quotes). These are your two responses to prompts for cron-config.
Create file C:\cygwin\Cygwin_launch_crontab_service.bat with content:
#echo off
C:
chdir C:\cygwin\bin
bash cron-config < Cygwin_launch_crontab_service_input.txt
Add a Shortcut to the following in the Windows Startup folder:
Cygwin_launch_crontab_service.bat
See http://www.sevenforums.com/tutorials/1401-startup-programs-change.html if you need help on how to add to Startup. BTW, you can optionally add these in Startup if you would like:
Cygwin
XWin Server
The first one executes
C:\cygwin\Cygwin.bat
and the second one executes
C:\cygwin\bin\run.exe /usr/bin/bash.exe -l -c /usr/bin/startxwin.exe
The correct syntax to install cron in cygwin as Windows service is to pass -n as argument and not -D:
cygrunsrv --install cron --path /usr/sbin/cron --args -n
-D returns usage error when starting cron in cygwin:
$
$cygrunsrv --install cron --path /usr/sbin/cron --args -D
$cygrunsrv --start cron
cygrunsrv: Error starting a service: QueryServiceStatus: Win32 error 1062:
The service has not been started.
$cat /var/log/cron.log
cron: unknown option -- D
usage: /usr/sbin/cron [-n] [-x [ext,sch,proc,parc,load,misc,test,bit]]
$
Below page has a good explanation.
Installing & Configuring the Cygwin Cron Service in Windows:
https://www.davidjnice.com/cygwin_cron_service.html
P.S. I had to run Cygwin64 Terminal on my Windows 10 PC as administrator in order to install cron as Windows service.
Getting updatedb to work in cron on Cygwin -- debugging steps
1) Make sure cron is installed.
a) Type 'cron' tab tab and look for completion help.
You should see crontab.exe, cron-config, etc. If not install cron using setup.
2) Run cron-config. Be sure to read all the ways to diagnose cron.
3) Run crontab -e
a) Create a test entry of something simple, e.g.,
"* * * * * echo $HOME >> /tmp/mycron.log" and save it.
4) cat /tmp/mycron.log. Does it show cron environment variable HOME
every minute?
5) Is HOME correct? By default mine was /home/myusername; not what I wanted.
So, I added the entry
"HOME='/cygdrive/c/documents and settings/myusername'" to crontab.
6) Once assured the test entry works I moved on to 'updatedb' by
adding an entry in crontab.
7) Since updatedb is a script, errors of sed and find showed up in
my cron.log file. In the error line, the absolute path of sed referenced
an old version of sed.exe and not the one in /usr/bin. I tried changing my
cron PATH environment variable but because it was so long crontab
considered the (otherwise valid) change to be an error. I tried an
explicit much-shorter PATH command, including what I thought were the essential
WINDOWS paths but my cron.log file was empty. Eventually I left PATH alone and
replaced the old sed.exe in the other path with sed.exe from /usr/bin.
After that updatedb ran to completion. To reduce the number of
permission error lines I eventually ended up with this:
"# Run updatedb at 2:10am once per day skipping Sat and Sun'
"10 2 * * 1-5 /usr/bin/updatedb --localpaths='/cygdrive/c' --prunepaths='/cygdrive/c/WINDOWS'"
Notes: I ran cron-config several times throughout this process
to restart the cygwin cron daemon.

Resources