scripts.team-holm.net
Hovedsiden
BASH Scripts


Legger ved her noen svært enkle script her.

  • mount_DVD.sh - et av mine første script i BASH.
  • removeService.sh - egentlig litt overflødig og Det er egentlig også feil å fjerne tjenester på denne måten.
  • start-stop-rTorrent.sh - kan settes opp som en cron-jobb til å stoppe og starte rtorrent som en tjeneste.
  • rTorrent som tjeneste - ikke mitt script, men linker til her til info.
  • Valve-HLDS - er for å starte en Half-Life Dedicated Server installert i Linux som en tjeneste.
  • start-node.sh - starter en node server som en tjeneste. Se kommentarer for installasjon.
  • registerWithSpaceWalk.sh - for automatisk registrering mot SpaceWalk.

  • Det meste som er delt her er delt for artighets skyld, og kanskje også som enkle eksempler på syntaks.

    start-stop-rTorrent.sh
    #!/bin/bash
    
    HOUR=`date +%H`
    DATE=`date`
    HIT=0
    
    if [ $HOUR -eq 22 ]; then
       /etc/init.d/rtorrent start 2>> /var/log/startStopTorrent.log >> /var/log/startStopTorrent.log
       if [ $? -gt 0 ]; then
          echo "${DATE} - Running script at hour: ${HOUR}" >> "/var/log/startStopTorrent.log"
          echo "${DATE} - Failed starting rTorrent" >> "/var/log/startStopTorrent.log"
       else
          echo "${DATE} - Running script at hour: ${HOUR}" >> "/var/log/startStopTorrent.log"
          echo "${DATE} - rTorrent started successfully" >> "/var/log/startStopTorrent.log"
       fi
       HIT=1
    fi
    if [ $HOUR -eq 7 ]; then
       /etc/init.d/rtorrent stop  2>> /var/log/startStopTorrent.log >> /var/log/startStopTorrent.log
       if [ $? -gt 0 ]; then
          echo "${DATE} - Running script at hour: ${HOUR}" >> "/var/log/startStopTorrent.log"
          echo "${DATE} - Failed stopping rTorrent" >> "/var/log/startStopTorrent.log"
       else
          echo "${DATE} - Running script at hour: ${HOUR}" >> "/var/log/startStopTorrent.log"
          echo "${DATE} - rTorrent stopped successfully" >> "/var/log/startStopTorrent.log"
       fi
       HIT=2
    fi
    #if [ HIT ]; then
       #Commented out this line, since it was just filling the log
       #echo "${DATE} - rTorrent was run, but had nothing to do" >> /var/log/startStopTorrent.log
    #fi
    
    if [ `stat -c %s /var/log/startStopTorrent.log` -gt 500000 ]; then
       mv /var/log/startStopTorrent.log /var/log/startStopTorrent.log.1
    fi

    start-node.sh
    #! /bin/bash
    ### BEGIN INIT INFO
    # Provides:          start-node
    # Required-Start:    $remote_fs $syslog
    # Required-Stop:     $remote_fs $syslog
    # Default-Start:     2 3 4 5
    # Default-Stop:      0 1 6
    # Short-Description: Initscript for node API
    # Description:  Automatically start node API when the system starts up.
    #               Provide commands for manually starting and stopping node API.
    #            This script needs to be edited before it works in your environment.
    #            In a CentOS/RedHat based environment it can be stored under 
    #            /etc/init.d/[name] and added to the system with chkconfig --add [name] --level 0356
    #            In a Debian based environment it can be stored under 
    #            /etc/init.d/[name] and added to the system with update-rc.d [name] defaults
    #            In CentOs this script depends on the rpm package redhat-lsb
    ### END INIT INFO
    # Adapt the following lines to your configuration
    # RUNUSER: The user to run start-node as.
    RUNUSER=root
    # NODE_INSTALLDIR: The path to the code where the node API is
    NODE_INSTALLDIR="/home/node/api"
    # ==================================================================================
    # ==================================================================================
    # ==================================================================================
    # PATH should only include /usr/* if it runs after the mountnfs.sh script
    PATH=/sbin:/usr/sbin:/bin:/usr/bin:$NODE_INSTALLDIR;
    DESC="node API"
    NAME=start-node
    SCRIPTNAME=/etc/init.d/$NAME
    # Define LSB log_* functions.
    # To be replaced by LSB functions
    # Defined here for distributions that don't define
    # log_daemon_msg
    log_daemon_msg () {
        echo $@
    }
    # To be replaced by LSB functions
    # Defined here for distributions that don't define
    # log_end_msg
    log_end_msg () {
        retval=$1
        if [ $retval -eq 0 ]; then
            echo "."
        else
            echo " failed!"
        fi
        return $retval
    }
    # Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
    . /lib/lsb/init-functions
     
    run_with_home() {
    if ps aux | grep "$NODE_INSTALLDIR/[s]erver.js" > /dev/null; then
        log_failure_msg "$NAME is already running."
    else
        echo "Logging to /tmp/start-node.log"
        if [ "$RUNUSER" != "$USER" ]; then
            su - "$RUNUSER" -c "nohup node ${NODE_INSTALLDIR}/$1 > /tmp/start-node.log 2>/dev/null &"
        else
            nohup node ${NODE_INSTALLDIR}/$1 > /tmp/start-node.log 2>/dev/null &
        fi
    fi
    }
    #
    # Function that starts the daemon/service
    #
    do_start()
    {
        run_with_home server.js
    }
    #
    # Function that stops the daemon/service
    #
    do_stop()
    {
    if ps aux | grep "$NODE_INSTALLDIR/[s]erver.js" > /dev/null; then
         # node is running
            killall node
      else
         # node is not running
            log_failure_msg "$NAME is not running."
    fi
    }
     
    case "$1" in
      start)
        [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
        do_start
        case "$?" in
            0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
            2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
        esac
        ;;
      stop)
        [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
        do_stop
        case "$?" in
            0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
            2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
        esac
        ;;
      status)
           if ps aux | grep "$NODE_INSTALLDIR/[s]erver.js" > /dev/null; then
            log_daemon_msg "$NAME is running" && exit 0 || exit $?
           fi
            log_failure_msg "$NAME is not running."
            return 1
           ;;
      restart|force-reload)
        #
        # If the "reload" option is implemented then remove the
        # 'force-reload' alias
        #
        log_daemon_msg "Restarting $DESC" "$NAME"
        do_stop
        case "$?" in
          0|1)
            do_start
            case "$?" in
                0) log_end_msg 0 ;;
                1) log_end_msg 1 ;; # Old process is still running
                *) log_end_msg 1 ;; # Failed to start
            esac
            ;;
          *)
            # Failed to stop
            log_end_msg 1
            ;;
        esac
        ;;
      *)
        echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2
        exit 3
        ;;
    esac

    mount_DVD.sh
    #! /bin/bash
    ##04.02.2009 - Atle Holm
    
    if [ $# -lt  1 ] || [ $# -gt 1 ]; then
       echo "You have to have 1 and you can only have 1 option, the number on the Debian DVD you want to mount!"
       exit 0
    fi
    case "$1" in
       1)
       umount /cdrom 2>> /dev/NULL
       mount -t iso9660 -o loop /home/Sources/ISO/debian-500-amd64-DVD-1.iso /cdrom
       echo "DVD1 mounted"
       ;;
       2)
       umount /cdrom 2>> /dev/NULL
       mount -t iso9660 -o loop /home/Sources/ISO/debian-500-amd64-DVD-2.iso /cdrom
       echo "DVD2 mounted"
       ;;
       3)
       umount /cdrom 2>> /dev/NULL
       mount -t iso9660 -o loop /home/Sources/ISO/debian-500-amd64-DVD-3.iso /cdrom
       echo "DVD3 mounted"
       ;;
       4)
       umount /cdrom 2>> /dev/NULL
       mount -t iso9660 -o loop /home/Sources/ISO/debian-500-amd64-DVD-4.iso /cdrom
       echo "DVD4 mounted"
       ;;
       5)
       umount /cdrom 2>> /dev/NULL
       mount -t iso9660 -o loop /home/Sources/ISO/debian-500-amd64-DVD-5.iso /cdrom
       echo "DVD5 mounted"
       ;;
       *) echo "You can only choose from 1 to 5"
    esac

    removeService.sh
    #! /bin/bash
    ## 02.08.2009 - Atle Holm
    ## Scriptet fjerner bare symlinks under /etc/rc?.d - THIS IS NOT THE RIGHT WAY TO DO THIS!
    ##Use update-rc.d instead to do this the right way
    if [ $# != 1 ]; then echo "You have to have one argument, the service name you want to remove!"; exit 1; fi
    
    echo "Starting removal of service.." >> /var/log/RemoveService-log.log
    echo "`date` - Removing service *$1*" >> /var/log/RemoveService-log.log
    X=0
    ErrCount=0
    while [ $X != 7 ]
    do
       FINDING=`find /etc/rc$X.d -name *$1* 2>> /var/log/RemoveService-log.log` 
       if [ $? != 0 ]; then 
          echo "Encountered an error, exiting!"; 
          echo "Encountered an error, exiting!" >> /var/log/RemoveService-log.log; 
          exit 1;
       fi
       for FOUND in ${FINDING}
       do
          echo "Removing ${FOUND}"
          rm ${FOUND} >> /var/log/RemoveService-log.log 2>> /var/log/RemoveService-log.log
          echo "${FOUND} deleted!" >> /var/log/RemoveService-log.log
       done
       if [ -z ${FINDING} ]; then 
          echo "Service was not found at /etc/rc$X.d"; (( ErrCount = ErrCount + 1 )); 
       fi
       (( X=X+1 ))
    done 
    if [ $ErrCount = 7 ]; then echo "Service *$1* was not found!" >> /var/log/RemoveService-log.log; fi
    echo "Done!" >> /var/log/RemoveService-log.log
    echo "Done!"; exit 0

    Valve-HLDS
    #!/bin/sh
    ### BEGIN INIT INFO
    # Provides:          service
    # Required-Start:    
    # Required-Stop:     
    # Default-Start:     2 3 4 5
    # Default-Stop:      0 1 6
    # Short-Description: HLDS initscript
    # Description:       This file should be used to construct scripts to be
    #                    placed in /etc/init.d.
    ### END INIT INFO
    #############
    ######
    #############
    # This script depends on screen.
    # It is placed underneath /etc/init.d and runs HLDS in screen as user specified below.
    # This script assumes you have set up an Half-Life dedicated server in Linux
    # as described in http://itblog.team-holm.net/index.php?scriptName=Linux&subSection=false
    # If the HLDS installation differs from what is shown in the link abovem this script needs
    # to be edited. The script further depends on a shell script that contains the runtime variables.
    # Here, this script is 'Valve-HLDS' and is defined in the config variable and STARTNAME variable below.
    # It merely contains:
    #   #! /bin/bash
    #   ./hlds_run -game valve +ip  +maxplayers 26 +map  +coop 0 +deathmatch 1
    # You have to name the script the same as what you specify as DAEMON name beneath in the defind DAEMON variable:
    # DAEMON=Valve-HLDS
    ##############
    ######
    ##############
    
    #######################
    ##Start Configuration##
    #######################
    
    #Do not put a space on either side of the equal signs e.g.
    # user = user 
    # will not work
    # system user to run as
    user="hlds"
    DATE=`date`
    
    # the system group to run as, not implemented, see d_start for beginning implementation
    # group=`id -ng "$user"`
    
    # the full path to the filename where you store your configuration
    config="`su -c 'echo $HOME' $user`/Valve-HLDS"
    
    # set of options to run with
    options=""
    
    # default directory for screen, needs to be an absolute path
    base="`su -c 'echo $HOME' $user`"
    
    # name of screen session
    srnname="hl_valve"
    
    # file to log to (makes for easier debugging if something goes wrong)
    logfile="/var/log/HLValveInit.log"
    #######################
    ###END CONFIGURATION###
    #######################
    PATH=/usr/bin:/usr/local/bin:/usr/local/sbin:/sbin:/bin:/usr/sbin:/home/hlds
    DESC="hl_valve"
    STARTNAME=Valve-HLDS
    DAEMON=Valve-HLDS
    SCRIPTNAME=/etc/init.d/$DAEMON
    
    checkcnfg() {
       exists=0
       for i in `echo "$PATH" | tr ':' '\n'` ; do
          if [ -f $i/$STARTNAME ] ; then
             exists=1
             break
          fi
       done
       if [ $exists -eq 0 ] ; then
          echo "${DATE} - cannot find hlds_run binary in PATH $PATH" | tee -a "$logfile" >&2
          exit 3
       fi
       if ! [ -r "${config}" ] ; then 
          echo "${DATE} - cannot find readable run file ${config}." | tee -a "$logfile" >&2
          echo "Check that it is there and permissions are appropriate." | tee -a "$logfile" >&2
          exit 3 
       fi 
       if [ `stat -c %s "$logfile"` -gt 500000 ]; then
       mv "$logfile" "$logfile".1
       fi
    }
    
    d_start() {
       [ -d "${base}" ] && cd "${base}"
       stty stop undef && stty start undef
       echo -n "Starting $DESC: $DAEMON"
       su -c "screen -A -m -d -S hlds $config" ${user} 2>&1 1>/dev/null | tee -a "$logfile" >&2 
       if [ $? != 0 ]; then
          echo -e "- This was ${DATE}" >> "$logfile"
       else
          echo -e "All OK in start at ${DATE}" >> "$logfile"
       fi
    }
    
    d_stop() {
       echo -n "Stopping $DESC: $DAEMON"
       pid=`ps -A | grep .${config##*/} | sed 's/^ *//g' | cut -d ' ' -f 1`
       if [ $pid ]; then
          kill -9 ${pid} | tee -a "$logfile" >&2 
       else
          echo "\nService is not running"
       fi
    }
    
    checkcnfg
    
    case "$1" in
       start)
          d_start
          echo "."
          ;;
       stop)
          d_stop
          echo "."
          ;;
       restart|force-reload)
          echo -n "Restarting $DESC: $DAEMON"
          d_stop
          sleep 1
          d_start
          echo "."
          ;;
       *)
          echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
          exit 1
          ;;
    esac
    exit 0

    registerWithSpaceWalk.sh
    #!/bin/bash
    #
    # Register with SpaceWalk for updates.
    # Script is used as a part of a VMware template. 
    # It ensures automatic registration to SpaceWalk given the right conditions.
    #
    # chkconfig: 12345 99 80
    # description: Register with SpaceWalk for updates, see /etc/hosts for info
    #
    
    #Get the systems IP-address at eth0 - Before Centos 7:
    #NETADDR=`/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'`
    
    #Get the systems IP-address at ETHNAME - Centos 7:
    ETHNAME=`/sbin/ifconfig | grep flags | cut -d: -f 1 | grep -v lo | head -1 | awk '{ print $1}'`
    NETADDR=`/sbin/ifconfig $ETHNAME | grep -w inet | cut -d ' ' -f 10 | awk '{ print $1}'`
    
    #Check that we are not in particular subnet before we continue:
    if [[ $NETADDR =~ ^192\.168\.100\.[0-9] ]]; then
            echo "** Detected that we are in the lab network, therefore we are not registering."
    else
            if [ -f /etc/sysconfig/rhn/systemid ]; then
                    echo "** The file /etc/sysconfig/rhn/systemid was found, so assuming the system is already registered with SpaceWalk"
            else
                    echo "** Seems the system is not registered with SpaceWalk"
                    TEMPLATENAME="CENTOS64.TEMPLATE"
                    if [ -f /etc/touchme ] || [ "$HOSTNAME" == "$TEMPLATENAME" ]; then
                            echo "** File /etc/touchme was found and/or hostname was CENTOS64.TEMPLATE, so not registering with SpaceWalk"
                    else
                            echo "** File /etc/touchme was not found and hostname was not CENTOS64.TEMPLATE, therefore registering with SpaceWalk"
                            rhnreg_ks --serverUrl=http://the-spacewalkserver/XMLRPC --activationkey=8-778bfb0a8dcbf0889fbb829aaf27w261
                            if [ $? == 0 ]; then
                                    touch /etc/touchme
                            fi
                    fi
            fi
    fi
    

    Perl
    VisualBasic
    BASH
    Powershell