Kommentierte Beispielskripte

Post Reply
Message
Author
User avatar
Lateralus
prolinux-forum-admin
Posts: 1238
Joined: 05. May 2004 7:35

Kommentierte Beispielskripte

#1 Post by Lateralus »

In diesem Thread sollen kommentierte Beispielskripte gesammelt werden, welche Einsteigern einen besseren Einblick in die Shell-Programmierung (vorzugsweise Bash, aber auch gerne andere Skriptsprachen, welche von der Shell aus aufgerufen werden können) ermöglicht.

Über rege Teilnahme würden wir uns sehr freuen!


edit: Die Skripte sollten in einer Shell ausführbar sein.Die Betonung sollte auf der bash (oder bourne-shell-kompatible) liegen, aber ich sehe keinen Grund, warum hier nicht auch andere solche Skriptsprachen stehen könnte.
Last edited by Lateralus on 30. Nov 2005 12:35, edited 1 time in total.

User avatar
killerhippy
Posts: 529
Joined: 19. May 2000 19:36
Contact:

#2 Post by killerhippy »

Von meinen Scriptereien könnte ich einiges einpflegen, aber wie wär's, wenn du zuvor eine Aufteilung in Scriptsprachen mächtest?
Es gibt keine dumme Fragen!

Killerhippy

User avatar
killerhippy
Posts: 529
Joined: 19. May 2000 19:36
Contact:

Bash Shell Script: mp3fill.sh um meinen USB-Stick-MP3Player zu füttern

#3 Post by killerhippy »

Hi,

das folgende Script ist gefährlich!

Es löscht Dateien!

Vor einem Einsatz muss es editiert werden!

Das folgende Script dient zur Ansicht und ist nicht in der Absicht veröffentlicht, ausgeführt zu werden - wer das tut, tut das in Eigenverantwortung ohne mein Einverständnis. Eventueller Schaden, der durch die Ausführung des Scriptes oder von Teilen desselben entsteht, ensteht durch die Person, die es ausführbar gemacht und zum Einsatz gebracht hat, deswegen nicht durch mich und ich hafte daher auch nicht für entstandenen Schaden, sondern die Person, die es zur Ausführung gebracht hat!

Code: Select all

#!/bin/bash
###############################################################################
# mp3player-fill.sh                                                           #
#                                                                             #
# Erases all mp3 files found at $DEST and refills $DEST's root dir with files #
# from $SOURCE.                                                               #
#                                                                             #
#                   Right, this script erases data!!!!                        #
#                   !!!!!!   Use at own risk  !!!!!!!!                        #
#                                                                             #
# You have do decide if you use automount or real mount points for the $DEST  #
# check being plugged in. See "# check target being checked in".              #
# The default is automount with /misc as root.                                #
#                                                                             #
# BTW: I have not set paths but hardcoded absolute paths to the executables.  #
# You have to check for yourself, wether they fit to your system.             #
# Read the source, Luke.                                                      #
#                                                                             #
# Author:       Sascha Wuestemann                                             #
# Email :       develop@killerhippy.de                                        #
# Version:      0.0.1                                                         #
# Licence:      GPL                                                           #
# Date:         2005-08-04                                                    #
#                                                                             #
# Needs rl, try to find the author if your package system doesn't have it.    #
# rl is to shuffle the mp3 files found at $SOURCE.                            #
# rl's autor is Arthur de Jong <arthur@tiefighter.et.tudelft.nl>              #
# &#40;taken from /usr/local/src/rl-0.2.0/AUTHORS&#41;                                #
###############################################################################

/bin/echo "I refuse to erase your data!"
exit 0

# slightly enhanced comments for http&#58;//www.pro-linux.de
# all paths to executables are hardcoded which I prefer, check for your system, if they 
# don't fit change the code.

# function checkenv&#58;
# check df of $DEST and Existenz of $FILE not null
check_env &#40;&#41; &#123;
        ERRORCODE=5
        DF=`/bin/df -h $DEST | /usr/bin/tail -n 1 | /bin/sed -e 's/  */ /g' | \
        /bin/cut -d ' ' -f 5`
        if &#91; -s "$&#123;FILE&#125;" &#93;; then
                ERRORCODE=0
        else
                echo "$&#123;FILE&#125;"
        fi
        if &#91; $DF == "100%" &#93;; then
                ERRORCODE=10
        fi

&#125;

# function rm_last
# if we went here, the file last copied hasn't fit onto the $DEST, so let's
# remove it.
rm_last &#40;&#41; &#123;
        # note that there is the number one and not the letter l for the ls options!
        LASTFILE=`ls -1rt $DEST | /usr/bin/tail -n 1`
        rm "$&#123;DEST&#125;/$&#123;LASTFILE&#125;"
        exit 0
&#125;

# Main

# varibles set
# Be careful!
# Edit your local settings here!
# SOURCE is safe, it is the place where files are copied from
# DEST is the target, where files are destroyed !!!!!!!!!!!!!

