Certificat | LPIC-1 |
Examen: | 102 (torneu a la resta de temes) |
Fitxers: | LPI107.2_CronIAt.pdf (LPI107.2_CronIAt.odp),UD_8_14_automatitzacio_tasques.pdf (Apunts Eva Dominguez) |
Objectius: | http://www.lpi.org/eng/certification/the_lpic_program/lpic_1/exam_102_detailed_objectives |
Dipòsit SVN: | https://svn.projectes.lafarga.cat/svn/lpi/Materials/Examen_102/107.2 |
Usuari: | anonymous |
Paraula de pas: | qualsevol paraula de pas |
107.2. Automatitzar tasques d'administració del sistema amb treballs programats | |
---|---|
![]() |
|
![]() |
Àrees Clau de Coneixement: |
![]() |
La següent és una llista parcial de fitxers, termes i utilitats utilitzades: |
![]() |
Apunts: LPI 107.2. Automatitzar tasques d'administració del sistema amb treballs programats |
cron és un servei de planificació de tasques basat en temps molt utilitzat en sistemes operatius Unix-like. 'cron' és una abreviatura de cronògraf (Drupal Terminology Page)
Cron és el nom del programa que permet als usuaris de sistemes Unix executar comandes o guions de shell de forma automàtica a una data i temps específics. És utilitzat sovint pels administradors de sistemes com a eina per automatitzar tasques d'administració.
cron ha estat reescrit durant diversos cops durant la seva història. En aquest article utilitzem cron vixie, de l'autor Paul Vixie, també autor de Bind, el servidor de DNS lliure més utilitzat.
NOTA: Hi ha altres implementacions de cron, com la de AT&T que poden diferir lleugerament al que es comenta a aquest article per a CRON
Segons el manual:
$ man cron ... cron - daemon to execute scheduled commands (Vixie Cron)
Cron és un dimoni i com a tal es pot controlar mitjançant scripts SystemV. Per iniciar-lo (segurament ja està iniciat)
$ sudo /etc/init.d/cron start
Per apagar-lo:
$ sudo /etc/init.d/cron stop
Amb upstart podeu utilitzar:
$ sudo service cron start start: Job is already running: cron
$ sudo service cron stop cron stop/waiting
$ sudo service cron start cron start/running, process 16308
O comprovar directament l'estat amb:
$ sudo service cron status cron start/running, process 16308
Podeu fer-ho utilitzant ps:
$ ps aux | grep cron root 16231 0.0 0.0 2092 876 ? Ss 13:43 0:00 cron ...
NOTA: Distribucions antigues o altres que no siguin de la família Debian potser anomenen al dimoni cron crond (cron Daemon)
Si el dimoni es diu crond podem comprovar si cron funciona amb:
$ ps aux | grep crond root 311 0.0 0.7 1284 112 ? S Dec24 0:00 crond sergi 8606 4.0 2.6 1148 388 tty2 S 12:47 0:00 grep crond
La majoria de distribucions Linux porten per defecte el dimoni cron executant-se. Sinó podem executar directament el dimoni.
$ crond
O millor consulteu:
Cron com a dimoni
Podem consultar les comandes que un usuari té planificades amb:
$ sudo crontab -l 5 4 * * * /usr/bin/php -c /etc/php4/cli/php.ini /var/www/moodle/auth/ldap/auth_ldap_sync_users.php > /var/log/moodle/ldap_sync.txt 30 15 * * * /usr/bin/php -c /etc/php4/cli/php.ini /var/www/moodle/auth/ldap/auth_ldap_sync_users.php > /var/log/moodle/ldap_sync.txt 05 20 * * * /usr/bin/php -c /etc/php4/cli/php.ini /var/www/moodle/auth/ldap/auth_ldap_sync_users.php > /var/log/moodle/ldap_sync.txt
Per editar-les utilitzem:
$ sudo crontab -e
Consulteu l'apartat Format del fitxer crontab. crontable per saber com s'han d'especificar tasques.
i s'obre el editor que tinguem especificat a la variable d'entorn EDITOR. Podem consultar les variables d'entorn amb:
$ env
Podem mirar quin editor tenim amb:
$ env | grep [[EDITOR]
Per establir la variable es pot utilitzar export o editar el fitxer ~/.bashrc de la home o alguna solució similar:
$ export EDITOR=/usr/bin/vi
És possible configurar el editor per defecte utilitzant alternatives.
També es pot editar un fitxer i després passar-lo a cron:
$ sudo joe fitxer $ crontab fitxer
Cada cop que es fa un canvi al fitxer de cron NO cal tornar a iniciar el servidor cron. A la pròxima iteració ja s'aplicaran els canvis.
El superusuari pot modificar els crontabs d'altres usuaris amb:
$ sudo crontab -e -u sergi
Es pot eliminar un crontab amb:
$ crontab -r
o
$ sudo crontab -r -u sergi
Amb l'opció -i demana confirmació abans d'esborrar el fitxer.
Els fitxers de crontab es guarden a /var/spool/cron/crontabs/* però no es poden modificar directament sense crontab.
Podem consultar el manual amb:
$ man crontab
La següent taula mostra els camps possibles a cada línia d'un fitxer crontab:
Camp Valor ------------------ minute 00 a 59 hour 00 a 23 day 1 a 31 month 1 a 12 weekday 0 a 6 (0=Sunday i també el valor 7) També es pot utilitzar les tres primeres lletres en angles uses sun, mon, tue, wen, thu, fri i sat.
Els primers cinc camps també poden tenir els següents valors:
NOTA: Podeu trobar més informació sobre el format de cron al fitxer /usr/share/doc/cron/FEATURES
Es poden utilitzar comentaris amb #.
Podem trobar un exemple força clar consultant el fitxer principal de tasques cron:
$ cat /etc/crontab # /etc/crontab: system-wide crontab # Unlike any other crontab you don't have to run the `crontab' # command to install the new version when you edit this file # and files in /etc/cron.d. These files also have username fields, # that none of the other crontabs do. SHELL=/bin/sh PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin # m h dom mon dow user command 17 * * * * root cd / && run-parts --report /etc/cron.hourly 25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily ) 47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly ) 52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly ) #
Anem a fer un exemple:
$ crontab -e
NOTA: El primer cop que editeu el vostre crontab us preguntarà quin voleu que sigui l'editor per defecte
afegiu:
# m h dom mon dow command 10,20,30,40,50 * * * * env DISPLAY=:0 /usr/bin/zenity --warning --title="Et recomanem..." --text="Que DESCANSIS" --width=500 >> /home/sergi/logfile 2>&1
NOTA: Tingueu en compte que cron és molt "sensible". Per exemple, a l'exemple anterior si poseu accents i/o l'exclamació (!) no us funcionarà :
10,20,30,40,50 * * * * env DISPLAY=:0 /usr/bin/zenity --warning --title="Et recomanem..." --text="Què DESCANSIS\!" --width=500
Consulteu Aplicacions gràfiques i cron.
Guardeu i espereu a que s'executi. Si no funciona podeu consultar el fitxer de log syslog:
$ sudo tail --lines=500 /var/log/syslog | grep CRON .. ... Apr 17 19:10:01 BSFHPCasa CRON[17449]: (sergi) CMD (zenity --warning --title="Et recomanem..." --text="Qu\303\250 DESCANSIS\!" --width=500)
Els crontabs es guarden a:
$ ls /var/spool/cron/crontabs/ ls: no s’ha pogut obrir el directori /var/spool/cron/crontabs/: Permission denied
Però vegeu que només els podeu modificar amb crontab o sent superusuaris o del grup crontab:
$ sudo ls -l /var/spool/cron/crontabs/ total 8 -rw------- 1 root crontab 274 2010-02-02 08:53 root -rw------- 1 sergi crontab 335 2010-04-17 15:01 sergi
Fixeu-vos que l'executable crontab:
$ whereis crontab crontab: /usr/bin/crontab /etc/crontab /usr/share/man/man5/crontab.5.gz /usr/share/man/man1/crontab.1.gz $ ls -la /usr/bin/crontab -rwxr-sr-x 1 root crontab 31712 2009-09-15 15:12 /usr/bin/crontab
S'executa com a grup crontab (bit GUID)
Es poden establir variables d'entorn a cada fitxer crontab. Per defecte les següents variables d'entorn s'estableixen segons el contingut del fitxer /etc/passwd de l'usuari:
SHELL, USER, LOGNAME, i HOME
La shell per defecte és sh (/bin/sh).
Totes es poden modificar excepte USER.
Es pot establir TZ però s'ignorarà excepte si l'utilitza només en una ordre.
MAILTO s'utilitza per indicar el login name de l'usuari del sistema al qual cron li envia el resultat de les ordres executades amb crontab.
Com hem comentat cada usuari pot definir el seu propi crontab amb l'ordre crontab. Això inclou al superusuari, que pot crear tasques d'administració de superusuari.
La resta d'alternatives són
Utilitzar el fitxer /etc/crontab
És possible editar aquest fitxer directament però no és recomana (facilita possibles actualitzacions de cron i permet tenir un sistema més ordenat)
$ cat /etc/crontab # /etc/crontab: system-wide crontab # Unlike any other crontab you don't have to run the `crontab' # command to install the new version when you edit this file # and files in /etc/cron.d. These files also have username fields, # that none of the other crontabs do. SHELL=/bin/sh PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin # m h dom mon dow user command 17 * * * * root cd / && run-parts --report /etc/cron.hourly 25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily ) 47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly ) 52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
Utilitzar la carpeta /etc/cron.d
Es poden definir entrades per al fitxer /etc/crontab posant-les a la carpeta /etc/cron.d:
$ ls -la /etc/cron.d total 32 drwxr-xr-x 2 root root 4096 2010-02-12 15:47 . drwxr-xr-x 176 root root 12288 2010-04-17 12:00 .. -rw-r--r-- 1 root root 288 2009-09-17 21:32 anacron -rw-r--r-- 1 root root 572 2009-09-28 00:45 mdadm -rw-r--r-- 1 root root 499 2009-11-26 15:50 php5 -rw-r--r-- 1 root root 102 2009-09-15 15:12 .placeholder
$ cd /etc/cron.d/ $ ls anacron mdadm php5 $ cat php5 # /etc/cron.d/php5: crontab fragment for php5 # This purges session files older than X, where X is defined in seconds # as the largest value of session.gc_maxlifetime from all your php.ini # files, or 24 minutes if not defined. See /usr/lib/php5/maxlifetime # Look for and purge old sessions every 30 minutes 09,39 * * * * root [ -x /usr/lib/php5/maxlifetime ] && [ -d /var/lib/php5 ] && find /var/lib/php5/ -type f -cmin +$(/usr/lib/php5/maxlifetime) -print0 | xargs -n 200 -r -0 rm
Utilitzar les tasques diàries, setmanals, ...
Com hem vist al fitxer /etc/crontab. S'executen les següents tasques de forma automàtica:
Els resultats dels crons s'envien per email al propietari del cron o a el que s'hagi especificat a la variable MAILTO.Això és pot canviar amb redireccions. Per exemple:
cmd | mail -s "Subject of mail" email
Si no es vol enviar correu es pot redireccionar a /dev/null:
cmd > /dev/null
O es pot fer un log a un fitxer:
cmd >> log.file
Dos majors que indiquen mode append. Un sol major es sobreescriu el contingut del fitxer de log.
L'exemple anterior nomes redirecciona la sortida estàndard. Es pot redireccionar també els errors amb:
cmd >> logfile 2>&1
Cal tenir en compte, que el fet que un script funcioni amb la shell comuna no vol dir que funcioni amb la shell de cron. Un exemple:
/etc/backups/scripts/files_backup.sh >& /media/disk/logs/files_backup.log
Això funciona amb bash però si ho executem amb sh o cron ens donarà l'error:
# /etc/backups/scripts/files_backup.sh >& /media/disk/logs/files_backup.log sh: Syntax error: Bad fd number
Es pot especificar qui te permisos per executar cron i qui no. El us és similar al cas dels fitxers host (o molts altres dimonis). Dos fitxers controlen els permisos i les denegacions:
/etc/cron.allow
/etc/cron.deny
Per impedir que un usuari utilitzi cron es coloca el nom de l'usuari al fitxer cron.deny
Si es vol evitar que tots els usuaris utilitzin cron es pot utilitzar ALL:
$ sudo bash -c "echo ALL >> /etc/cron.deny"
o
$ sudo -s # echo ALL >> /etc/cron.deny
Si vols permetre l'usuari foo:
# echo cog >>/etc/cron.allow
Si no hi ha res als fitxers tothom pot utilitzar cron. Si utilitzem el fitxer cron.allow nomes els usuaris que surtin en aquest fitxer podran utilitzar cron.
A una Ubuntu 9.10 els fitxers no estan ni indicats, els hauríeu de crear. Per tant per defecte tots els usuaris poden utilitzar cron.
$ sudo grep -n "daily" -r .| more ./syslog.0:506:Feb 28 00:00:01 acacha /USR/SBIN/CRON[19980]: (root) CMD ([ -x /usr/sbin/update-motd ] && /usr/sbin/update-motd daily 2>/dev/null) ./syslog.0:699:Feb 28 06:25:01 acacha /USR/SBIN/CRON[23200]: (root) CMD (test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )) ./auth.log:64:Feb 28 07:51:19 acacha sudo: sergi : TTY=pts/1 ; PWD=/home/sergi ; USER=root ; COMMAND=/usr/bin/joe /etc/cron.daily/sync_mediawiki.sh ./auth.log:65:Feb 28 07:52:03 acacha sudo: sergi : TTY=pts/1 ; PWD=/etc/cron.daily ; USER=root ; COMMAND=/bin/cat /var/log/syslog ./auth.log:68:Feb 28 07:54:10 acacha sudo: sergi : TTY=pts/1 ; PWD=/etc/cron.daily ; USER=root ; COMMAND=/bin/bash ./auth.log:80:Feb 28 07:58:55 acacha sudo: sergi : TTY=pts/1 ; PWD=/var/log ; USER=root ; COMMAND=/bin/cat daily ./auth.log:81:Feb 28 07:59:04 acacha sudo: sergi : TTY=pts/1 ; PWD=/var/log ; USER=root ; COMMAND=/bin/grep -n daily -r .
0 * * * * echo "WAKE UP" 2>&1 /dev/console
Executa WAKE UP a la consola a cada hora de cada dia de cada mes.
0 0 * * * calendar -
O amb entorn gràfic:
0 * * * * zenity --warning --title="Et recomanem..." --text="Què DESCANSIS\!" --width=500
Executa calendar a l'inici d'una hora a l'inici del dia de cada dia del mes.
10,20,30,40,50 * * * * /adm/checkdaemon 2>&1 | /bin/mail -s "CRON:Check" root
S'executa als minuts 10, 20, 30 ,40, i 50 de cada hora de cada dia de tots els mesos.
Més exemples extrets de la pàgina web de linuca:
Exemple 1. Executar tots els dies un scripts de còpia de seguretat a les 7:00 del matí:
0 7 * * * /home/usuario/copiadeseguridad.sh
Exemple 2. Executar tots els primers dies de mes un scripts de copia de seguretat a les 7:00 del matí:
0 7 1 * * /home/usuario/copiadeseguridad.sh
Exemple 3. Executar tots els divendres a les 21:30 un script de còpia de seguretat:
30 21 * * 5 /home/usuario/copiadeseguridad.sh
Exemple 4: Cridar la comanda fetchmail cada 15 minuts:
0,15,30,45 * * * * fetchmail
*/15 * * * * fetchmail
Anacron a diferència de cron no pressuposa que la màquina s'estigui executant de forma continuada i permet a màquines que no estan sempre enceses poden executar tasques diàries, setmanals i mensuals. Només l'administrador del sistema pot executar pot configurar tasques d'anacron (amb cron és possible que els usuaris automatitzin tasques).
Anacron només pot executar tasques un cop al dia (o en períodes més grans: setmanes, mesos, etc.) en contrast amb cron que es pot arribar a executar cada minut.
Al executar anacron (no és un dimoni que s'estigui executant en tot moment) executa les tasques indicades al fitxer de configuració: /etc/anacrontab
Si el sistema es torna a iniciar o s'inicia després de la mitjanit, les tasques diàries són executades després de cert retard i de forma ordenada (una tasca anacron a l'hora). De fet anacron utilitza cron per executar-se, consulteu el fitxer /etc/cron.d/anacron:
$ cat /etc/cron.d/anacron # /etc/cron.d/anacron: crontab entries for the anacron package SHELL=/bin/sh PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin #30 7 * * * root test -x /etc/init.d/anacron && /usr/sbin/invoke-rc.d anacron start >/dev/null 30 7 * * * root start -q anacron || :
Si la màquina esta encesa s'executa a les 7:30 i sinó s'executa al iniciar la màquina.
Per cada tasca a executar (segons el fitxer de configuració) anacron mirà si la tasca s'ha executat en els últims n dies i la executa si n és major que el període indicat per cada ordre. Si la tasca s'ha d'executa es fa després d'esperar-se un temps prudencial (delay) així s'evita executar múltiples tasques al mateix temps.
Un cop s'ha executat la tasca, per cada tasca que executa anacron manté una marca de temps a /var/spool/anacron/:
$ ls /var/spool/anacron/ cron.daily cron.monthly cron.weekly
Quan ja no té més tasques pendents anacron s'atura.
Els fitxers proporcionats per anacron són:
$ dpkg -L anacron /. /etc /etc/cron.d /etc/cron.d/anacron /etc/init.d /etc/cron.daily /etc/cron.daily/0anacron /etc/cron.weekly /etc/cron.weekly/0anacron /etc/cron.monthly /etc/cron.monthly/0anacron /etc/apm /etc/apm/event.d /etc/apm/event.d/anacron /etc/anacrontab /etc/init /etc/init/anacron.conf /usr /usr/sbin /usr/sbin/anacron /usr/share /usr/share/doc /usr/share/doc/anacron /usr/share/doc/anacron/TODO /usr/share/doc/anacron/README.Debian /usr/share/doc/anacron/copyright /usr/share/doc/anacron/changelog.gz /usr/share/doc/anacron/README.gz /usr/share/doc/anacron/changelog.Debian.gz /usr/share/man /usr/share/man/man5 /usr/share/man/man5/anacrontab.5.gz /usr/share/man/man8 /usr/share/man/man8/anacron.8.gz /usr/lib /usr/lib/pm-utils /usr/lib/pm-utils/sleep.d /usr/lib/pm-utils/sleep.d/95anacron /usr/lib/pm-utils/power.d /usr/lib/pm-utils/power.d/anacron /var /var/spool /var/spool/anacron /etc/init.d/anacron
El fitxer de configuració principal és:
/etc/anacrontab
A una Ubuntu 9.10:
$ cat /etc/anacrontab # /etc/anacrontab: configuration file for anacron # See anacron(8) and anacrontab(5) for details. SHELL=/bin/sh PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin # These replace cron's entries 1 5 cron.daily nice run-parts --report /etc/cron.daily 7 10 cron.weekly nice run-parts --report /etc/cron.weekly @monthly 15 cron.monthly nice run-parts --report /etc/cron.monthly
NOTA: Fixeu-vos que està en sincronia amb cron i s'utilitzen les mateixes carpetes per a les tasques diaries, semanals i mensuals.
En analogia al fitxer principal de configuració de cron (/etc/crontab). Segons el manual:
$ man anacrontab
Descriu les tasques controlades per anacron i pot tenir 3 tipus de línies:
Les línies de descripció de tasques poden ser de dos tipus/formats:
period delay job-identifier command
o
@period_name delay job-identify command
On:
Els camps es poden separar per espais en blanc o tabuladors.
Es pot continuar una línia amb '\'.
Permet especificar que es puguin executar ordres un sol cop en un moment donat:
$ date ds abr 17 19:49:16 CEST 2010 $ tty /dev/pts/15
Ara li diem que executi un hola a les 19:52:
$ at 19:52 warning: commands will be executed using /bin/sh at> echo "hello" > /dev/pts/15 at> <EOT> job 1 at Sat Apr 17 19:52:00 2010
Fixeu-vos que per indicar el final de les ordres cal utilitzar el caràcter de final de fitxer (EOF) amb Control-D quan esteu al principi d'un fitxer (igual que amb els heredoc)
Us mostra el número de tasca (a l'exemple job 1). vegem un altre exemple, aquest cop amb un temp relatiu
$ at now + 25 minutes echo ^G > /dev/pts/15 ^D Job c00ceb7fb.00 will be executed using /bin/sh
Es farà un beep en 25 minuts. Podem especificar un dia concret per enviar un correu amb mail
$ at 4:55pm Friday warning: commands will be executed using /bin/sh at> echo '5 p.m. trobada amb Pep' | mail sergi at> <EOT> job 2 at Fri Apr 23 16:55:00 2010
Per mostrar una llista de les tasques pendents (q de queue):
$ atq
Al superusuari li mostra totes les tasques pendents de tots els usuaris. Per eliminar una tasca:
$ atrm numero_de_tasca
o
$ at -d numero_de_tasca
Es pot veure el contingut d'una tasca amb:
$ at -c numero_de_tasca
Per exemple:
$ at -c 11 #!/bin/sh # atrun uid=1000 gid=1000 # mail sergi 0 umask 22 ORBIT_SOCKETDIR=/tmp/orbit-sergi; export ORBIT_SOCKETDIR SSH_AGENT_PID=2706; export SSH_AGENT_PID XDG_SESSION_COOKIE=fd7623409951c1415cfc7fa04b30a877-1271564824.202249-1695066321; export XDG_SESSION_COOKIE GTK_RC_FILES=/etc/gtk/gtkrc:/home/sergi/.gtkrc-1.2-gnome2; export GTK_RC_FILES WINDOWID=83886084; export WINDOWID OLDPWD=/home/sergi/subversion/lpi/Materials/Examen_102; export OLDPWD GTK_MODULES=canberra-gtk-module; export GTK_MODULES USER=sergi; export USER LS_COLORS=rs=0:di=01\;34:ln=01\;36:hl=44\;37:pi=40\;33:so=01\;35:do=01\;35:bd=40\;33\;01:cd=40\;33\;01:or=40\;31\;01:su=37\;41:sg=30\;43:ca=30\;41:tw=30\;42:ow=34\;42:st ... \;36:\*.xspf=00\;36:; export LS_COLORS SSH_AUTH_SOCK=/tmp/keyring-Pam2yp/socket.ssh; export SSH_AUTH_SOCK GNOME_KEYRING_SOCKET=/tmp/keyring-Pam2yp/socket; export GNOME_KEYRING_SOCKET SESSION_MANAGER=local/BSFHPCasa:@/tmp/.ICE-unix/2658,unix/BSFHPCasa:/tmp/.ICE-unix/2658; export SESSION_MANAGER USERNAME=sergi; export USERNAME DESKTOP_SESSION=gnome; export DESKTOP_SESSION PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games; export PATH PWD=/home/sergi/subversion/lpi/Materials/Examen_102/107.2; export PWD JAVA_HOME=/usr/lib/jvm/java-6-sun-1.6.0.15; export JAVA_HOME GDM_KEYBOARD_LAYOUT=es\ cat; export GDM_KEYBOARD_LAYOUT LANG=ca_ES.UTF-8; export LANG GNOME_KEYRING_PID=2643; export GNOME_KEYRING_PID GDM_LANG=ca_ES.UTF-8; export GDM_LANG GDMSESSION=gnome; export GDMSESSION HISTCONTROL=ignoreboth; export HISTCONTROL SPEECHD_PORT=7560; export SPEECHD_PORT SHLVL=1; export SHLVL HOME=/home/sergi; export HOME GNOME_DESKTOP_SESSION_ID=this-is-deprecated; export GNOME_DESKTOP_SESSION_ID LOGNAME=sergi; export LOGNAME DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-GqIXZWIJ6b,guid=a782784356e8bffdc85e98754bca8a18; export DBUS_SESSION_BUS_ADDRESS XDG_DATA_DIRS=/usr/share/gnome:/usr/local/share/:/usr/share/; export XDG_DATA_DIRS LESSOPEN=\|\ /usr/bin/lesspipe\ %s; export LESSOPEN LESSCLOSE=/usr/bin/lesspipe\ %s\ %s; export LESSCLOSE COLORTERM=gnome-terminal; export COLORTERM XAUTHORITY=/var/run/gdm/auth-for-sergi-58K5CM/database; export XAUTHORITY cd /home/sergi/subversion/lpi/Materials/Examen\_102/107\.2 || { echo 'Execution directory inaccessible' >&2 exit 1 } echo hola | wall
On el numero_de_tasca és el retornat per l'ordre atq.
L'ordre es proporcionada pel paquet del mateix nom:
$ whereis at at: /usr/bin/at /etc/at.deny /usr/share/man/man1/at.1.gz $ dpkg -S /usr/bin/at at: /usr/bin/at
Les tasques pendents es guarden físicament a /var/spool/atjobs.
Consulteu també:
$ man at ... at, batch, atq, atrm - queue, examine or delete jobs for later execution
És pot especificar qui te permisos per executar at i qui no. Dos fitxers controlen els permisos i les denegacions:
/etc/at.allow
/etc/at.deny
Per impedir que un usuari utilitzi at es col·loca el nom de l'usuari al fitxer at.deny
Si es vol evitar que tots els usuaris utilitzin at es pot utilitzar ALL:
$ sudo bash -c "echo ALL >> /etc/at.deny"
o
$ sudo -s # echo ALL >> /etc/at.deny
Si vols permetre el usuari foo:
# echo cog >>/etc/at.allow
Si no hi ha res als fitxers tothom pot utilitzar at. Si utilitzem el fitxer at.allow nomes els usuaris que surtin en aquest fitxer podran utilitzar at.
A una Ubuntu 9.10 els fitxers no estan ni indicats, els hauríeu de crear. Per tant per defecte tots els usuaris poden utilitzar at.
# echo "halt" | at 11 PM warning: commands will be executed using /bin/sh job 1 at Thu Dec 4 23:00:00 2008 # at -l 1 Thu Dec 4 23:00:00 2008 a root
Recursos:
# echo "halt" | at 11 PM warning: commands will be executed using /bin/sh job 1 at Thu Dec 4 23:00:00 2008 # at -l 1 Thu Dec 4 23:00:00 2008 a root
Recursos:
$ dpkg -l | grep cron ii anacron 2.3-13.1ubuntu10 cron-like program that doesn't go by time ii cron 3.0pl1-106ubuntu3 process scheduling daemon
Consulteu:
$ dpkg -l | grep cron
El paquet s'anomena igual que el dimoni cron. Els fitxers que proporciona són:
Executables:
$ dpkg -L cron | grep bin /usr/bin /usr/bin/crontab <-- Configuració de cron /usr/sbin /usr/sbin/cron <-- El propi dimoni cron
Fitxers de configuració:
$ dpkg -L cron | grep etc /etc /etc/cron.hourly /etc/cron.hourly/.placeholder /etc/cron.daily /etc/cron.daily/.placeholder /etc/cron.daily/standard /etc/cron.weekly /etc/cron.weekly/.placeholder /etc/cron.monthly /etc/cron.monthly/.placeholder /etc/cron.monthly/standard /etc/cron.d /etc/cron.d/.placeholder /etc/init.d /etc/pam.d /etc/pam.d/cron /etc/init /etc/init/cron.conf /etc/crontab /etc/init.d/cron
Els fitxers placeholder son per evitar que s'eliminin les carpetes:
$ cat /etc/cron.hourly/.placeholder # DO NOT EDIT OR REMOVE # This file is a simple placeholder to keep dpkg from removing this directory
Cron utilitza PAM com a mecanisme d'autenticació. Quasi utilitza PAM per defecte però:
$ cat /etc/pam.d/cron # # The PAM configuration file for the cron daemon # @include common-auth session required pam_env.so @include common-account @include common-session-noninteractive # Sets up user limits, please define limits for cron tasks # through /etc/security/limits.conf session required pam_limits.so
Inclou la possibilitat de definir límits amb pam_limits.
Consulteu at
Consulteu atq
Consulteu atrm
Consulteu anacron.
A una Ubuntu 9.10 el fitxer conté:
$ cat /etc/crontab # /etc/crontab: system-wide crontab # Unlike any other crontab you don't have to run the `crontab' # command to install the new version when you edit this file # and files in /etc/cron.d. These files also have username fields, # that none of the other crontabs do. SHELL=/bin/sh PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin # m h dom mon dow user command 17 * * * * root cd / && run-parts --report /etc/cron.hourly 25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily ) 47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly ) 52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly ) #
Observeu que per defecte l'interpret d'ordres és sh (al fer scripts cron ho heu de tenir en compte ja que hi ha diferències entre bash i sh). També es configura el PATH.
Consulteu /etc/at.deny
Consulteu /etc/at.allow
Consulteu /etc/cron.allow.
Consulteu /etc/cron.deny.
És on es guarden els fitxer de cron (crontabs):
$ ls -l /var/spool/cron total 12 drwxrwx--T 2 daemon daemon 4096 2009-12-22 11:44 atjobs drwxrwx--T 2 daemon daemon 4096 2009-09-15 15:09 atspool drwx-wx--T 2 root crontab 4096 2010-04-17 15:01 crontabs
És la configuració upstart de cron en versions d'Ubuntu com Ubuntu 9.10 o superior.
$ cat /etc/init/cron.conf # cron - regular background program processing daemon # # cron is a standard UNIX program that runs user-specified programs at # periodic scheduled times description "regular background program processing daemon" start on runlevel [2345] stop on runlevel [!2345] expect fork respawn exec cron
$ cat /usr/share/doc/cron/FEATURES $Id: FEATURES,v 2.1 1993/12/28 08:34:43 vixie Exp $ Features of Vixie's cron relative to BSD 4.[23] and SysV crons: -- Environment variables can be set in each crontab. SHELL, USER, LOGNAME, and HOME are set from the user's passwd entry; all except USER can be changed in the crontab. PATH is especially useful t o set there. TZ can be set, but cron ignores it other than passing it on through to the commands it runs. Format is variable=value Blanks surrounding the '=' will be eaten; other blanks in value are okay. Leading or trailing blanks can be preserved by quoting, single or double quotes are okay, just so they match. PATH=.:/bin:/usr/bin SHELL=/bin/sh FOOBAR = this is a long blanky example Above, FOOBAR would get "this is a long blanky example" as its value. SHELL and HOME will be used when it's time to run a command; if you don't set them, HOME defaults to your /etc/passwd entry and SHELL defaults to /bin/sh. MAILTO, if set to the login name of a user on your system, will be the person that cron mails the output of commands in that crontab. This is useful if you decide on BINMAIL when configuring cron.h, since binmail doesn't know anything about aliasing. -- Weekdays can be specified by name. Case is not significant, but only the first three letters should be specified. -- Months can likewise be specified by name. Three letters only. -- Ranges and lists can be mixed. Standard crons won't allow '1,3-5'. -- Ranges can specify 'step' values. '10-16/2' is like '10,12,14,16'. -- Sunday is both day 0 and day 7 -- apparently BSD and ATT disagree about this. -- Each user gets their own crontab file. This is a win over BSD 4.2, -- Sunday is both day 0 and day 7 -- apparently BSD and ATT disagree about this. -- Each user gets their own crontab file. This is a win over BSD 4.2, where only root has one, and over BSD 4.3, where they made the crontab format incompatible and although the commands can be run by non-root uid's, root is still the only one who can edit the crontab file. This feature mimics the SysV cron. -- The 'crontab' command is loosely compatible with SysV, but has more options which just generally make more sense. Running crontab with no arguments will print a cute little summary of the command syntax. -- Comments and blank lines are allowed in the crontab file. Comments must be on a line by themselves; leading whitespace is ignored, and a '#' introduces the comment. -- (big win) If the `crontab' command changes anything in any crontab, the 'cron' daemon will reload all the tables before running the next iteration. In some crons, you have to kill and restart the daemon whenever you change a crontab. In other crons, the crontab file is reread and reparsed every minute even if it didn't change. -- In order to support the automatic reload, the crontab files are not readable or writable except by 'crontab' or 'cron'. This is not a problem, since 'crontab' will let you do pretty much whatever you want to your own crontab, or if you are root, to anybody's crontab. -- If any output is generated by a command (on stdout OR stderr), it will be mailed to the owner of the crontab that contained the command (or MAILTO, see discussion of environment variables, above). The headers of the mail message will include the command that was run, and a complete list of the environment that was passed to it, which will contain (at least) the USER (LOGNAME on SysV), HOME, and SHELL. -- the dom/dow situation is odd. '* * 1,15 * Sun' will run on the first and fifteenth AND every Sunday; '* * * * Sun' will run *only* on Sundays; '* * 1,15 * *' will run *only* the 1st and 15th. this is why we keep 'e->dow_star' and 'e->dom_star'. I didn't think up this behaviour; it's how cron has always worked but the documentation hasn't been very clear. I have been told that some AT&T crons do not act this way and do the more reasonable thing, which is (IMHO) to "or" the various field-matches together. In that sense this cron may not be completely similar to some AT&T crons.
Configuració upstart de anacron.
Per tant comproveu que la vostra comanda funciona amb sh fent:
$ sh
I provant els vostres scripts amb aquest tipus de shell
Consulteu:
#Int.C3.A8rprets_d.27ordres_i_cron\Intèrprets d'ordres i cron
Vigileu que les comandes acabin amb un salt de línia, tant al fitxer cron (per exemple /etc/cron.d/elmeucron) com l'script que escriviu
Quan es crea un crontab de superusuari es pot especificar quin usuari es vol utilitzar. si s'intenta fer el mateix a un crontab d'usuari normal, aleshores s'intentarà executar el nom de l'usuauri com una ordre i fallarà.
S'utilitza a cron per indicar una nova línia, si voleu utilitzar aquest caràcter cal escapar-lo amb "\%".
Per veure el que pot estar fallant podeu crear un fitxer de log. Consulteu Control_de_les_sortides_amb_cron
Per a poder executar aplicacions gràfiques amb cron cal indicar la variable d'entorn DISPLAY. Per exemple:
00 06 * * * env DISPLAY=:0 gui_appname
Si es tenen diversos monitor no heu d'oblidar indicar quin voleu utilitzar:
00 06 * * * env DISPLAY=:0.0 gui_appname
A més a Ubuntu 9.10 Karmic Koala cal:
~$ xhost +local: non-network local connections being added to access control list
Consulteu els canvis amb:
~$ xhost access control enabled, only authorized clients can connect LOCAL: ...
El principi de l'script ha de començar amb
#!/bin/sh