Showing posts with label Ubuntu. Show all posts
Showing posts with label Ubuntu. Show all posts

Friday, 15 December 2017

Ubuntu - what do the colours in the console mean - Blue is Directory etc.

So I chanced upon a lovely Unix script which prints out a colour key in case a newbie is bamboozled by the coloured items. Copy the following in your terminal


eval $(echo "no:global default;fi:normal file;di:directory;ln:symbolic link;pi:named pipe;so:socket;do:door;bd:block device;cd:character device;or:orphan symlink;mi:missing file;su:set uid;sg:set gid;tw:sticky other writable;ow:other writable;st:sticky;ex:executable;"|sed -e 's/:/="/g; s/\;/"\n/g')           
{      
  IFS=:     
  for i in $LS_COLORS     
  do        
    echo -e "\e[${i#*=}m$( x=${i%=*}; [ "${!x}" ] && echo "${!x}" || echo "$x" )\e[m" 
  done       
} 

You will dark blue is a directory, normal file is white plus some others (run the script!)

Reproduced from Ask Ubuntu

Changing the bash prompt

So I really do not like so many colours in my bash prompt, here is an economical bash prompt that does not have colours and also does not have username and hostname.

PS1='\[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}bash :\w\$'

To ensure this happens on each logon I changed my .bashrc file using nano. It lives in the home directory ~ and is hidden by default.

cd ~
nano .bashrc

In nano add the PS1= line to the end, then attempt to exit, it will prompt for a save before exiting to which you say yes.

If you forget your password

Thankfully there is askubuntu.com and this answer works.

Changing the Ubuntu's Window Caption

So if I am making a video I do not want my user name and hostname appearing in the bash prompt (see above) or in the Ubuntu window's title. I'm sure it is configurable but I knew how to use a Windows API call to set the window caption and this code below will suffice. It's for a C# console.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;

namespace UbuntuWindowTitleRenamer
{
    class Program
    {
        [DllImport("user32.dll")]
        static extern bool SetWindowText(IntPtr hWnd, string text);

        [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

        [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
        static extern int GetWindowTextLength(IntPtr hWnd);

        static void Main(string[] args)
        {
            Process[] processes = null;
            string bashPrompt = Environment.GetEnvironmentVariable("BASH_WINDOW_TITLE_PREFIX");
            while (!Console.KeyAvailable)
            {
                processes = Process.GetProcessesByName("ubuntu");
                LoopThruProcesses(processes, bashPrompt);
                processes = Process.GetProcessesByName("bash");
                LoopThruProcesses(processes, bashPrompt);
            }
        }

        static void LoopThruProcesses(Process[] processes, string bashPrompt)
        {
            foreach (var procLoop in processes)
            {
                long ProcId = procLoop.Id;
                string hexProcId = ProcId.ToString("x8");

                {
                    List consoleWindows = Accessibility.GetConsoleWindowsByProcessId(ProcId);
                    foreach (IntPtr consoleWindow in consoleWindows)
                    {
                        int textLength = GetWindowTextLength(consoleWindow);

                        StringBuilder sb = new StringBuilder(textLength+1);
                        GetWindowText(consoleWindow, sb, sb.Capacity);

                        string windowCaption = sb.ToString();

                        if (windowCaption.StartsWith(bashPrompt))
                        {
                            string newCaption = "bash " + windowCaption.Substring(bashPrompt.Length);
                            SetWindowText(consoleWindow, newCaption);
                            Console.WriteLine("changing window caption:" + newCaption);
                        }
                    }
                }

                {
                    string originalCaption = procLoop.MainWindowTitle;
                    if (originalCaption.StartsWith(bashPrompt))
                    {
                        string newCaption = "bash " + originalCaption.Substring(bashPrompt.Length);
                        SetWindowText(procLoop.MainWindowHandle, newCaption);
                        Console.WriteLine("changing window caption:" + newCaption);
                    }
                }
            }
        }
    }

    public class Accessibility
    {
        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);

        [DllImport("user32.dll")]
        static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int processId);

