bash

Start a not running process via cron

Written by  on Februar 24, 2017

Beispielcode zum Starten eines Prozesses, wenn diese nicht mehr Läuft. Direkt zur Verwendung in Cron.

#!/bin/bash

PROG="apache"
ps -ww aux | grep -v grep | grep $PROG >/dev/null 2>&1
if [[ $? -eq 0 ]]; then
  echo "$PROG found"
else
  echo "$PROG not found"
  # hier restart einfügen
fi

Achtung: Das Script einfach parametrisierbar zu machen via $1 statt $PROG funktioniert nicht, da $1 auch wieder von PS gefunden wird. Es wird daher immer der $PROG found Zweig durchlaufen!

bash select

Written by  on Februar 21, 2017

Die Bash enthält eine Funktion mit der sich ein einfaches Menü darstellen lässt.

#!/bin/bash
# Bash Menu Script Example

PS3='Please enter your choice: '
options=("Option 1" "Option 2" "Option 3" "Quit")
select opt in "${options[@]}"
do
    case $opt in
        "Option 1")
            echo "you chose choice 1"
            ;;
        "Option 2")
            echo "you chose choice 2"
            ;;
        "Option 3")
            echo "you chose choice 3"
            ;;
        "Quit")
            break
            ;;
        *) echo invalid option;;
    esac
done

http://askubuntu.com/questions/1705/how-can-i-create-a-select-menu-in-a-shell-script

Das hat aber ganz schön Nachteile. Alle Beispiele werden in einer Schleife abgewickelt, das brauche ich aber nicht, wenn ich nur einen Durchlauf haben möchte. Ausserdem muss ein Wert 3 Mal angegeben werden. Einmal in der Auflistung, einmal im Case zweig, und noch Einmal wenn ich mit dem Wert tatsächlich etwas anfangen will, wenn er gewählt wurde. Was also tun, um eine einfache Auswahl zu erzeugen, die sich auch einfach erweitern lässt?

Wir verwenden dazu ein Array:

# Warning ARRAY[0] is empty for boundary checking!!!
ARRAY[1]="aa"
ARRAY[2]="ab"

