ITCooky Recipes

Lets cooky it yammy things!

How to use Linux on Windows through Windows Subsystem for Linux – with examples!

дата May 23, 2020

There is an opportunity to use Linux (almost 100%) through the built-in features of Windows 10! For what? For automation using console commands. Windows is called Windows (window) for a reason, because you have to do everything with your hands and eyes, although initially in the history of computers everything worked automatically with information on the console using commands and regular expressions. The size of the information is growing, the literacy of the users too, the complexity and the practicality of the tasks as well, and therefore, Microsoft has released Linux on Windows, because its PowerShell scripting language has not taken off, it is not multiplatform, It is closed, not widely used, so there are no working examples for every occasion! And in Linux, this is all there, because it has been used and developed for decades!

I will put Windows 10 on a virtual machine, that iso www.microsoft.com/en-us/ evalcenter / evaluate-windows-10-enterprise Works 90 days free! Incredibly freshly downloaded, she stays for an hour to update something

Well, if you read that you are already used to Windows, but that surprises me, every time I launch Windows, rarely!

When it starts, search for “Turn Windows Features”, in the past it was necessary you would also have to activate developer mode, but now it is not needed

Put a check in Windows Subsystem for Linux

Install via Microsoft store – Ubuntu 18.04 LTS Store

After installation, run Ubuntu 18.04 LTS through the program’s menu and it starts updating something, I’m sure that’s Windows influation!

It works!

Windows disk is mounted on Linux, you can go to it
cd /mnt/c
ls -l


here you can create a folder
mkdir ubuntu
from Windows it will look like a normal folder, you can write there

The begingng
I want to move a folder from a Linux machine to a Windows machine. How? Copy it to a USB flash drive and carry it on your feet – nope, it’s a computer, everything can be done on a computer without legs!

I have installed on a Linux machine
sudo apt install openssh-server

In Windows Ubuntu I go to the folder where I want to download
cd /mnt/c/ubuntu
And I download the necessary folder from the Linux machine
scp -r alexandr@192.168.1.13:/home/alexandr/Documents/nespi ./
Enter the password of the Linux machine and everything downloaded!

You can also put a file to Linux machine from Windows
scp ./somefile.txt alexandr@192.168.1.13:/home/alexandr/Documents/nespi
Now for example I need to find out the size of the file whose name is 001.jpg in this folder
I can do
ls -l
and look through the eyes

but why use my eyes, if I can order that they immediately give me a size of this file
So
ls -l | grep 001.jpg | awk '{print $5}'

And that is the console magic, you can make specific requests to the computer and receive specific responses, and all this in the form of commands, without pressing the mause button here, find the word with eyes etc, everything can be automated!

The line is simple. The first ls -l command ends with the | , which means that everything you issued goes to the following command. grep takes from this only the line where there is 001.jpg and launches it at the following command. awk takes fifth columns of this row, where exactly the file size is.

If you don’t want to see a number on the screen, write the size of all jpg files in one file, and have the name appear first
ls -l | grep .jpg | awk '{print $9" "$5" bytes"}' > list.txt

this is what we get in the list.txt file

raspberrypi_nespi_itcooky001.jpg 485839 bytes
raspberrypi_nespi_itcooky002.jpg 238575 bytes
raspberrypi_nespi_itcooky003.jpg 233167 bytes
raspberrypi_nespi_itcooky004.jpg 35420 bytes
raspberrypi_nespi_itcooky005.jpg 137017 bytes
raspberrypi_nespi_itcooky006.jpg 133464 bytes
raspberrypi_nespi_itcooky007.jpg 83661 bytes

If, for example, we want kilobytes instead of bytes, you can add this parameter to ls
ls -l --block-size=K| grep .jpg | awk '{print $9" "$5}' > list.txt

And you can do even more, through awk, add a math take number without decimals and without rounding
ls -l | grep .jpg | awk '{printf ("%s %d %s\n", $9, $5/1000, "Kbytes")}' > list.txt

raspberrypi_nespi_itcooky001.jpg 485 Kbytes
raspberrypi_nespi_itcooky002.jpg 238 Kbytes
raspberrypi_nespi_itcooky003.jpg 233 Kbytes
raspberrypi_nespi_itcooky004.jpg 35 Kbytes
raspberrypi_nespi_itcooky005.jpg 137 Kbytes
raspberrypi_nespi_itcooky006.jpg 133 Kbytes
raspberrypi_nespi_itcooky007.jpg 83 Kbytes