        public static List GetConsoleWindowsByProcessId(long processId)
        {
            List retVal = new List();

            IntPtr hWnd = FindWindowEx(IntPtr.Zero, IntPtr.Zero, "ConsoleWindowClass", null);
            while (hWnd != IntPtr.Zero)
            {
                //Console.WriteLine("Window handle:" + hWnd.ToString("x8"));
                retVal.Add(hWnd);
                hWnd = FindWindowEx(IntPtr.Zero, hWnd, "ConsoleWindowClass", null);
            }
            return retVal;
        }
    }
}

Ubuntu (Windows Subsystem for Linux) Apache2 Configuration Overview

So Apache2 running on Ubuntu running on Windows Subsystem for Linux (WSL) on Windows 10 has a different configuration from other Apache2 installs. So there is a mismatch between documentation, if for example one is following Dedoimedo's Apache Web server Complete Guide. The config details are hiding in plain sight on the default index page that appears after a fresh install. Because we are meant to replace that page I am keeping a copy here.

Configuration Overview

Ubuntu's Apache2 default configuration is different from the upstream default configuration, and split into several files optimized for interaction with Ubuntu tools. The configuration system is fully documented in /usr/share/doc/apache2/README.Debian.gz. Refer to this for the full documentation. Documentation for the web server itself can be found by accessing the manual if the apache2-doc package was installed on this server.

The configuration layout for an Apache2 web server installation on Ubuntu systems is as follows:

/etc/apache2/
|-- apache2.conf
|       `--  ports.conf
|-- mods-enabled
|       |-- *.load
|       `-- *.conf
|-- conf-enabled
|       `-- *.conf
|-- sites-enabled
|       `-- *.conf
          
  • apache2.conf is the main configuration file. It puts the pieces together by including all remaining configuration files when starting up the web server.
  • ports.conf is always included from the main configuration file. It is used to determine the listening ports for incoming connections, and this file can be customized anytime.
  • Configuration files in the mods-enabled/, conf-enabled/ and sites-enabled/ directories contain particular configuration snippets which manage modules, global configuration fragments, or virtual host configurations, respectively.
  • They are activated by symlinking available configuration files from their respective *-available/ counterparts. These should be managed by using our helpers a2enmod, a2dismod, a2ensite, a2dissite, and a2enconf, a2disconf . See their respective man pages for detailed information.
  • The binary is called apache2. Due to the use of environment variables, in the default configuration, apache2 needs to be started/stopped with /etc/init.d/apache2 or apache2ctl. Calling /usr/bin/apache2 directly will not work with the default configuration.
Document Roots

By default, Ubuntu does not allow access through the web browser to any file apart of those located in /var/www, public_html directories (when enabled) and /usr/share (for web applications). If your site is using a web document root located elsewhere (such as in /srv) you may need to whitelist your document root directory in /etc/apache2/apache2.conf.

The default Ubuntu document root is /var/www/html. You can make your own virtual hosts under /var/www. This is different to previous releases which provides better security out of the box.

Ubuntu on WSL piping output to the host OS's drives - convert LFs to CRLFs

So continuing on the Ubuntu theme. I need to configure Apache. So I am not used to Linux because it has been a dozen years ago since I trained for certification on Linux. I still want to use my favourite Windows apps not mention the windowed environment; it takes a while to acclimatise to console culture. Specifically, whilst poking around the Linux file system, I need to find a way to pipe output of a command to a file on the host OS’s drive and then handle the line feed issue.

In Linux line feeds are one character ASC 10, whilst in Windows line feeds are in fact two, ASC 13 + ASC 10. If you don’t believe me then in VBA Immediate window try ?ASC(MID$(vbNewLine,1,1)) and then ?ASC(MID$(vbNewLine,2,1)) .

So in the Linux console a typical command would be sudo find / -name apache2.conf &> /mnt/n/findapache.txt which searches for Apache2 configuration file (it’s not where my Apache book says it should be!). The above command pipes output both stdout and stderr (hence “&>”) to /mnt/n which is where my N: drive is mounted into the unified Linux file system.

So here is some code to process the line feeds