# Display array to screen
for (( i = 1; $i <= ${#ARRAY[@]}; i++ ))
do
  echo "Press $i for ${ARRAY[$i]}"
done

#Read input until we have a valid input
until [[ $input -gt 0 ]] && [[ $input -le ${#ARRAY[@]} ]]; do
  echo "Wert zwischen 1 und ${#ARRAY[@]} waehlen"
  read input
done

# Do what you like with your selection
X=${ARRAY[$input]}

Braucht man mehr Werte im Script, kann man das Array beliebig erweitern. Das könnte man in ein anderes File auslagern. Oder noch was einbauen, dass man eine Taste drücken muss nachdem eine Bildschirmseite ausgegeben wurde.

Aufräumen wenn ein Script abgebrochen wurde

Written by  on November 29, 2016
#!/bin/bash
TMPFILE1=$(mktemp /tmp/im1.XXXXXX)
TMPFILE2=$(mktemp /tmp/im2.XXXXXX)
trap "rm -f $TMPFILE1 $TMPFILE2; exit 1" INT
sleep 10

Frei nach How Linux Works, S. 264

From String to Array of Strings in Bash

Written by  on Oktober 13, 2016

Definition eines String:

STRING="A"

Definition eines Array:

STRING[0]="A"
STRING[1]="B"

oder

STRING="A"
STRING[1]="B"

Das heißt, nur mit STRING=“A“ kann noch nicht unterschieden werden, ob es nur ein String ist, oder ein Array. D.h. man kann eine bestehende Definition einfach weiterverwenden. Und auch, diese bei Bedarf einfach um ein zweites Feld erweitern.
Wie aber muss der Code aussehen, damit er von Haus aus mit der Erweiterung umgehen kann?

Feststellen der Anzahl der Elemente im Array

${#STRING[*]} 
COUNT=0
while [[ ${COUNT} -lt ${#STRING[*]} ]]; do 
  echo ${STRING[$COUNT]}; 
  COUNT=$((COUNT+1)); 
done

Output für

unset STRING

(kein Output)

Output für

STRING="a"
a

Output für

STRING="a"
STRING[1]="b"
a
b

Voraussetzungen: Elemente im Array von 0 weg zählend durchnummerieren. Das erleichtert das durchlaufen einer Zählschleife ungemein!

Windows und die Bash

Written by  on August 27, 2016

Spannende Zeiten! Microsoft gibt die Powershell frei für Linux. Und gleichzeitig gibt’s die Bash unter Windows 10.
Wie kommt man zur Shell? Die Installation geht recht einfach laut Anleitung.
Man braucht zumindest Windows 10 Anniversary Update build 14316, das prüft man am einfachsten mit „winver.exe“
Dann aktiviert man den Entwicklermodus. Einfach Windows Taste -> „Entwicklerfunktionen verwenden“
Als nächstes „Windows Features aktivieren oder deaktivieren“ und „Windows Subsystem for Linux (beta)“ wählen. Neustarten. Installation abschließen, indem der Befehl „bash“ ausgeführt wird.

VI Insert Mode and the Cursor Keys

Written by  on April 18, 2016

Wenn der Editor vi im Insert Mode mit den Pfeiltasten statt den Cursor zu bewegen die Buchstaben A, B, C und D ausgibt lässt sich das leicht beheben.

~/.vimrc

set nocompatible

Hitting arrow keys adds characters in vi editor – Ask Ubuntu

bash timeout

Written by  on Februar 14, 2016

Was tun, wenn man in einem Script nicht ewig auf einen externen Timeout warten möchte?
Wir rufen timeout auf. Das sieht z.B. so in einer Busy Box aus:
$ timeout -t 5 sleep 10
Terminated
$ echo $?
143

Hingegen auf einem Ubuntu 14.04 so:
$ timeout 2 sleep 5
$ echo $?
124

Auch wenn das nicht ganz einheitlich ist, doch ein tolles tool um z.B. curl nach ein paar Sekunden abzubrechen, wenn ein Download nicht funktioniert.

How to logrotate

Written by  on Januar 28, 2016

Just a short example of how some basic logrotate in bash could work:

# Logrotate with more than 5 Megabytes
LOGFILESIZE=$(stat -c%s "$LOGFILE")
if [[ $((LOGFILESIZE/1024/1024)) -gt 5 ]]; then
mv $LOGFILE $LOGFILE.old
fi

Testing OCSP

Written by  on Dezember 23, 2015

To test OCSP you need three things: The issuer certificate, the certificate you’d like to check and the path to the OCSP. All this information seems to be slightly redundant, as the certificate itself already contains the information about the OCSP URL and most of the time also the path to the issuer certificate. It would be very nice if openssl would read all this information from the certificate itself, nevertheless you need this three things to do some basic checks.
Get the required information from the AIA and download the issuer certificate:

[1]Authority Info Access
     Access Method=On-line Certificate Status Protocol (1.3.6.1.5.5.7.48.1)
     Alternative Name:
          URL=http://ocsp.startssl.com/sub/class1/server/ca
[2]Authority Info Access
     Access Method=Certification Authority Issuer (1.3.6.1.5.5.7.48.2)
     Alternative Name:
          URL=http://aia.startssl.com/certs/sub.class1.server.ca.crt

Write the request into a file

openssl ocsp -issuer startssl.cer -cert www.höllrigl.at.cer -no_nonce -url http://ocsp.startssl.com/sub/class1/server/ca -reqout ocsp.req

Convert the request to base64

openssl enc -in ocsp.req -out ocsp.req.b64 -a

The file should look something like this

MEswSTBHMEUwQzAJBgUrDgMCGgUABAR571c85Prvkggz7EWCVSbdzaAjFQQUFbqc
WolwWaxKVTlvLQA1YeCBz7MCChnePRMAAAAArhA=

Then you URL encode that file – you might use some free online decoder like http://meyerweb.com/eric/tools/dencoder/ – but here you have to remove the line breaks in advance. Or you do it directly at the shell

tr -d '\n' < ocsp.req.b64 | php -R 'echo urlencode($argn);'

Your output should look something like

MEswSTBHMEUwQzAJBgUrDgMCGgUABAR571c85Prvkggz7EWCVSbdzaAjFQQUFbqcWolwWaxKVTlvLQA1YeCBz7MCChnePRMAAAAArhA%3D

Now you can build your request to submit in a webbrowser or using curl at the shell.

curl http://ocsp.startssl.com/sub/class1/server/ca/MEswSTBHMEUwQzAJBgUrDgMCGgUABAR571c85Prvkggz7EWCVSbdzaAjFQQUFbqcWolwWaxKVTlvLQA1YeCBz7MCChnePRMAAAAArhA%3D --proxy http://path.to.proxy:8080 > ocsp.resp

With the output file you are able to verify the output with something like

openssl ocsp -respin ocsp.resp -text
OCSP Response Data:
    OCSP Response Status: successful (0x0)
...

Why all this effort, when openssl might do this on it’s own?
Just because openssl won’t work too well in an envrionment where a proxy is required.
The –proxy option seems only to work starting with version openssl 1.1

Alternatively you could also try telnet to connect via a proxy

telnet path.to.proxy 8080
CONNECT ocsp.startssl.com:80 HTTP/1.0
GET /sub/class1/server/ca/MEswSTBHMEUwQzAJBgUrDgMCGgUABAR571c85Prvkggz7EWCVSbdzaAjFQQUFbqcWolwWaxKVTlvLQA1YeCBz7MCChnePRMAAAAArhA%3D

But using curl and writing into a file might be more useful.

Compile OpenSSL

Written by  on Dezember 20, 2015

Most distributions contain only an old version of openssl. If you need a newer version for your scripts, ther often is no other way than compiling it from source. Here I’ll show you, how to do it. And don’t be afraid, it’s super easy! The latest version is a 1.1 development version.
There are only a few prerequisits: You need the packets make and gcc. First you download the source from github and unpack it:

wget https://github.com/openssl/openssl/archive/master.zip
unzip master.zip
cd openssl-master

You simply do the steps for compiling software on unix/linux:

./config
make
make install

You need to do at least the 3rd step as root, so it can install the files for you. By default, everything gets installed into /usr/local/ssl – so it won’t destroy your system OpenSSL.

# /usr/local/ssl/bin/openssl version
OpenSSL 1.1.0-pre2-dev  xx XXX xxxx

Have a lot of fun!