SOURCE="/misc/landisk/mp3"
DEST="/misc/mp3"

# check target being checked in
# you have to be shure and take only one of both
# if DEST is not plugged in, the script terminates &#40;automount&#41;
# if DEST is not mounted, the script terminates &#40;mountpoints&#41;
# the following is for automount only, e.g. /media/usb
/bin/df $DEST 1>/dev/null 2>&1 || exit 0
# the following is for mountpoints only, e.g. /mnt/mp3
#/bin/mount | /bin/grep -q $DEST || exit0


# clean the target from mp3 files. Directories itselves are not touched.
/usr/bin/find $DEST -iname '*.mp3' -exec /bin/rm &#123;&#125; \;

# collect data and copy
/usr/bin/find $SOURCE -iname '*.mp3' -print | /usr/local/bin/rl | \
while read FILE ; do
        check_env
        # DEST is full
        if &#91; $ERRORCODE -eq 10 &#93;; then
                exit 0
        # source file is not zero byte
        elif &#91; $ERRORCODE -ne 5 &#93;; then
                /bin/cp "$&#123;FILE&#125;" $DEST 2>/dev/null || rm_last
        fi
done
exit 0
Ich habe eine cronjob, der nachts läuft. Wenn der Player am USB-Port hängt, kommt da neue Musik drauf. Der Automounter ist natürlich entsprechend konfiguriert...
Es gibt keine dumme Fragen!

Killerhippy

zulu911

#4 Post by zulu911 »

n diesem Thread sollen kommentierte Beispielskripte gesammelt werden, welche Einsteigern einen besseren Einblick in die Shell-Programmierung (vorzugsweise Bash, aber auch gerne andere Skriptsprachen, welche von der Shell aus aufgerufen werden können) ermöglicht.
Hallo.
Vielleicht sollte man die Skripte dann auch teilweise erklären damit Anfänger verstehen was da gemacht wird, und vor allem warum.

Das ist zwar eher kein Einsteiger-Kurs über Shellprogrammierung, doch man soll ja begreifen was da passiert. Erfahrungen sammeln warum manche das so machen und manche so.
So habe ich das zumindest verstanden.
Ansonsten gute Idee!

Das man nicht erklärt ...

Code: Select all

# Hier das ist eine Funktion
        rm_last &#40;&#41; &#123; 
        LASTFILE=`ls -1rt $DEST | /usr/bin/tail -n 1` 
        rm "$&#123;DEST&#125;/$&#123;LASTFILE&#125;" 
        exit 0 
&#125; 
ist ja klar, wie gesagt.

Script it ....

Cu

User avatar
killerhippy
Posts: 529
Joined: 19. May 2000 19:36
Contact:

mondoarchive

#5 Post by killerhippy »

Zum Nikolaus gibt es ein wertvolles Geschenk :D

Ein Script, um Backups vom laufenden System zu erstellen unter Verwendung von mondoarchive.
Die entstandenen ISO-Dateien müssen nur noch selbst gebrannt werden. Von der ersten kann gebootet und dann z.B. interaktiv restauriert werden. Für weitergehende Informationen siehe http://www.mondorescue.org/.

Natürlich ist dieses Script nur zur Ansicht, wer es zur Ausführung bringt, trägt die Verantwortung über alle Folgen selbst.

Code: Select all

#!/bin/sh

###############################################################################
#                                                                             #
# sysbackup.sh is using mondoarchive                                          #
#                                                                             #
# - creates iso-files for systembackup, see "setting variables" for your      #
#   local settings.                                                           #
# - different exit values allow you to start and observe this script from a   #
#   master script, see the source, Luke.                                      #
# - can be executed by cron.                                                  #
# - it does not check for existing files at target and will overwrite them if #
#   they exist without asking.                                                #
#                                                                             #
# Author&#58;       Sascha Wuestemann                                             #
# Email &#58;       develop@killerhippy.de                                        #
# Version&#58;      0.0.1                                                         #
# Licence&#58;      GPL                                                           #
# Date&#58;         2005-12-05                                                    #
#                                                                             #
###############################################################################

# setting variables
DATE="/bin/date +%F_%H-%M-%S"
SCRIPT_START=`$&#123;DATE&#125;`
THIS_MACHINE=`/bin/uname -n`
FIND="/usr/bin/find"
MONDO="/usr/sbin/mondoarchive"
MONDO_ROOT="/mnt/nfs"
MBR_DEV="hda"

# default setting is to place everything, tmp files, too, to the target dir.
FIND_WHERE="$&#123;MONDO_ROOT&#125;/$&#123;THIS_MACHINE&#125;/$&#123;SCRIPT_START&#125;"
MONDO_OUT="-d $&#123;FIND_WHERE&#125;"
MONDO_PRE="-S $&#123;FIND_WHERE&#125;"
MONDO_TMP="-T $&#123;FIND_WHERE&#125;"
# unfortunately setting "-E \"/dir1 /dir2\"" does not work
# so I have to split the options line, one half here, the other at the command.
MONDO_EXC="/mnt /daten /daten1 /daten2 /tmp /proc"
# see the manpage of mondoarchive if you don't know the following options.
MONDO_OPT="-Oi -9 -s 680m -N -F"
# end of setting variables

