Publi

Ejecutar scripts mientras inicia el sistema

botas

En ocasiones, queremos automatizar tareas al arranque del ordenador, tal vez para ofrecer asistencia remota (y enviarnos la IP del ordenador), actualizar una base de datos, correr scripts en una página web, hacer que el ordenador emita un sonido, inicializar un sistema antirrobo, o incluso interactúe con un arduino.

En muchas ocasiones, incluir nuestros scripts en /etc/rc.local basta, en Debian y derivadas lo encontramos fácilmente, en otras distribuciones también hay forma de hacerlo, aunque si necesitamos algo más complicado, como por ejemplo ejecutar varios scripts en un directorio determinado, en varios runlevels y que cuando se apague el ordenador se ejecuten otros scripts diferentes he hecho un pequeño init-script.

La diferencia con rc.local sería que en el primero, debemos escribir uno a uno los scripts que se ejecutarían y luego incluirlos, el script que pongo a continuación los buscará en /etc/iscripts/start si queremos que se inicien cuando arranca el ordenador y en /etc/iscripts/shutdown si queremos arrancarlos al apagar el ordenador. Por otra parte, si durante el arranque pasamos por varios runlevels, lo más seguro es que rc.local ejecute las cosas varias veces, iscripts, lo ejecutará todo una vez al arrancar y una vez al apagar.

Este es el script que debemos introducir en /etc/init.d/iscripts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#!/bin/bash
# Copyright (c) 2012 Gaspar Fernández
# All rights reserved.
#
# Author: Gaspar Fernández, 2012
#
# /etc/init.d/iscripts
### BEGIN INIT INFO
# Provides:          iscripts
# Required-Start:    $network
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Executes special scripts at boot or shutdown time
# Description:       Sometimes it is useful to run several scripts when
#            booting the system and not only when running GUI.
#            You can add here daemons with no init.d file, custom
#                    configurations, database changes, etc
### END INIT INFO
#

EXECUTED_start_SCRIPTS=""
EXECUTED_shutdown_SCRIPTS=""

. /lib/lsb/init-functions

function check_iscripts()
{
    if [ ! -d "/etc/iscripts/" ];
    then
        mkdir -p /etc/iscripts/start
        mkdir -p /etc/iscripts/shutdown
    fi

    # Creates directory if not exist
    if [ ! -d "/var/run/iscripts" ];
    then
        mkdir -p /var/run/iscripts
    fi

    if [ "`runlevel`" = "N 2" ];
    then
        > /var/run/iscripts/start
        > /var/run/iscripts/shutdown
    fi

    EXECUTED_start_SCRIPTS="`cat /var/run/iscripts/start`"
    EXECUTED_shutdown_SCRIPTS="`cat /var/run/iscripts/shutdown`"
}

function is_executed()
{
    LIST="EXECUTED_$2_SCRIPTS"

    if [ -z "`echo ${!LIST} | grep \\"$1\\"`" ];
    then
        echo 0
    else
        echo 1
    fi
}

function execute_script()
{
    if [ -x $file ];
        then
        if [ "`is_executed "$file" "$2"`" = "0" ];
        then
                echo -n "Running $file ..." >&2
            $file
            if [ "$?" = "0" ];
            then
                echo "$file" >> /var/run/iscripts/$2
            fi
        fi
        fi

}

function start_scripts()
{
    for file in /etc/iscripts/start/*
    do
        execute_script "$file" start
    done
}

function shutdown_scripts()
{
    for file in /etc/iscripts/shutdown/*
    do
        execute_script "$file" shutdown
    done
}

function get_status()
{
    echo "Not implemented yet"

}

check_iscripts

#echo "$1 in runlevel `runlevel`" >> /var/log/iscripts

case "$1" in
    start)
        echo "Starting scripts... "
    start_scripts
        ;;
    stop)
        echo "Starting shutdown scripts..."
    shutdown_scripts
        ;;
    restart)
        $0 stop
        $0 start
        ;;
    reload)
    echo "Not used"
        ;;
    status)
        echo "Scripts status..."

        checkproc $BAR_BIN
    ;;
    *)
        ## If no parameters are given, print which are avaiable.
        echo "Usage: $0 {start|stop|status|restart}"
        exit 1
        ;;
esac

No está demasiado probado, y lo calificaría de inestable, aunque espero seguir sacando versiones del mismo. Encontramos una línea comentada

1
#echo "$1 in runlevel `runlevel`" >> /var/log/iscripts

Si quitamos la # escribirá un log en /var/log/iscripts informando de las llamadas que se han hecho en el script, nos será útil para saber los runlevels por los que pasa nuestro sistema. El código lo he probado en Linux Mint y en Debian, me gustaría saber si lo probáis en otra distribución para saber si da algún problema.

Foto: watchsmart (Flickr). CC-by el 28/08/2012

También podría interesarte....

There are 4 comments left Ir a comentario

  1. Pingback: Bitacoras.com /

  2. Pingback: BlogESfera.com /

  3. Andrew Mark /
    Usando Google Chrome Google Chrome 117.0.0.0 en Windows Windows NT

    Wonderful article. Fascinating to read. I love to read such an excellent article. Thanks! It has made my task more and extra easy. Keep rocking.
    Top Gun Bomber Jacket

  4. Mike Rooney /
    Usando Google Chrome Google Chrome 118.0.0.0 en Windows Windows NT

    I found this post very exciting. I am also sending it to my friends to enjoy this blog. Yellowstone Merchandise

Leave a Reply