Look at awk instead of print this printf but it is an operator of C! First, describe where “” will be located, and then where to get these three values. %s is inserting a line, %d is taking only an integer, typing %.0f will also leave only an integer but will round what is after the decimal point. \n this sends to the next line!

We process all photos in the Linux console for Windows
There’s a folder with a bunch of photos and I want them all to be on the same HTML page for you to click and look once in the browser. Simple, useful, but how to do it? In console it is easy!

I first look to see if there is a bash shell command
bash –version

Show the version, it means there is!
If we write a file, we need some kind of editor … I use vi, there is also MC is both a file browser and an editor.

Install MC
sudo apt update
sudo apt install mc

run
mc
We select the file, at the bottom of the menu there is what to do with it, we exit F10

Create a fotogen.sh file with text

#!/bin/bash
echo "<html><body>" > foto.html
ls -l *.jpg | awk '{print "<img src="$9" width=100%>"}' >> foto.html
echo "</body></html>" >> foto.html

run
sh ./ftogen.sh
And we get a page with photos always shrunk or stretched to fit the page. If you don’t need to stretch, you should remove width = 100% . That’s so fast and easy, you don’t have to copy a line a hundred times and change a figure, like I did before getting console commands

And now I want the previews to appear, and the big images open with a click. You can automatically make small images in IrfanView is a good Windows program, but you can do it in console!

Install imagemagick
sudo apt-get install imagemagick

A very special program! I had to understand for a long time how to work with it as there are so many examples on the internet! The program is 29 years old, it is impossible to work with it using conventional console logic. There is a basic command to work with image conversion, but you don’t know how to write new file to new folder. There is another mogrify command and it is exactly the same as convert, it only knows how to write to a new folder, but it doesn’t work in pipe.

mogrify -path mini -resize 300 -quality 80 *.jpg

It puts in the mini folder, which is in the place where we are (generally for that you have to put ./ but not here), all the jpg change the size and quality
Here is the code ready to generate a thumbnail photo page

Create a fotogen2.sh file with text