Option Explicit

'* Tools->References->Microsoft Scripting Runtime

Sub Test()
    'ConvertLinuxLineFeedsToWindowsCRAndLineFeeds "n:\findapache.txt"
    ConvertLinuxLineFeedsToWindowsCRAndLineFeeds "n:\apache2.conf"
End Sub

Sub ConvertLinuxLineFeedsToWindowsCRAndLineFeeds(ByVal sLinuxFile As String, _
                        Optional ByVal sWindowsFile As String)

    sWindowsFile = Trim(sWindowsFile)
    If LenB(sWindowsFile) = 0 Then
        Dim vSplit As Variant
        vSplit = VBA.Split(sLinuxFile, ".")
        
        Dim lCount As Long
        lCount = UBound(vSplit)
        ReDim Preserve vSplit(0 To lCount + 1)
        vSplit(lCount + 1) = vSplit(lCount)
        vSplit(lCount) = "winLfCr"
        
        sWindowsFile = VBA.Join(vSplit, ".")
    
    End If

    Dim oFSO As New Scripting.FileSystemObject
    
    
    Debug.Assert oFSO.FileExists(sLinuxFile)
    Dim oTxtIn As Scripting.TextStream
    Set oTxtIn = oFSO.OpenTextFile(sLinuxFile)

    Dim oTxtOut As Scripting.TextStream
    Set oTxtOut = oFSO.CreateTextFile(sWindowsFile)

    While Not oTxtIn.AtEndOfStream
        Dim sLine As String
        sLine = oTxtIn.ReadLine
        Debug.Print sLine
        
        oTxtOut.WriteLine sLine
        
    Wend
    
    oTxtOut.Close
    oTxtIn.Close
    
    Set oTxtOut = Nothing
    Set oTxtIn = Nothing

End Sub


Now one can use Notepad to view the contents. Without the windows line feeds the whole file looks like it has no line breaks!

Wednesday, 13 December 2017

Installing Apache into Ubuntu running on Windows Subsystem for Linux on Windows 10

Part A - Installing WSL

So in the previous post I discussed the merits of Apache and whilst installable directly onto Windows 10 there is a good case for running it on Linux. But fortunately we don't have to thanks to a new component of Windows 10 called Windows Subsystem for Linux (Wikipedia article) (hereafter WSL) which is more lightweight than a fully virtualised machine (though a VM remains an option).

Microsoft's own documentation is here. To install one can follow instruction on this web page Microsoft - Install the Linux Subsystem on Windows 10 - Microsoft Docs. However, I can supplement with some extra info and a few screenshots because not everything is spelt out and indeed some of it I didn't follow at all :) .

To install 'Windows Subsystem for Linux' one needs to go to the Control Panel->Programs and Features->Turn Windows features on or off

Taking the above update requires a reboot.

Then I opened the Windows Store. Then I searched for Ubuntu and made sure to match the one shown on the Microsoft installation web page, the correct app is published by Canonical Group Limited. Then I clicked Install and it began downloading. Ubuntu is the leading leading distribution or "Distro". Once installed I pinned to Start menu and then clicked the Launch button. A command windows opens and the installation continues

After a while I get a prompt to create a new UNIX username which I did, on the first machine I tried this there was such a long dealy I though the process had hung, but please be patient it will get there. Then it asks for a password which I entered and then confirmed. then I am dropped into a console session. Yea! Try 'cd /' and then 'ls' to see the contents of your root folder.

Part B - Installing Apache

So next we install Apache, and I followed (roughly) the instructions from Digital Ocean and at the prompt I did the following

sudo apt-get update

sudo apt-get install apache2

this completes the install. Now we start the server with

sudo /etc/init.d/apache2 start

Then in a browser naviaget to

http://127.0.0.1

and one should see the Apache2 Ubuntu Default page

By the way, to fans of Virtual Machines (VMs) who are not convinced all I can say in parting is that I had to tidy a user profile of late because it grew massive and I discovered huge VM disk images. WSL allows the native disk filing system to be mounted so there is no need for a separate disk image with WSL.