# start up message
echo "$&#123;0&#125;&#58; **** starting backup of $&#123;THIS_MACHINE&#125; ****"
echo "$&#123;0&#125;&#58; **** at $&#123;SCRIPT_START&#125;"

# precautions

# does the MBR_DEV exist and is a special block file?
if &#91; ! -b /dev/$&#123;MBR_DEV&#125; &#93;; then
        echo "$&#123;0&#125;&#58; !!!! $&#123;MBR_DEV&#125; is no block device or does not exist. FIXME !!!!"
        exit 1
fi

# does the target root directory exist?
if &#91; ! -d $&#123;MONDO_ROOT&#125; &#93;; then
        echo "$&#123;0&#125;&#58; !!!! $&#123;MONDO_ROOT&#125; does not exist. FIXME !!!!"
        exit 2
fi

# does the target directory exist or do we have to create it?
if &#91; ! -d $&#123;FIND_WHERE&#125; &#93;; then
        if /bin/mkdir -p $&#123;FIND_WHERE&#125;
        then
                echo "$&#123;0&#125;&#58; **** $&#123;FIND_WHERE&#125; directory created ****"
        else
                echo "$&#123;0&#125;&#58; !!!! fatal $&#123;FIND_WHERE&#125; error. FIXME !!!!"
                exit 3
        fi
fi

# if the target directory already exists, maybe we can not write to it?
FILE="$&#123;FIND_WHERE&#125;/.sysbackup-testfile.$$"
if /usr/bin/touch $&#123;FILE&#125;
then
        echo "$&#123;0&#125;&#58; **** I can modify files at $&#123;FIND_WHERE&#125;, good. ****"
        /bin/rm $&#123;FILE&#125;
        unset FILE
else
        echo "$&#123;0&#125;&#58; !!!! fatal $&#123;FILE&#125; error. FIXME !!!!"
        exit 4
fi

# execute backup
if $&#123;MONDO&#125; $&#123;MONDO_OPT&#125; $&#123;MONDO_OUT&#125; $&#123;MONDO_PRE&#125; $&#123;MONDO_TMP&#125; \
-E "$&#123;MONDO_EXC&#125;"
then
        echo "$&#123;0&#125;&#58; **** backup was succesfull ****"
else
        echo "$&#123;0&#125;&#58; !!!! fatal backup error. FIXME !!!!"
        exit 5
fi

# clean up, mondoarchive v2.04 forgets about deleting the work directory.
$&#123;FIND&#125; $&#123;FIND_WHERE&#125; -type d -path "$&#123;FIND_WHERE&#125;/mondo*" -exec rmdir &#123;&#125; \;

# backup of MBR
if /bin/dd if=/dev/$&#123;MBR_DEV&#125; of=$&#123;FIND_WHERE&#125;/$&#123;MBR_DEV&#125;.mbr bs=512 count=1
then
        echo "$&#123;0&#125;&#58; **** mbr of /dev/$&#123;MBR_DEV&#125; saved succesfully. ****"
else
        echo "$&#123;0&#125;&#58; !!!! fatal dd error of /dev/$&#123;MBR_DEV&#125;. FIXME !!!!"
        exit 6
fi

SCRIPT_STOP=`$&#123;DATE&#125;`

# final message
echo "$&#123;0&#125;&#58; **** backup of $&#123;THIS_MACHINE&#125; has been finished ****"
echo "$&#123;0&#125;&#58; **** at $&#123;SCRIPT_STOP&#125; ****"

Das Erzeugen der MBR-Datei ist wahrscheinlich unnötig und kommt ja auch nicht auf die CDs, ist aber good to have im even more worst case :wink:

P.S.: Wer es als cronjob einsetzt, möchte vielleicht echo durch /usr/bin/logger ersetzten, denn mondoarchive ist sehr verbose.
Es gibt keine dumme Fragen!

Killerhippy

User avatar
killerhippy
Posts: 529
Joined: 19. May 2000 19:36
Contact:

remrem.pl remove remarks Perl Script

#6 Post by killerhippy »

Wer sich z.B. schon mal die squid.conf angeschaut hat, wird dieses Script lieben! :wink:

Code: Select all