#!/bin/bash
mkdir web ./web/mini
cp ./*.jpg ./web
mogrify -path web/mini -resize 300 -quality 80 ./web/*.jpg
echo "<html><body>" > ./web/foto.html
ls -l *.jpg | awk '{print "<a href=./"$9"><img src=./mini/"$9"></a>"}' >> ./web/foto.html
echo "</body></html>" >> ./web/foto.html

The script that we have is in the folder where there are images that we want to process, they all have the extension .jpg
launching

sh ./fоtogen2.sh
First we make two folders. Copy the first originals. We take the originals from the first and place the mini in the second. First we generate the page. It turns out that everything is in the web folder and the images and previews must be opened to see photo.html, the web folder can be taken with you or placed on a web server or file sharing

Monitor cartridge status on printers or printers
A typical task, suppose you have a hundred printers, and you want information about the cartridges hanging on the monitor wall, and somehow displayed!

I have a printer and not the most successful, or rather the most failed (I don’t consider OKI). I bought Kyocera FS 1125 MFP because I believed that its network, and it turned out that it can’t scan over network, there is no web interface. I thought it was Linux compatible – you can only print over the network if there are no Russian letters in the file name. Kyocera is a major corporate player, I think this spoiled him: He has stuck with some corporation forever and doesn’t want his products to be competitive. Do not buy!

You need to install snmp in WSL
sudo apt install snmp

You need to verify that snmp is enabled on the printer. To do this, go to the printer via USB with a special program. You can’t download it separately from the Kyocera website, but there is an ISO CD there, maybe it’s there …

I can still check it differently – if that command works
snmpwalk -v 2c -c public 192.168.1.2

It really works! I get a lot of parameters that the printer outputs via snmp! Its meaning is difficult to find. But you can guess, I know that now the printer has 11%, that the cartridge is for 1000 pages!

snmpwalk -v 2c -c public 192.168.1.2 1.3.6.1.2.1.43.11.1.1.9.1.1
Here it shows how many pages are left until the end – 110 is like 11%

snmpwalk -v 2c -c public 192.168.1.2 1.3.6.1.2.1.43.11.1.1.8.1.1
toner cartridge 1000

snmpwalk -v 2c -c public 192.168.1.2 1.3.6.1.2.1.43.11.1.1.6.1.1
cartridge name

snmpwalk -v 2c -c public 192.168.1.2 1.3.6.1.2.1.25.3.2.1.1.3.1
printer model name

I create a printers.data file with a description of printers where there will be a network name, ip, real name (the main thing is that it does not have spaces)

NetPrinter1 192.168.1.2 Low_Dep
NetPrinter2 192.168.1.2 Market_Dep
NetPrinter3 192.168.1.100 Food_Dep
NetPrinter4 192.168.1.2 KillersHR_Dep

I have a printer, so the IPs are repeated and there is an incorrect IP

Here is the code that polls the printers

#!/bin/bash

#get date
my_date=`date +%Y.%m.%d-%H:%M`

#collect new data from printers
filename="./printers.data"
rm ./snmp.data
 while IFS= read -r line
 	do
           print_ip=`echo ${line} | awk '{print $2}'`    
           print_net=`echo ${line} | awk '{print $1}'`
           print_dep=`echo ${line} | awk '{print $3}'` 
	   print_left=`snmpwalk -r 2 -t 2 -L n -c public -v 2c ${print_ip} 1.3.6.1.2.1.43.11.1.1.9.1.1 | awk '{print $4}'`
	    if [ -z "$print_left" ]
	    then
		    print_left="ERRROR"
	    fi

           print_resurce=`snmpwalk -r 2 -t 2 -L n -c public -v 2c ${print_ip} 1.3.6.1.2.1.43.11.1.1.8.1.1 | awk '{print $4}'`
	    if [ -z "$print_resurce" ]
            then
		    print_resurce="ERRROR"
      	   fi
           print_cartridge=`snmpwalk -r 2 -t 2 -L n -c public -v 2c ${print_ip} 1.3.6.1.2.1.43.11.1.1.6.1.1 | awk '{print $4}'`          
	   if [ -z "$print_cartridge" ]
             then
		     print_cartridge="ERRROR"
	    fi


	   echo "$print_net $print_ip $print_dep $print_left $print_resurce $print_cartridge" >> ./snmp.data


 done < "$filename"

If the printer does not respond – ERROR. SNMP waits a long time even for the -r option. The number of -t timeout attempts does not greatly reduce the wait.
These are the collected data, I specially included here the printer file data, so that later it is easier to show the information

NetPrinter1 192.168.1.2 Low_Dep 110 1000 "TK-1120S"
NetPrinter2 192.168.1.2 Market_Dep 110 1000 "TK-1120S"
NetPrinter3 192.168.1.100 Food_Dep ERRROR ERRROR ERRROR
NetPrinter4 192.168.1.2 KillersHR_Dep 110 1000 "TK-1120S"

Now I add to this script the part where the page will be generated
everything here

#!/bin/bash

#get date
my_date=`date +%Y.%m.%d-%H:%M`

#collect new data from printers
filename="/mnt/c/ubuntu/print/printers.data"
rm /mnt/c/ubuntu/print/snmp.data
 while IFS= read -r line
 	do
           print_ip=`echo ${line} | awk '{print $2}'`    
           print_net=`echo ${line} | awk '{print $1}'`
           print_dep=`echo ${line} | awk '{print $3}'` 
	   print_left=`snmpwalk -r 2 -t 2 -L n -c public -v 2c ${print_ip} 1.3.6.1.2.1.43.11.1.1.9.1.1 | awk '{print $4}'`
	    if [ -z "$print_left" ]
	    then
		    print_left="ERRROR"
	    fi

           print_resurce=`snmpwalk -r 2 -t 2 -L n -c public -v 2c ${print_ip} 1.3.6.1.2.1.43.11.1.1.8.1.1 | awk '{print $4}'`
	    if [ -z "$print_resurce" ]
            then
		    print_resurce="ERRROR"
      	   fi
           print_cartridge=`snmpwalk -r 2 -t 2 -L n -c public -v 2c ${print_ip} 1.3.6.1.2.1.43.11.1.1.6.1.1 | awk '{print $4}'`          
	   if [ -z "$print_cartridge" ]
             then
		     print_cartridge="ERRROR"
	    fi
	    print_porcent=`echo $((100*${print_left}/${print_resurce}))`
	    

	   echo "$print_net $print_ip $print_dep $print_porcent $print_left $print_resurce $print_cartridge" >> /mnt/c/ubuntu/print/snmp.data


 done < "$filename"

echo "<html>
<meta http-equiv=\"refresh\" content=\"65\">
<body>
<style>
body {
    background-color: #000000;
    }
    a:link, a:visited, .custom { 
        color: #ffffff;
}
h1 {
        color: #FF0000;
	font-size: 14px;
}
p {
    color: #ffffff;
    }
    </style>
    <p>Printers Data: update on $my_date</p>
    <table><tr><td width=120><p>Net name</p></td>
    <td width=120><p>Department</p></td>
    <td width=120><p>Cartridge</p></td>
    <td width=120 align=center><p>%</p></td></tr>" > /mnt/c/ubuntu/print/index.html
  
awk '{print "<tr><td width=120><a href=http://"$2" style=\"text-decoration: none\">"$1"</a></td><td width=120 bgcolor=#1d1e2a><p>"$3"</p></td><td width=120><p>"$7"</p></td><td align=center "} $4 >= 85 && $4 <= 100 { printf "bgcolor=#39901d"} $4 > 50 && $4 < 85 { printf "bgcolor=#37bb0c"} $4 <= 50 && $4 >30 { printf "bgcolor=#ADFF2F"} $4 <= 30 && $4 >15 { printf "bgcolor=#FFFF00"} $4 <= 15 && $4 >= 0 { printf "bgcolor=#ff0000"} {print " width=150>"$4"</td></tr>"}' /mnt/c/ubuntu/print/snmp.data >> /mnt/c/ubuntu/print/index.html    
echo "</table></html>" >> /mnt/c/ubuntu/print/index.html

ATTENTION: Here the relative paths ./ replaced with the absolute /mnt/c/ubuntu/print/ for cront to workb

The first part is slightly modified; the calculation of the percentage of the remaining print_porcent resource is added. The HTML page will refresh every 65 seconds, this is written to the second line of HTML. The fields with percentages of the remaining cartridge will be tinted in different colors according to this value. The network name is a link. So this image turns out

So try to get him into the local cron
crontab -e
add line

* * * * * sh /mnt/c/ubuntu/print/printers.sh

Cron in WSL is corrupted, must be started every time with hands and from root to work
sudo service cron start
sudo service atd start

You can even run this script from the Windows command line and try to insert it into your own Task Schedular
C:\Windows\System32\bash.exe -c "/bin/sh/ mnt/c/ubuntu/print/prinetrs.sh"

¡How to send an email warning when the cartridge reaches a low level!
For that you have to install
sudo apt-get install ssmtp
Customize the file, need root rights need to run
sudo mc
and edit /etc/ssmtp/ssmtp.conf

We only leave this text in the file, with our data

root=username@gmail.com
mailhub=smtp.gmail.com:465
rewriteDomain=gmail.com
AuthUser=username@gmail.com
AuthPass=password
FromLineOverride=YES
UseTLS=YES

Now go to your gmail account myaccount.google.com/security and under Security activate Unreliable applications that have account access

Now we make the letter file mail.txt

To: recipient_name@gmail.com
From: username@gmail.com
Subject: Sent from a terminal!

Hi this is only test just ignored. By the way i have bougth butter and cheese, can you next time buy it by yourself, you know i dont have a job and enough mony to buy all food needed!

ans send it
ssmtp recipient_name@gmail.com < mail.txt
It works!

Now a script that just takes the cartridge percentage, will compare, generate a letter and send it! I'll call the printmail.sh file

#!/bin/bash

#set warning cartridge level
cartridge_war=15
print_ip=192.168.1.2
to_email=recipient_name@gmail.com
from_email=username@gmail.com
#get date
my_date=`date +%Y.%m.%d-%H:%M`

#collect new data from printers
	   print_left=`snmpwalk -r 2 -t 2 -L n -c public -v 2c ${print_ip} 1.3.6.1.2.1.43.11.1.1.9.1.1 | awk '{print $4}'`
	    if [ -z "$print_left" ]
	    then
		    print_left="ERRROR"
	    fi

           print_resurce=`snmpwalk -r 2 -t 2 -L n -c public -v 2c ${print_ip} 1.3.6.1.2.1.43.11.1.1.8.1.1 | awk '{print $4}'`
	    if [ -z "$print_resurce" ]
            then
		    print_resurce="ERRROR"
      	   fi
	    print_porcent=`echo $((100*${print_left}/${print_resurce}))`

	    if [ $print_porcent -lt $cartridge_war ]
	    then
                 echo "To: $to_email\nFrom: $from_email\nSubject: Low toner\nLow carridge! Toner left $print_porcent%, and aprox $print_left pages to print.\nDate:$my_date" > /mnt/c/ubuntu/print/mail2.txt
                 ssmtp $to_email < /mnt/c/ubuntu/print/mail2.txt
	    fi

On the console, everything works! I insert it into Windows Task Scheduler. We will have to launch in Task Schedular
C:\Windows\System32\bash.exe -c "/bin/sh/ mnt/c/ubuntu/print/printmail.sh"

I go to Task Scheduler and menu in these windows like this


And it works! Even when no one is logged in, you can leave the Windows computer on and everything will work!


Leave a Reply

Your email address will not be published. Required fields are marked *