#!/usr/bin/perl -w
#
##########################################################################
#                                                                        #
# remrem.pl, a perl-script to watch e.g. config files with a lot of lines#
# starting with a "#" &#40;remarks&#41; or blank lines without them, to watch    #
# only the important lines, indeed, them which are active.               #
#                                                                        #
# Two output possiblities&#58;                                               #
#                                                                        #
# - STDOUT just for watching                                             #
# - pipe to a file for getting rid of those wastings.                    #
#                                                                        #
# put it to /usr/local/bin, the standard place for new executables.      #
#                                                                        #
# artistic GPL, author&#58; Sascha Wuestemann 2001, augest                   #
# Version&#58; 1.00, verified to work by and for me &#58;&#41;                       #
# Mail&#58; develop@killerhippy.de                                           #
# send diffs, if wonderful, else don't                                   #
# I don't take any garantie nor do I pay for harm this script might do   #
# use at own risk!                                                       #
#                                                                        #
# published being convinced that it is useful ;&#41;                         #
#                                                                        #
##########################################################################

sub usage &#123;
print "\n\nWhat the hell is this? It is \'REMoveREMarks\'\!\n\nremrem.pl deletes blank lines  or lines starting with a \'\#\' from a given file-one and prints it to STDOUT or writes i
t to file-two\n\nSyntax &#58;\n\n $0 inputfile\n\# STOUT, try $0 inputfile \| less\n\n $0 inputfile outputfile \n\# Output tho <outputfile>\n\n";
&#125;

if &#40;
    &#40;! $ARGV&#91;0&#93;            &#41; or
    &#40;  $ARGV&#91;0&#93; eq "--help"&#41;
   &#41; &#123;
 usage;
 exit;
&#125;

open&#40;FUN,"<$ARGV&#91;0&#93;"&#41;||die "Can't open file $ARGV&#91;0&#93; for reading";

if &#40;$ARGV&#91;1&#93;&#41; &#123;
    open&#40;GUN,">>$ARGV&#91;1&#93;"&#41;||die "Can't open file $ARGV&#91;1&#93; for writing"
&#125;

foreach $zeile &#40;<FUN>&#41; &#123;
       $zaehler++;
       if &#40;
           &#40; ! &#40;$zeile=~/^\s*&#91;#;&#93;+/ &#41; &#41; and
           &#40; $zeile=~/\w/&#41;
          &#41; &#123;
             if &#40;$ARGV&#91;1&#93;&#41; &#123;
                 print GUN $zeile
             &#125;
             else &#123;
                   print "$zaehler&#58; $zeile" 
                  &#125;
       &#125;
&#125;
if &#40;$ARGV&#91;1&#93;&#41; &#123;
    close&#40;GUN&#41;||die "Can't close filehandle $ARGV&#91;1&#93;."
&#125;
close&#40;FUN&#41;||die "Can't close filehandle $ARGV&#91;0&#93;."
Last edited by killerhippy on 20. Dec 2005 1:44, edited 1 time in total.
Es gibt keine dumme Fragen!

Killerhippy

User avatar
killerhippy
Posts: 529
Joined: 19. May 2000 19:36
Contact:

mp3play.sh

#7 Post by killerhippy »

mp3play.sh ist völlig überflüssig. Braucht kein Mensch. Kann mpg123 auch alleine. Hat aber Spass gemacht :wink:

Code: Select all

#!/bin/bash
###############################################################################
# uses rl -  Randomize Lines written by Arthur de Jong!                       #
#                                                                             #
# mp3play.sh                                                                  #
# plays mp3 files ordered or randomly from a default or given source.         #
#                                                                             #
# Author&#58;       Sascha Wuestemann                                             #
# Email&#58;        develop@killerhippy.de                                        #
# Version&#58;      0.0.2                                                         #
# License&#58;      GPL                                                           #
# Date&#58;         2005-12-19                                                    #
###############################################################################

usage &#40;&#41; &#123;
        echo "Usage&#58; $0 &#91;OPTIONS&#93;"
        echo -e "  -z\t\tshuffle"
        echo -e "  -s <source>\tsource to be played. Can be a file or directory.
"
        echo "With no options, shuffle is unset and source is /misc/landisk/mp3"
&#125;

# Defaults
SHUFFLE_CMD=/bin/cat
SOURCE=/misc/landisk/mp3
PLAY=/usr/bin/mpg123-3dnow

# Defaults ovewritten by optional parameters
while getopts "hzs&#58;" OPTIONS; do
        case $OPTIONS in
                "z" &#41; SHUFFLE_CMD=/usr/local/bin/rl;;
                "s" &#41; SOURCE=$OPTARG;;
                "h" &#41; usage; exit 1;;
                *   &#41; usage;exit 1;;
        esac    
done

# mixed up options?
case "$SOURCE" in
        "z" &#41; usage;exit 1;;
        "-z" &#41; usage; exit 1;;
esac

# unset IFS in case of directories or filenames containing whitespaces
# in their names. No restore of IFS nescessary here.
IFS=""
find "$SOURCE" -iname '*.mp3' -print | $SHUFFLE_CMD | while read FILE ; do
        if &#91; -s "$&#123;FILE&#125;" &#93;; then
                echo "Now playing&#58; $FILE"
                echo ""
                $PLAY -y "$&#123;FILE&#125;"
                sleep 1
        else
                echo "File seems empty&#58;"
                echo "$&#123;FILE&#125;"
        fi
done
exit 0
Es gibt keine dumme Fragen!

Killerhippy

User avatar
killerhippy
Posts: 529
Joined: 19. May 2000 19:36
Contact:

hdautocap.sh

#8 Post by killerhippy »

Noch so'n script, dass nicht besonders brilliant und auch nicht ausgesprochen schön, aber für die Konsolenjunkies vielleicht interessant ist.

Code: Select all

#!/bin/sh
###############################################################################
# hdautocap.sh                                                                #
# shows capabilities of ide drives and set's them to max value.               #
# Author&#58;       Sascha Wuestemann                                             #
# Email&#58;        develop@killerhippy.de                                        #
# Version&#58;      0.0.1                                                         #
# License&#58;      GPL                                                           #
# Date&#58;         2005-12-20                                                    #
###############################################################################

usage &#40;&#41; &#123;
        echo "Usage&#58; $0 &#91;OPTIONS&#93;"
        echo -e "  -q\t\tquery drive."
        echo -e "  -s\t\tset drive to its capabilties."
        echo -e "  -h\t\tthis page."
        echo -e "  -d &#91;drive&#93;\tdefine drive, e.g. $DRIVE"
&#125;

check_drive &#40;&#41; &#123;
        echo -n "checking drive&#58; "
        if &#91; ! -b /dev/$DRIVE &#93;; then
                echo "bad"
                echo "Error&#58; /dev/$DRIVE is no block device"
                usage
                exit 1
        else
                echo "good"
                MODEL=`cat /proc/ide/$DRIVE/model`
                echo "Modell&#58; $MODEL"
        fi

&#125;

query_drive &#40;&#41; &#123;
        # from IDE
        CAPS=/proc/ide/$DRIVE/settings
        echo -n "querying drive $DRIVE&#58;"
        io_32bit_val=`cat $CAPS | grep io_32bit | sed 's/  */ /g' | \
        cut -d ' ' -f 2`
        io_32bit_cap=`cat $CAPS | grep io_32bit | sed 's/  */ /g' | \
        cut -d ' ' -f 4`
        io_32bit_rwv=`cat $CAPS | grep io_32bit | sed 's/  */ /g' | \
        cut -d ' ' -f 5`

        multcount_val=`cat $CAPS | grep multcount | sed 's/  */ /g' | \
        cut -d ' ' -f 2`
        multcount_cap=`cat $CAPS | grep multcount | sed 's/  */ /g' | \
        cut -d ' ' -f 4`
        multcount_rwv=`cat $CAPS | grep multcount | sed 's/  */ /g' | \
        cut -d ' ' -f 5`

        using_dma_val=`cat $CAPS | grep using_dma | sed 's/  */ /g' | \
        cut -d ' ' -f 2`
        using_dma_cap=`cat $CAPS | grep using_dma | sed 's/  */ /g' | \
        cut -d ' ' -f 4`
        using_dma_rwv=`cat $CAPS | grep using_dma | sed 's/  */ /g' | \
        cut -d ' ' -f 5`

        wcache_val=`cat $CAPS | grep wcache | sed 's/  */ /g' | \
        cut -d ' ' -f 2`
        wcache_cap=`cat $CAPS | grep wcache | sed 's/  */ /g' | \
        cut -d ' ' -f 4`
        wcache_rwv=`cat $CAPS | grep wcache | sed 's/  */ /g' | \
        cut -d ' ' -f 5`

        echo " done."
&#125;

query_out &#40;&#41; &#123;
        echo "printing out&#58;"
        echo -e "device\tcapabilty\tcurrent\tmode\tmaxval"
        echo -e "$DRIVE\tio_32bit\t$io_32bit_val\t$io_32bit_rwv\t$io_32bit_cap"
        echo -e "$DRIVE\tmultcount\t$multcount_val\t$multcount_rwv\t$multcount_cap"
        echo -e "$DRIVE\tusing_dma\t$using_dma_val\t$using_dma_rwv\t$using_dma_cap"
        echo -e "$DRIVE\twcache\t\t$wcache_val\t$wcache_rwv\t$wcache_cap"
&#125;

set_drive &#40;&#41; &#123;
        echo "setting drive&#58; $DRIVE"
        # from HDPARM
        if &#91; "rw" == "$io_32bit_rwv" &#93;; then
                $HDPARM -c $io_32bit_cap /dev/$DRIVE
        fi
        if &#91; "rw" == "$multcount_rwv" &#93;; then
                $HDPARM -m $multcount_cap /dev/$DRIVE
        fi
        if &#91; "rw" == "$using_dma_rwv" &#93;; then
                $HDPARM -d $using_dma_cap /dev/$DRIVE
        fi
        # the following sets the write cache if available
        # comment or delete, if you don't like it
        if &#91; "rw" == "$wcache_rwv" &#93;; then
                $HDPARM -W $wcache_cap /dev/$DRIVE
        fi
        # no choice to test, so lets jump into the cold water
        $HDPARM -X34 /dev/$DRIVE
&#125;

# Path
HDPARM=/sbin/hdparm

while getopts "qshd&#58;" OPTIONS; do
        case $OPTIONS in
                "d" &#41; DRIVE=$OPTARG;;
                "q" &#41; ORDER="query_drive";;
                "s" &#41; ORDER="set_drive";;
                "h" &#41; usage; exit 0;;
                *    &#41; usage; exit 1;;
        esac
done

if &#91; ! -e $CAPS &#93;; then
        echo "Kernel variables for $DRIVE not available."
        exit 1
fi

if &#91; ! $DRIVE &#93;; then
        echo "Error&#58; No drive given!"
        usage
        exit 1
else
        check_drive
        if &#91; ! "$ORDER" &#93;; then
                echo "but no action-ERROR!"
                usage
                exit 1
        fi

fi

if &#91; "query_drive" == "$ORDER" &#93;; then
        query_drive
        query_out
fi

if &#91; "set_drive" == "$ORDER" &#93;; then
        query_drive
        set_drive
fi

exit 0
Es gibt keine dumme Fragen!

Killerhippy

User avatar
killerhippy
Posts: 529
Joined: 19. May 2000 19:36
Contact:

wetter.sh

#9 Post by killerhippy »

Diesmal eine Auftragsarbeit von viewtopic.php?t=1028804&highlight=:

Das Script:

Code: Select all

#!/usr/bin/perl
#
# mit den folgenden Zeilen in der .procmailrc löscht dieses script die
# Werbung aus der Mail und stellt sie einem lokalen User zu&#58;
#
# ~.procmailrc
# &#58;0 c
# # avoid mail loops
# * !^X-Loop&#58; your_account@someFQDN
# * Subject&#58; Ihr persoenlicher Wetterletter*
# | formail -A "X-loop&#58; your_account@someFQDN" \
# | /home/username/bin/wetter.sh | /usr/sbin/sendmail -oi username@localhost

$ok=1;
$merker=-1;
        # Werbung ist von je einer Zeile "+"s eingeschlossen.
        # Wir drucken, solange die erste nicht gekommen ist.
        # Danach drucken wir solange nicht, bis die naechste da ist
        # und drucken die aktuelle Zeile nicht, danach drucken wir
        # wieder.
        # Am Ende der Mail kommt nach der Verabschiedung wieder
        # Werbung, daher drucken wir nur bis dahin.
while&#40;<STDIN>&#41; &#123;
        if &#40; $_=~ m/^\+/ &#41; &#123;
                $merker++;
                if &#40; ! $merker &#41; &#123;
                        $ok=0
                &#125;
                else &#123;
                        $ok=1;
                        next;
                &#125;
        &#125;
        print if $ok;
        if &#40; $_=~ m/Ihre wetter.com Redaktion/ &#41; &#123;
                exit;
        &#125;
&#125;
close&#40;STDOUT&#41; || die "STDOUT could not be closed\n";
Im /home/username/bin/wetter.sh abgespeichert sieht die /home/.procmailrc bei mir (beinahe) so aus:

Code: Select all

&#58;0
# avoid mail loops
* !^X-Loop&#58; your_account@someFQDN
* To&#58; your_account@someFQDN
| formail -A "X-loop&#58; your_account@someFQDN" \
| /home/username/bin/wetter.sh | /usr/sbin/sendmail -oi username@localhost
Edited 2006-01-05: Obige Zeilen entsprechen meiner persönlichen Konfiguration, weil ich mir den letter an einen Email-Alias schicken lasse. Leute, die nur eine Emailadresse haben, für die sie keinen Alias einrichten können, müssen auf das subject treffen lassen, siehe oben im script. /Edited 2006-01-05
Das im Script für die .procmail zusätzlich angegebene kleine c weisst procmail an, das Ergebnis zu kopieren, so dass am Ende die Orignalmail und die geänderte zugestellt werden. Ohne c wird die Orignalmail verworfen und nur die geänderte Mail zugestellt. Es wird mittels formail ein zusätlicher X-Header eingefügt, damit procmail keine Endlosschleifen erzeugt. Die Mail wird durch eine Reihe von pipes geschickt und landet am Ende bei sendmail.

Das Script arbeitet mit STDIN und STDOUT, deswegen muss sendmail aka exim (or whatever) zum nochmaligen senden bemüht werden. Sofern der Empfänger ein lokaler user ist, findet dann eine lokale Zustellung statt, eine richtige Emailadresse kann auch angegeben werden, dann findet (wenn der MTA das kann) die Zustellung dorthin statt.

Rechtlicher Hinweis: Das Verändern des Bodytextes fremder Email ist nach meinem Kenntnisstand verboten! Der Einsatz ist deshalb nur für die eigene Mail erlaubt.

Hinweis zur Kompatibilität: Es funktioniert, solange man die Wetternachrichten als Textmail bekommt, HTML-Mail habe ich mir nicht angeguckt, da müsste wohl das pattern matching angepasst werden und solange die Mail in der z.Z. der Programmierung vorliegenden Struktur versendet wird.

Warum Perl? Nun, wie man sieht, ist Perl ein mächtiges Textwerkzeug, daher brauchte ich nicht lange überlegen, besonders weil mir nicht schnell einfallen wollte, wie man das wohl in bash machen könnte. Vielleicht postet ja ein bash-guru das Pendent?

Für den Einsatz ist ein funktionierender MTA, z.B. exim notwendig, procmail, formail und Perl.
Es gibt keine dumme Fragen!

Killerhippy

User avatar
killerhippy
Posts: 529
Joined: 19. May 2000 19:36
Contact:

sipgate voip status Wechsel mailen

#10 Post by killerhippy »

Der Voice-over-IP Dienstleister Sipgate, http://www.sipgate.de bietet ja an, nach einem Login oder durch Einbau von HTML-Code z. B. auf der eigenen Homepage Kenntnis über den Online-Status bei Sipgate zu erlangen. Das ist nett aber nicht bequem und so habe ich mir was ausgeklügelt, um Statuswechsel mit der Benennung des aktuellen Status mailen zu lassen.

Wie's funktioniert:
Das Script hat lokal beide Versionen der Status-Grafiken im Arbeitsverzeichnis gespeichert. Beim ersten Aufruf werden zwei Kopien der bei Sipgate aktuell downloadbaren Grafik in /tmp gespeichert. Sie dienen als Referenz um Aussagen über alten und neuen Status zu machen. Ab jetzt wird bei einem Aufruf die aktuelle Grafik von Sipgate geholt und ersetzt die aktuelleste Referenzdatei. Wenn sich aktuelleste und ältere Referenzdatei unterscheiden, hat es einen Statuswechsel gegeben und das script kopiert die aktuelleste Referenzdatei nach der älteren Referenzdatei, danach prüft es, ob die aktuelle Referenzdatei der im Arbeitsverzeichnis vorliegenden Online- oder Offline-Grafik gleicht und kann so den neuen Status ermitteln und meldet dies.
Wenn es nichts zu melden gibt, gibt es auch keine Ausgabe. Wenn die Grafik von Sipgate nicht geholt werden kann, gibt es eine Warnung. Danach keine weiteren bis zum nächsten Statuswechsel.
Statusänderungen ohne Download der Grafik von Sipgate können mangels Glaskugeldevice nicht festgestellt werden. :wink:
Im Zweifel musst Du Dich selbst auf Deiner Sipgate-Nummer anrufen! :)

Wenn du dieses Script nutzen möchtest, brauchst du also noch drei zusätzliche Dinge, die ich hier nicht zur Verfügung stellen kann und die Dir bereitstehen, wenn Du Dich bei Sipgate eingeloggt hast:
  • URL
    Online-Grafik
    Offline-Grafik
Im "Status" Kasten rechts in der "Endgerät (Details): online <grafik>" Zeile kannst du auf Details oder auf die Grafik klicken und es poppt ein neues Fenster auf. Hier findest du den HTML-Code, für dieses Script brauchst du nur den URL der in doppelten Anführungszeichen steht, den kopierst du in eine Datei mit Namen "url". Weiter brauchst du noch die blaue (für online) und graue (fuer offline) Version der Grafik, die durch diesen URL den aktuellen Zustand abbildet und speicherst die Datei jeweils unter offline-Voip.gif und online-Voip.gif. Wenn du den URL schon in der Datei "url" gespeichert hast, geht das ganz einfach durch

Code: Select all

wget -O <dateiname> `cat url`
Du musst also selbst dafür sorgen, dass Du neben den Online-Status und der dazugehörigen Datei einen Offline-Status provozierst und die dazugehörige Datei bekommst.
BTW: Doppelte Anführungszeichen indizieren hier etwas und sind nicht Bestandteil des Indizes!
BTW2: Einfache Anführungszeichen sind backtickets und wenn du nicht weisst was das ist, hilft dir die Suche danach hier und bei $suchmachine!
FYI: Der Link sieht ziemlich kryptisch aus:
http://www.sipgate.de:<portnummer>/<Unterverzeichnis>/<Dateiname>
wobei Unterverzeichnis und Dateiname aus lauter alphanumerischen Zeichen (Zahlen und Buchstaben) bestehen, er zielt aber auf eine GIF-Grafik.

Die Mailfunktion habe ich nicht eingebaut, wenn man das Script in der vorliegenden Form als cronjob aufruft, bekommt man automatisch Mail, wenn's was zu melden gibt.
Wie der cronjob einzurichten ist, steht in den ersten Zeilen des scripts als Bemerkung.
Wenn du das nicht möchtest, lies den Code und passe die echo-Ausgaben an und lösche ggfs die semaphoren-Datei bezogenen Zeilen, dies script ist aus einer Abfrage/Ausgabe-Version hervorgegangen und die Anpassung hat Vorlagen, sollte also nicht allzu schwierig sein...

Wenn Fragen auftauchen, die Du alleine nicht lösen kannst, schreib' mir eine Mail, wenn's von allgemeinen Interesse ist, mache ich eine FAQ.

Code: Select all

#!/bin/sh
#
# check_voip-status.sh
#
# Info&#58;
# Makes use of the GIF sipgate offers to be shown e. g. at your homepage.
# Get the information by logging in and click at your status picture. Extract
# the url and copy it to the file named url this script uses.
# Also download the GIF for online and offline-status from sipgate and name
# them to online-Voip.gif and offline-Voip.gif
# These three files must be placed at the same directory as this script
# Put them to an own directory e.g. to bin/voip at your home directory.
#
# Function&#58;
# checks current VoIP status and compares with the state before.
# If state has changed it is printed else not.
# If current state GIF cannot be fetched, a warning is printed once until
# it is available again and unavailable thereafter.
# Can be part of a cronjob&#58;
#    # check VoIP status changes
#    */5 * * * *        /home/killerhippy/bin/voip/check_voip-status.sh
# This checks every 5 minutes.
# If used this way, you get mail if the status has changed.
# If used at the command line, it prints nothing or the status change
# information or the warning if your GIF is not available, but only the first
# time and once again if status has changed and becomes unavailable again - this
# is to avoid mass mails if used by cronjob.
#
# files in this directory&#58;
# offline-Voip.gif      673 bytes GIF when offline
# online-Voip.gif       1072 bytes GIF when online
# url                   contains url to get GIF from your sipgate account
#
# files being placed by this script in /tmp&#58;
# /tmp/voip-status/                     own directory to separate from others
# /tmp/voip-status/old_current.gif      old state indicating GIF
# /tmp/voip-status/very_current.gif     current state indicating GIF
# /tmp/voip-status/status_not_available GIF currently not available semaphore
#
# Author &#58; Sascha Wuestemann
# Version&#58; 0.1
# Date   &#58; 2006-04-11
# Licence&#58; GNU GPL v2 see http&#58;//www.gnu.org if not enclosed.

# change to working directory
# adjust if nescessary
cd ~/bin/voip/

# subcommand to get GIF saved as by given name
GET_GIF &#40;&#41; &#123;
        wget -O /tmp/voip-status/$1 --quiet `cat url` 
&#125;

# make own directory if nescessary
if &#91; ! -d /tmp/voip-status &#93;; then
        mkdir /tmp/voip-status
fi

# check for existence of old_current GIF, if not there get it
if &#91; ! -e /tmp/voip-status/old_current.gif &#93;; then
        if GET_GIF old_current.gif; then
                echo "fetched initial GIF" >/dev/null
                if &#91; -e /tmp/voip-status/status_not_available &#93;; then
                        rm /tmp/voip-status/status_not_available
                fi
                cp /tmp/voip-status/old_current.gif \
                /tmp/voip-status/very_current.gif
        else
                if &#91; ! -e /tmp/voip-status/status_not_available &#93;; then
                        touch /tmp/voip-status/status_not_available
                        echo "Initial VoIP status not available"
                        exit 1
                else
                        exit 0
                fi
        fi
fi

# get current GIF or warn
if GET_GIF very_current.gif; then
        echo "fetched current GIF" >/dev/null
        if &#91; -e /tmp/voip-status/status_not_available &#93;; then
                rm /tmp/voip-status/status_not_available
        fi
else
        if &#91; ! -e /tmp/voip-status/status_not_available &#93;; then
                touch /tmp/voip-status/status_not_available
                echo "Current VoIP status not available"
                exit 1
        else
                exit 0
        fi
fi

# check differences between GIFs
if diff /tmp/voip-status/old_current.gif \
/tmp/voip-status/very_current.gif > /dev/null ; then
        echo "Status has not changed." >/dev/null
else
        cp /tmp/voip-status/very_current.gif /tmp/voip-status/old_current.gif
        echo "Current VoIP status has changed"
        if diff /tmp/voip-status/very_current.gif \
        online-Voip.gif >/dev/null ; then
                echo "New status&#58; We are online"
        fi
        if diff /tmp/voip-status/very_current.gif \
        offline-Voip.gif >/dev/null; then
                echo "New status&#58; We are offline"
        fi
fi

exit 0

Es gibt keine dumme Fragen!

Killerhippy

User avatar
Lateralus
prolinux-forum-admin
Posts: 1238
Joined: 05. May 2004 7:35

#11 Post by Lateralus »

Ich möchte an dieser Stelle mal killerhippy für sein Engagement danken.

Post Reply