adminlinux i

71
CURSO DE CURSO DE ADMINISTRADOR ADMINISTRADOR DE LINUX I DE LINUX I 1/71

Upload: jose-salom

Post on 05-Feb-2016

29 views

Category:

Documents


0 download

DESCRIPTION

Apuntes sobre administrador Linux

TRANSCRIPT

Page 1: Adminlinux I

CURSO DE CURSO DE ADMINISTRADOR ADMINISTRADOR

DE LINUX IDE LINUX I

1/71

Page 2: Adminlinux I

Índice de contenido1.-INTRODUCCIÓN A LA ADMINISTRACIÓN LINUX............................................4

Actualización de software............................................................................ 4Directorios principales..................................................................................4Permisos ficheros......................................................................................... 5Para crear usuario y grupos......................................................................... 5LOS ENLACES EN LINUX............................................................................... 6FSTAB .......................................................................................................... 7ARRANQUE DEL SISTEMA........................................................................... 10CRONTAB....................................................................................................11Como compilar un programa en codigo fuente..........................................12

COMPILACION DEL KERNEL. PONER MODULOS Y PARCHES...........................15PASO A PASO PARA LA COMPILACION.........................................................15Para aplicar un parche a un kernel.............................................................21MODULOS...................................................................................................22

RECUPERACION DEL SISTEMA EN CASO DE FALLO.........................................234.- CONFUGURACON DE LA RED LOCAL.........................................................24

Ficheros de configuración de red...............................................................25CONFIRGURAR UN SERVIDOR DHCP...............................................................275.- NFS (Network File System)........................................................................29

PRACTICA NFS............................................................................................ 30INSTALAR VMWARE SERVER...........................................................................31

VMware Server sobre Debian.....................................................................33La consola se cuelga al pulsar el botón browse.........................................33WEBMIN......................................................................................................34

6.- OpenLDAP ................................................................................................36¿Que vamos a hacer?.................................................................................36INSTALACIÓN OpenLDAP.............................................................................37Migracion de los datos locales al Directorio LDAP......................................39PARTE DEL CLIENTE....................................................................................40Directorio HOME centralizado.................................................................... 44PRACTICA OpenLDAP..................................................................................45

SERVIDOR DE IMPRESION CUPS.....................................................................46AÑADIR UNA IMPRESORA........................................................................... 47Configurar un cliente linux para imprimir por impresoras remotas de CUPS...................................................................................................................48

COPIAS DE SEGURIDAD..................................................................................49PARA CONFIGURAR UN SERVIDOR DE RSYC Que es donde tenemos lo datos.......................................................................................................... 49PARTIMAGE.................................................................................................51PARTED. .....................................................................................................52IMAGEN DEL SO en FORMATO ISO (como ghost)........................................53SYSTEM RESCUE CD *Descargar................................................................53

SAMBA y WINBIND ........................................................................................ 54

2/71

Page 3: Adminlinux I

PRÁCTICA DE SAMBA..................................................................................61COMO HACER QUE EL SERVIDOR SAMBA HAGA FUNCIONES DE PDC........64PRACTICA SAMBA....................................................................................... 66PRACTICA DE METER UN LINUX EN UN DOMINIO , con WINBIND...............66

PRACTICA FINAL PERMISOS Y USUARIOS, SISTEMAS DE FICHEROS, MONITORIZACION DEL SISTEMA,................................................................... 68SAMBA Y RSYNC.............................................................................................68

3/71

Page 4: Adminlinux I

ADMINISTRADOR LINUX I

1.-INTRODUCCIÓN A LA ADMINISTRACIÓN LINUX

Actualización de software.

En /etc/apt/sources.list es donde se especifica el repositorio donde buscar los paquetes.

Comentar la linea de cdrom si no lo voy a usar.

debian:/home/jose# cat /etc/apt/sources.list## deb cdrom:[Debian GNU/Linux 4.0 r0 _Etch_ - Official i386 CD Binary-1 20070407-11:55]/ etch contrib main

# deb cdrom:[Debian GNU/Linux 4.0 r0 _Etch_ - Official i386 CD Binary-1 20070407-11:55]/ etch contrib main

#Lsita de paquetesdeb http://ftp.rediris.es/debian/ etch maindeb-src http://ftp.rediris.es/debian/ etch main

#Actualizaciones de seguridaddeb http://security.debian.org/ etch/updates main contribdeb-src http://security.debian.org/ etch/updates main contrib

apt-get update -> actualiza la lista de paquetesapt-get upgrade -> actuliza los paquetes necesartios

Para cambiar de version de debian.Cambiamos las referencias en el fichero sources.list

Directorios principales

/bin :binarios para cualquier usuario/dev : todos los disp. del sistema/boot : Imagenes del kernel/sbin: binarios de root/home: Dir de los usuarios/lib:Libreria del sistema/initrd: Es lo que carga el cargador de arranque antes de cargar la imagen del nuebleo/etc: Directorio de configuración de todo el sistema./lost+found: Existe por que el fs es ext/media: donde se monta el CD y los USB/mnt: donde montamos los discos del sistema por convencio.

4/71

Page 5: Adminlinux I

/proc: Se actualiza en tiempo real para llevar el control de proceso y del sistema./root: El home del root/srv: En suse se pone el servidor www y ftp/sys:/tmp: Para archivos temporales/ver:/usr: Arbol de las aplicaciones instaladas. /usr/share /var:tenemos spools de impresion, correo, log

/var y /home se recomienda instalarlo en otro disco o particion.

Permisos ficheros.

debian:/home/jose# ls -ltotal 4drwxr-xr-x 2 jose jose 4096 2007-11-05 17:46 Desktop

owner group otherrwx rwx rwx

#chmod 755 fich

Los archivos se crean con mascara por defecto 644

Todos los fichero tienen un propietario y un grupo. Para cambiarlo

#chown usuario fich#chgroup grupo fich

Para crear usuario y grupos

# useradd -d /home/user -m -s/bin/bash -G grupo nombreuser

-m es para que cree automaticamente el directorio home, si no lo tengo que crear.

En /etc/passwd estan los usuario

hplip:x:107:7:HPLIP system user,,,:/var/run/hplip:/bin/false

5/71

Page 6: Adminlinux I

jose:x:1000:1000:jose salom,,,:/home/jose:/bin/bash

En /etc/groups

Para poner la contraseña al usuario # passwd usuario

Gráficamente en Administración /usuarios y grupos

LOS ENLACES EN LINUX.

Un enlace se identifica por que aparece una “l” en los permisos y luego dice la ruta.

Para hacer un enlace simple.#ls -s origen distino

Si hacemos para ver el numero de i-nodo # ls -il

debian:/home/jose/Desktop# ln -s AdminLinux.odt linux.odtdebian:/home/jose/Desktop# ls -iltotal 441124127 -rw-r--r-- 1 jose jose 36432 2007-11-05 18:02 AdminLinux.odt1123972 -rwx------ 1 jose jose 4136 2007-11-05 17:31 foo-0000163960.desktop1124139 lrwxrwxrwx 1 root root 14 2007-11-05 18:07 linux.odt -> AdminLinux.odt

Si creo un enlace DURO.

# ln origen distino // sin la s

debian:/home/jose/Desktop# ln AdminLinux.odt linux.odtdebian:/home/jose/Desktop# ls -iltotal 1161124127 -rw-r--r-- 2 jose jose 36843 2007-11-05 18:09 AdminLinux.odt1124130 -rw-r--r-- 1 root root 36432 2007-11-05 18:09 copia.odt

6/71

Page 7: Adminlinux I

1123972 -rwx------ 1 jose jose 4136 2007-11-05 17:31 foo-0000163960.desktop1124127 -rw-r--r-- 2 jose jose 36843 2007-11-05 18:09 linux.odt

Aquí vemos que realmente es como si fuera el mismo fichero ya que tiene el mismo i-nodo.

FSTAB

Aquí indicamos las particiones que queremos montar en el sistema al arrancar.

debian:/media# cat /etc/fstab# /etc/fstab: static file system information.## <file system> <mount point> <type> <options> <dump> <pass>proc /proc proc defaults 0 0/dev/hda3 / ext3 defaults,errors=remount-ro 0 1/dev/hda2 none swap sw 0 0/dev/hdc /media/cdrom0 udf,iso9660 user,noauto 0 0/dev/fd0 /media/floppy0 auto rw,user,noauto 0 0x.x.x.x:/dir_remoto /mnt/donde nfs user # para montar un sistema nfs

options:user: Para que el usuario pueda montar el devnoauto: Para que no lo monte al inicio.

Type: Tipo de particionSi pones auto el sistema intenta reconocer la particion.

Comandos para crear particiones #fdisk o #cfdisk

Reinicio el equipo para que reconozca la nueva particion

debian:/media# mkfs. mkfs.cramfs mkfs.ext2 mkfs.ext3 mkfs.minix

Para porder hacer particiones DOS y NTFS instalar el paquete.

debian:~/backup# mkfs. TAB TABmkfs.cramfs mkfs.ext2 mkfs.ext3 mkfs.minix mkfs.reiserfsdebian:~/backup# apt-get install dosfstools ntfsprogsLeyendo lista de paquetes... HechoCreando árbol de dependencias... Hecho.....

debian:~/backup# mkfs. TAB TABmkfs.cramfs mkfs.ext3 mkfs.msdos mkfs.reiserfsmkfs.ext2 mkfs.minix mkfs.ntfs mkfs.vfat

7/71

Page 8: Adminlinux I

Veo que solo puedo dar formato a la particion de esos tipos luego instalo el paquete reiserfsprogs

debian:/media# apt-get install reiserfsprogsLeyendo lista de paquetes... HechoCreando árbol de dependencias... HechoSe instalarán los siguientes paquetes NUEVOS: reiserfsprogs0 actualizados, 1 se instalarán, 0 para eliminar y 0 no actualizados.Necesito descargar 480kB de archivos.Se utilizarán 1090kB de espacio de disco adicional después de desempaquetar.Des:1 http://ftp.rediris.es etch/main reiserfsprogs 1:3.6.19-4 [480kB]Descargados 480kB en 1s (328kB/s)Seleccionando el paquete reiserfsprogs previamente no seleccionado.(Leyendo la base de datos ...67724 ficheros y directorios instalados actualmente.)Desempaquetando reiserfsprogs (de .../reiserfsprogs_1%3a3.6.19-4_i386.deb) ...Configurando reiserfsprogs (3.6.19-4) ...debian:/media# mkfs. TAB TABmkfs.cramfs mkfs.ext2 mkfs.ext3 mkfs.minix mkfs.reiserfs

Ahora ya puedo formatear con reiserfs la nuevas particion que había creado.

debian:/home/jose# mkfs.reiserfs /dev/hda4mkfs.reiserfs 3.6.19 (2003 www.namesys.com)

A pair of credits:Alexander Zarochentcev (zam) wrote the high low priority locking code, onlineresizer for V3 and V4, online repacker for V4, block allocation code, and majorparts of the flush code, and maintains the transaction manager code. We givehim the stuff that we know will be hard to debug, or needs to be very cleanlystructured.

Vladimir Demidov wrote the parser for sys_reiser4(), the V3 alpha port, part ofthe V3 journal relocation code, and helped Hans keep the business side ofthings running.

Guessing about desired format.. Kernel 2.6.18-5-686 is running.Format 3.6 with standard journalCount of blocks on the device: 1220928Number of blocks consumed by mkreiserfs formatting process: 8249Blocksize: 4096Hash function used to sort names: "r5"Journal Size 8193 blocks (first block 18)Journal Max transaction length 1024inode generation number: 0UUID: 2b695283-9fe4-4dbe-b72f-7aa3b2649909ATTENTION: YOU SHOULD REBOOT AFTER FDISK! ALL DATA WILL BE LOST ON '/dev/hda4'!Continue (y/n):yInitializing journal - 0%....20%....40%....60%....80%....100%Syncing..ok

Tell your friends to use a kernel based on 2.4.18 or later, and especially not akernel based on 2.4.9, when you use reiserFS. Have fun.

8/71

Page 9: Adminlinux I

ReiserFS is successfully created on /dev/hda4.

Ahora voy a montar la particion en el directorio que me creo /mnt/part4

debian:/home/jose# mkdir /mnt/part4debian:/home/jose# lsDesktopdebian:/home/jose# mount /dev/hda4 /mnt/part4

Con df vemos los datos de los dispositivos montados y sus espacio libre y usado. La opcion -h es para que lo ponga en Gb y mbdebian:/home/jose# df -hS.ficheros Tamaño Usado Disp Uso% Montado en/dev/hda3 9,2G 2,2G 6,6G 25% /tmpfs 252M 0 252M 0% /lib/init/rwudev 10M 64K 10M 1% /devtmpfs 252M 0 252M 0% /dev/shm/dev/sda1 879M 650M 229M 74% /media/PKBACK# 001/dev/hda4 4,7G 33M 4,7G 1% /mnt/part4

Para que se cargue en el inicio pondriamos los datos del mount en el fstab.

proc /proc proc defaults 0 0/dev/hda3 / ext3 defaults,errors=remount-ro 0 1/dev/hda2 none swap sw 0 0/dev/hdc /media/cdrom0 udf,iso9660 user,noauto 0 0/dev/fd0 /media/floppy0 auto rw,user,noauto 0 0/dev/hda4 /mnt/part4 auto rw,user,auto 0 1

Si pones noauto no se carga al principio, pero luego para montarla solo hace falta pasarle el punto de montaje.

#mount /mnt/part4

El comando du nos dice el espacio ocupado por directorio.

Nos dice lo que ocupa cada fichero del directorio.

debian:/home/jose# du /etc -h12K /etc/console-tools12K /etc/w3m4,0K /etc/apt/sources.list.d16K /etc/apt/apt.conf.d48K /etc/apt

Con la opcio -s nos pone la suma.

debian:/home/jose# du -sh3,3M

9/71

Page 10: Adminlinux I

Para que los volumenes montados salgan por defecto hay que ejecutar. Reiniciar y ejecutar ....

#gconf-editorY en aplicaciones/nautilus/ seleccionamos lo que queremos que salga

ARRANQUE DEL SISTEMA.

La configuracion de arranque del sistema está en

/etc/inittab

Si tenemos ubuntu este archivo esta cambiado a otro sitio...

debian:/home/jose# cat /etc/inittab# /etc/inittab: init(8) configuration.# $Id: inittab,v 1.91 2002/01/25 13:35:21 miquels Exp $

# The default runlevel.

Lo siguiente indica que inicia en el nivel dos esto quiere decir que va al directirio/etc/rc.2d/ y todo lo que empieza por s hace un start del demonio que le indica el enlace. En concreto

debian:/etc/rc2.d# lsREADME S20acpid S20exim4 S21nfs-common S99rmnologinS10sysklogd S20bittorrent S20hotkey-setup S89anacron S99stop-bootlogdS11klogd S20cpufrequtils S20makedev S89atdS18portmap S20cupsys S20openbsd-inetd S89cronS19hplip S20dbus S21gdm S99rc.local

id:2:initdefault:

# Boot-time system configuration/initialization script.# This is run first except when booting in emergency (-b) mode.si::sysinit:/etc/init.d/rcS

# What to do in single-user mode.~~:S:wait:/sbin/sulogin

# /etc/init.d executes the S and K scripts upon change# of runlevel.## Runlevel 0 is halt.# Runlevel 1 is single-user.

10/71

Page 11: Adminlinux I

# Runlevels 2-5 are multi-user.# Runlevel 6 is reboot.

...

O sea que si quiero preparar diferentes tipos de arranque cambio el nivel de arranque en el inittab y puedo parametriarme los directorios . Solo usar de 2 a 5

Todos los demonios de ejecucion estan en el directorio

/etc/init.d/demonio startPodemos usar la opcion start- restart -stop

Un forrma de ver los proceso es con ps o top#ps -ax#ps -fd#topA top le podemos pasar el proceso para hacer un kill . con Q salimos

El primer proceso que se ejecuta cuando se carga el kernel es el init

Podemos ver la salida del arbol de procesos padres e hijos#pstree | less

Para pasar a otro nivel se hace con el comando init# init 1 Esto pasaria al nivel uno cerraria lo que empieza K en el directorio 1 y arrancaria solo los demonios que empiezan por S

CRONTAB

Nos sirve para programar tareas. Lo tenemos en /etc

debian:/etc# cat 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/shPATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user command17 * * * * root cd / && run-parts --report /etc/cron.hourly25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )

En /etc/crontab se guardan las tareas programadas del sistema.

debian:/etc# cat crontab

11/71

Page 12: Adminlinux I

# /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/shPATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user command# Tareas todos los dias a las 17:0017 * * * * root cd / && run-parts --report /etc/cron.hourly#Tareas diarias25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )#Tareas Somanales47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )#Tareas Mensuales.52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )

Todos los shells scripts que ponemos en esos directorios los lanzará según el directorios diarioamente /semanalmente ....

Ademas podemos programar las tareas por cada usuario.

$ crontab -e // Para editar el fichero. No hace falta indicar el usuario$ crontab -l // Lista la programacion que tenemos.$ crontab -r // Borra todas las tareas programadas

Estas tareas se guardan por cada usuario en

/var/spool/cron/crontab/nombreDeUsuario

En /etc puedo crear los ficheros llamados /etc/cron.allow y /etc/cron.deny para permitir o denegar a ciertos usuario a programarse sus tareas.AT

Exite otro programador de tareas llamado at. Es más rápido.

# at 16:25 7 Nov -> me mostrara un promt para que le digamos los comandos que debe ejecutar. Para salir CTRL+D y se guarda la tarea.

debian:/etc# at 16:25 7 novwarning: commands will be executed using /bin/shat> ls -l > $home/mils.txtat> <EOT>job 1 at Wed Nov 7 16:25:00 2007debian:/etc# at -l1 Wed Nov 7 16:25:00 2007 a root

Como compilar un programa en codigo fuente.

12/71

Page 13: Adminlinux I

Lo primero que necesitamos es un compilador gcc y el make.Esto esta incluido en el paquete built-essential

debian:~# apt-get install build-essentialLeyendo lista de paquetes... HechoCreando árbol de dependencias... HechoSe instalarán los siguientes paquetes extras: g++ g++-4.1 gcc gcc-4.1 libc6-dev libssp0 libstdc++6-4.1-dev linux-kernel-headers

Vamos a probar a instalarnos como ejemplo un cliente en consola que se llama tmsnc. Esta en http://tmsnc.sourceforge.net

El fichero lo descargamos.jose@debian:~/Desktop/Descargas$ lstmsnc-0.3.2.tar.gz

Procedimiento general.1.- Configurar el programa para nuestra maquina2.- Lo compilamos3.- Lo instalamos.

Primero hay que descomprimlo y sacamos del tar.

$ tar xzvf fichero.tar.gz Donde x:sacar del tar

jose@debian:~/Desktop/Descargas$ tar xzvf tmsnc-0.3.2.tar.gz

1.- Para configurar el programa usar el configue. Para esto suele hacer falta tener el paquete ncurses-dev

jose@debian:~/Desktop/Descargas/tmsnc-0.3.2$ ./configurechecking for a BSD-compatible install... /usr/bin/install -cchecking whether build environment is sane... yeschecking for gawk... nochecking for mawk... mawk

.......

checking if the linker (/usr/bin/ld) is GNU ld... yeschecking for shared library run path origin... donechecking for iconv... yeschecking for iconv declaration... extern size_t iconv (iconv_t cd, char * *inbuf, size_t *inbytesleft, char * *outbuf, size_t *outbytesleft);checking for openssl... noconfigure: error: ssl.h not found in

ME avisa de que aun me falta una librería en este caso openssl que se llama

13/71

Page 14: Adminlinux I

libssl-dev

Ahora paso otra vez el /.configure y acaba bien

....config.status: creating autopackage/default.apspecconfig.status: creating src/config.hconfig.status: src/config.h is unchangedconfig.status: executing depfiles commands

Version: 0.3.2 Prefix: /usr/local CFLAGS: -g -O2

Talkfilter support: no i18n support: yes

2.- Compilacion con make

Ahora ya puedo pasa el make para compilar.

$ make

jose@debian:~/Desktop/Descargas/tmsnc-0.3.2$ makeMaking all in srcmake[1]: se ingresa al directorio `/home/jose/Desktop/Descargas/tmsnc-0.3.2/src'make all-ammake[2]: se ingresa al directorio `/home/jose/Desktop/Descargas/tmsnc-0.3.2/src'make[2]: se sale del directorio `/home/jose/Desktop/Descargas/tmsnc-0.3.2/src'make[1]: se sale del directorio `/home/jose/Desktop/Descargas/tmsnc-0.3.2/src'Making all in docmake[1]: se ingresa al directorio `/home/jose/Desktop/Descargas/tmsnc-0.3.2/doc'make[1]: No se hace nada para `all'.make[1]: se sale del directorio `/home/jose/Desktop/Descargas/tmsnc-0.3.2/doc'make[1]: se ingresa al directorio `/home/jose/Desktop/Descargas/tmsnc-0.3.2'make[1]: No se hace nada para `all-am'.make[1]: se sale del directorio `/home/jose/Desktop/Descargas/tmsnc-0.3.2'

3.- Para instalar. usar make install como ROOT

#make installjose@debian:~/Desktop/Descargas/tmsnc-0.3.2$ suPassword:debian:/home/jose/Desktop/Descargas/tmsnc-0.3.2# make installMaking install in srcmake[1]: se ingresa al directorio `/home/jose/Desktop/Descargas/tmsnc-0.3.2/src'make[2]: se ingresa al directorio `/home/jose/Desktop/Descargas/tmsnc-0.3.2/src'test -z "/usr/local/bin" || mkdir -p -- "/usr/local/bin" /usr/bin/install -c 'tmsnc' '/usr/local/bin/tmsnc'make[2]: No se hace nada para `install-data-am'.make[2]: se sale del directorio `/home/jose/Desktop/Descargas/tmsnc-0.3.2/src'make[1]: se sale del directorio `/home/jose/Desktop/Descargas/tmsnc-0.3.2/src'Making install in docmake[1]: se ingresa al directorio `/home/jose/Desktop/Descargas/tmsnc-

14/71

Page 15: Adminlinux I

0.3.2/doc'make[2]: se ingresa al directorio `/home/jose/Desktop/Descargas/tmsnc-0.3.2/doc'make[2]: No se hace nada para `install-exec-am'.test -z "/usr/local/share/man/man1" || mkdir -p -- "/usr/local/share/man/man1" /usr/bin/install -c -m 644 './tmsnc.1' '/usr/local/share/man/man1/tmsnc.1'make[2]: se sale del directorio `/home/jose/Desktop/Descargas/tmsnc-0.3.2/doc'make[1]: se sale del directorio `/home/jose/Desktop/Descargas/tmsnc-0.3.2/doc'make[1]: se ingresa al directorio `/home/jose/Desktop/Descargas/tmsnc-0.3.2'make[2]: se ingresa al directorio `/home/jose/Desktop/Descargas/tmsnc-0.3.2'make[2]: No se hace nada para `install-exec-am'.make[2]: No se hace nada para `install-data-am'.make[2]: se sale del directorio `/home/jose/Desktop/Descargas/tmsnc-0.3.2'make[1]: se sale del directorio `/home/jose/Desktop/Descargas/tmsnc-0.3.2'

COMPILACION DEL KERNEL. PONER MODULOS Y PARCHES

Para ver la version del Kernel:

$ uname -aLinux debian 2.6.18-5-686 #1 SMP Wed Oct 3 00:12:50 UTC 2007 i686 GNU/Linux

Las versiones pares son las estables.

Hay tres formas de compilar el kernel.

make configmake xconfigmake menuconfig

PASO A PASO PARA LA COMPILACION.

1.- Primero bajarme el fuente de www.kernel.org

Aquí selecionamos la ultima version estable.

En la Web encontramos....

The latest stable version of the Linux kernel is: 2.6.23.1 2007-10-12 16:47 UTC F V

En Enlace F -> Me descarga la version FullEn enlace V -> Me descarga el parche para pasar de la versión anterior a esta.

2.- Descomprimimos el kernel. Como es un bzip se hace con el siguiente comando.

$ tar xjvf fichero.bz2

3.- Ahora tenemos una carpeta con el todo el código fuente. La tenemos que

15/71

Page 16: Adminlinux I

mover a /usr/src. Esto lo debemos hacer como root

debian:/home/jose/Desktop/Descargas# mv linux-2.6.23.1 /usr/src

4.-Tenemos que hacer un enlace simbolico para que se llame /usr/src/linux

debian:/usr/src# ln -s /usr/src/linux-2.6.23.1/ /usr/src/linuxdebian:/usr/src# lslinux linux-2.6.23.1

Nota: La configuración del kernel que gastamos ahora mismo esta en /boot/config-version_del_nucleo

debian:/usr/src/linux# ls /bootconfig-2.6.18-4-686 initrd.img-2.6.18-4-686.bak vmlinuz-2.6.18-4-686config-2.6.18-5-686 initrd.img-2.6.18-5-686 vmlinuz-2.6.18-5-686grub System.map-2.6.18-4-686initrd.img-2.6.18-4-686 System.map-2.6.18-5-686

Una vez compilado por primera vez un nucleo en el fichero .configPara empezar una compilación a partir de las de actual nucleo podemos copiar la actual.

ebian:/usr/src/linux# cp /boot/config-2.6.18-5-686 .config

5.a- Nos metemos dentro de la carpeta /usr/src/linux y ponemos # ./make config5.b.- Podemos usar modo gráfico con # make xconfig5.c.- Podemos usar el modo texto con # make menuconfig (es necesario tener el paquete ncurses-dev)

Nota Tambien exite:Kernel-image: Una imagen compiladaKernel-headers : A veces es necesario para instalar una tarjeta que solo compiles lar kernel-headers.NOTA: Para virtualizar por XEN activar Virtualizacion-bae machine.

Mofificamos / añadimos y quitamos propiedades del kernel y salimos y guardamos.

A partir de aquí podemos seguir por el estilo clasico o el estilo debian...

16/71

Page 17: Adminlinux I

Estilo Clasico. ----

6.- Hacemos make dep para compilar las dependencias.

7a.- make bzImage -> imagen comprimida con bzip7b.- make Image -> Imagen sin comprimir7.c- make zImage -> Imagen comprimida con zip.

Esto crea la imagen en /usr/src/linux/arch/i386/boot Y copiaremos esa imagen en /boot

8.- make modules9.- make modules install

Estilo Debian -----

6.- Es necesario instalar el paquete kernel-package.

debian:/usr/src/linux# apt-get install kernel-package

7.- Creamos dos paquetes deb. El kernel-image.deb y el header.deb con el siguiente comando.

# make-kpkg -–initrd kernel_image kernel_headers -append_to_version=NOMBRE

En usr/src nos dejara los .deb de la imagen del kernel y las cabeceras.Nota: Los header no hacen falta realmente. solo si hiciera falta por algún dispositivo.

debian:/usr# cd src/debian:/usr/src# lslinuxlinux-2.6.23.1linux-image-2.6.23.1mikernel_2.6.23.1mikernel-10.00.Custom_i386.deb

17/71

Page 18: Adminlinux I

8.- Para instalarlo se hace ...

#dpkg -i paquete.deb

debian:/usr/src# dpkg -i linux-image-2.6.23.1mikernel_2.6.23.1mikernel-10.00.Custom_i386.debSeleccionando el paquete linux-image-2.6.23.1mikernel previamente no seleccionado.(Leyendo la base de datos ...73240 ficheros y directorios instalados actualmente.)Desempaquetando linux-image-2.6.23.1mikernel (de linux-image-2.6.23.1mikernel_2.6.23.1mikernel-10.00.Custom_i386.deb) ...Done.Configurando linux-image-2.6.23.1mikernel (2.6.23.1mikernel-10.00.Custom) ...Running depmod.Finding valid ramdisk creators.Using mkinitramfs-kpkg to build the ramdisk.Running postinst hook script /sbin/update-grub.You shouldn't call /sbin/update-grub. Please call /usr/sbin/update-grub instead!

Searching for GRUB installation directory ... found: /boot/grubSearching for default file ... found: /boot/grub/defaultTesting for an existing GRUB menu.lst file ... found: /boot/grub/menu.lstSearching for splash image ... none found, skipping ...Found kernel: /boot/vmlinuz-2.6.23.1mikernelFound kernel: /boot/vmlinuz-2.6.18-5-686Found kernel: /boot/vmlinuz-2.6.18-4-686Updating /boot/grub/menu.lst ... done

9.- Nos pone en el grub la imagen compilada como primera opción por defecto.

En este caso me agrega la prime opcion y como en opcion default tengo 0 arrancaria por ahí. En menu.lst se configura el grup

debian:/usr/src# cd /bootdebian:/boot# cd grub/debian:/boot/grub# cat menu.lst# menu.lst - See: grub(8), info grub, update-grub(8)# grub-install(8), grub-floppy(8),# grub-md5-crypt, /usr/share/doc/grub# and /usr/share/doc/grub-doc/.

## default num# Set the default entry to the entry number NUM. Numbering starts from 0, and# the entry number 0 is the default if the command is not used.## You can specify 'saved' instead of a number. In this case, the default entry# is the entry saved with the command 'savedefault'.# WARNING: If you are using dmraid do not change this entry to 'saved' or your# array will desync and will not let you boot your system.default 0

## timeout sec

18/71

Page 19: Adminlinux I

# Set a timeout, in SEC seconds, before automatically booting the default entry# (normally the first entry defined).timeout 5

# Pretty colourscolor cyan/blue white/blue

## password ['--md5'] passwd# If used in the first section of a menu file, disable all interactive editing# control (menu entry editor and command-line) and entries protected by the# command 'lock'# e.g. password topsecret# password --md5 $1$gLhU0/$aW78kHK1QfV3P2b2znUoe/# password topsecret

## examples## title Windows 95/98/NT/2000# root (hd0,0)# makeactive# chainloader +1## title Linux# root (hd0,1)# kernel /vmlinuz root=/dev/hda2 ro#

## Put static boot stanzas before and/or after AUTOMAGIC KERNEL LIST

### BEGIN AUTOMAGIC KERNELS LIST## lines between the AUTOMAGIC KERNELS LIST markers will be modified## by the debian update-grub script except for the default options below

## DO NOT UNCOMMENT THEM, Just edit them to your needs

## ## Start Default Options #### default kernel options## default kernel options for automagic boot options## If you want special options for specific kernels use kopt_x_y_z## where x.y.z is kernel version. Minor versions can be omitted.## e.g. kopt=root=/dev/hda1 ro## kopt_2_6_8=root=/dev/hdc1 ro## kopt_2_6_8_2_686=root=/dev/hdc2 ro# kopt=root=/dev/hda3 ro

## default grub root device## e.g. groot=(hd0,0)# groot=(hd0,2)

## should update-grub create alternative automagic boot options## e.g. alternative=true## alternative=false# alternative=true

## should update-grub lock alternative automagic boot options## e.g. lockalternative=true## lockalternative=false# lockalternative=false

19/71

Page 20: Adminlinux I

## additional options to use with the default boot option, but not with the## alternatives## e.g. defoptions=vga=791 resume=/dev/hda5# defoptions=

## should update-grub lock old automagic boot options## e.g. lockold=false## lockold=true# lockold=false

## Xen hypervisor options to use with the default Xen boot option# xenhopt=

## Xen Linux kernel options to use with the default Xen boot option# xenkopt=console=tty0

## altoption boot targets option## multiple altoptions lines are allowed## e.g. altoptions=(extra menu suffix) extra boot options## altoptions=(single-user) single# altoptions=(single-user mode) single

## controls how many kernels should be put into the menu.lst## only counts the first occurence of a kernel, not the## alternative kernel options## e.g. howmany=all## howmany=7# howmany=all

## should update-grub create memtest86 boot option## e.g. memtest86=true## memtest86=false# memtest86=true

## should update-grub adjust the value of the default booted system## can be true or false# updatedefaultentry=false

## ## End Default Options ##

title Debian GNU/Linux, kernel 2.6.23.1mikernelroot (hd0,2)kernel /boot/vmlinuz-2.6.23.1mikernel root=/dev/hda3 roinitrd /boot/initrd.img-2.6.23.1mikernelsavedefault

title Debian GNU/Linux, kernel 2.6.23.1mikernel (single-user mode)root (hd0,2)kernel /boot/vmlinuz-2.6.23.1mikernel root=/dev/hda3 ro singleinitrd /boot/initrd.img-2.6.23.1mikernelsavedefault

title Debian GNU/Linux, kernel 2.6.18-5-686root (hd0,2)kernel /boot/vmlinuz-2.6.18-5-686 root=/dev/hda3 roinitrd /boot/initrd.img-2.6.18-5-686savedefault

title Debian GNU/Linux, kernel 2.6.18-5-686 (single-user mode)root (hd0,2)kernel /boot/vmlinuz-2.6.18-5-686 root=/dev/hda3 ro single

20/71

Page 21: Adminlinux I

initrd /boot/initrd.img-2.6.18-5-686savedefault

title Debian GNU/Linux, kernel 2.6.18-4-686root (hd0,2)kernel /boot/vmlinuz-2.6.18-4-686 root=/dev/hda3 roinitrd /boot/initrd.img-2.6.18-4-686savedefault

title Debian GNU/Linux, kernel 2.6.18-4-686 (single-user mode)root (hd0,2)kernel /boot/vmlinuz-2.6.18-4-686 root=/dev/hda3 ro singleinitrd /boot/initrd.img-2.6.18-4-686savedefault

### END DEBIAN AUTOMAGIC KERNELS LIST

# This is a divider, added to separate the menu items below from the Debian# ones.title Other operating systems:root

# This entry automatically added by the Debian installer for an existing# linux installation on /dev/hda1.title SUSE Linux Enterprise Server 10 SP1 (on /dev/hda1)root (hd0,0)kernel /boot/vmlinuz-2.6.16.46-0.12-default root=/dev/disk/by-id/ata-ST340014A_5JXHZYGJ-part1 vga=0x303 resume=/dev/hda2 splash=silent showoptsinitrd /boot/initrd-2.6.16.46-0.12-defaultsavedefaultboot

# This entry automatically added by the Debian installer for an existing# linux installation on /dev/hda1.title Failsafe -- SUSE Linux Enterprise Server 10 SP1 (on /dev/hda1)root (hd0,0)kernel /boot/vmlinuz-2.6.16.46-0.12-default root=/dev/disk/by-id/ata-ST340014A_5JXHZYGJ-part1 vga=normal showopts ide=nodma apm=off acpi=off noresume nosmp noapic maxcpus=0 edd=off 3initrd /boot/initrd-2.6.16.46-0.12-defaultsavedefaultboot

Para aplicar un parche a un kernel.

1. Tememos el codigo fuente.2. Bajamos el parche Fichero *.dif3. Pasamos el parche al codigo fuente.4. patch -p1 < dichero.dif5. Compilamos de forma normal

21/71

Page 22: Adminlinux I

MODULOS

Para ver los modulos que tiene un kernel cargado en un momento dado.

# lsmod | less

Para cargar el modulo nuevo que tenemos disponible.

# modprobe modulo

Para ver los modulos disponibles para ese kernel en su compilacion# modprobe -l | less

Si algún modulo no esta disponible habria que compilar el kernel otra vez y marcar el modulo como disponible.

En el archivo /etc/modules estan los modulos que quiero que siempre carge al inicio de la maquina

debian:/etc# cat modules# /etc/modules: kernel modules to load at boot time.## This file contains the names of kernel modules that should be loaded# at boot time, one per line. Lines beginning with "#" are ignored.

loop

Descargamos un modulo de memoria con...

# modprobe -r modulo

Para ver de forma grafica los modulos disponible podemos instalar el paquete modconf.

# apt-get install modconf

22/71

Page 23: Adminlinux I

RECUPERACION DEL SISTEMA EN CASO DE FALLO.

Logs del sistema se guardan en ..

/var/log/messages/var/log/syslog

dmess -> Informacion del arranque del kernel.

Listar el HW PCI

lspci -llspci -v

lsub -> Nos dice los USB conectados. Si tenemos un linux que no arranca...1.- Arrancariamos desde CD con una version live-CD2.- Cargariamos la particion del linux que no arranca en algun sitio del sistema Live-CD

mkdir /mnt/linux_malmount /dev/hda3 /mnt/linux_mal

3.- Podemos acceder al los ficheros del sistema.4.-Tenemos que hacer uba jaula sobre un directorio con chroot. Todo lo que hagamos dentro de esto no afectará al resto del sistema.

5.- El /mnt/proc Estará vacio porque ese sistema no tiene procesos.Luego hay que montarlo de tipo procmount -t proc none /mnt/linux_mal/proc6.- Tambien para los devicesmount -o bind /dev /mnt/linux_mal/dev

7.- Lanzamos chroot para que cree una jaula para que actue como su estubiera en el sistema averiado.# chroot /mnt/linux_mal/ /bin/bashAhora es como si ubieramos arrancado desde el discp del linux averiado.Para salir de la jaula : exit

8.- Si ni tenemos red podemos lanzar el eht0 para que la pille# dhcclient eth0

9.- Para instalar grub

#grub-install /dev/hdaCopia la configuracion del grub y la instala en el MBR

23/71

Page 24: Adminlinux I

Como podriamos ahora chequear el sistema de fichero.

Para esto el fs debe estar desmontado.

fsck /dev/hda3o fsck.ext3 /dev/hda3 -> Si no sabe el tipo de particion y yo se lo digo.

4.- CONFUGURACON DE LA RED LOCAL

Es conveniente deshabilitar el network manager de gnome, ya que utiliza otros ficheros de configuracion.Para eso entramos en Prederencias /Sesiones

Y lo desctivamos

24/71

Page 25: Adminlinux I

Ficheros de configuración de red.

Archivo de configuración de red

/etc/network/interfaces

jose@debian:~$ cat /etc/network/interfaces# This file describes the network interfaces available on your system# and how to activate them. For more information, see interfaces(5).

# The loopback network interfaceauto loiface lo inet loopback

# The primary network interfaceallow-hotplug eth0iface eth0 inet dhcpjose@debian:~$

Si quetemos poner los parametros de forma estatica cambiomos dhcp por static y ponemos los parametros de configuración.

allow-hotplug eth0iface eth0 inet staticaddress X.X.X.Xnetmask X.X.X.Xbroadcast X.X.X.Xnetwork X.X.X.Xgateway X.X.X.X

Para configurar la red desde linea de comandos.

#ifcondig ethX X.X.X.X netmask X.X.X.X

ifup ethXifdown ethX

Para establecer las routas por defecto

# route -nKernel IP routing tableDestination Gateway Genmask Flags Metric Ref Use Iface192.168.2.0 0.0.0.0 255.255.255.0 U 0 0 0 eth00.0.0.0 192.168.2.50 0.0.0.0 UG 0 0 0 eth0

Para añadir una ruta de forma manual

# route add default gw X.X.X.X netmask 0.0.0.0

25/71

Page 26: Adminlinux I

Para añadirle otra red

route add -net 192.168.3.0 netmask 255.255.255.0 gw 192.168.2.50

Por cada servidor DNS tenemos una linea en /etc/resolv.conf

debian:/home/jose# cat /etc/resolv.conf# generated by NetworkManager, do not edit!

nameserver 192.168.0.10

Para tener un listado entre nombres e IP los tenemos en este fichero.

/etc/hosts

Para poner las redes que tenemos./etc/networks

El nombre de la maquina lo ponemos en el fichero

/etc/hostname

Los puertos de servicios del servidor los podemos ver en

/etc/services

Nos dice los protocolos en /etc/protocos

26/71

Page 27: Adminlinux I

CONFIRGURAR UN SERVIDOR DHCP

Instalamos el servidor

debian:/etc/network# apt-get install dhcp

La configuracion de la enterface de escucha se hace en /etc/default/dhcpAquí le diremos la interface donde escucharemos para servir dhcp

# On what interfaces should the DHCP server (dhcpd) serve DHCP requests?# Separate multiple interfaces with spaces, e.g. "eth0 eth1".INTERFACES="eth0"

Primero vamos a poner una IP fija modificando /etc/network/interfaces.

#iface eth0 inet dhcpiface eth0 inet staticaddress 192.168.4.4netmask 255.255.255.0broadcast 192.168.4.255network 192.168.4.0gateway 192.168.4.254

Reiniciamos la red

debian:/etc/network# ifdown eth0ifdown: interface eth0 not configureddebian:/etc/network# ifup eth0

Para configurara el DHCP se utiliza le fichero. /etc/dhcpd.confEn este se pueden definir opciones por defecto al principio y luego para cada subred redefinir estas opciones de la siguiente forma:

subnet 192.168.4.0 netmask 255.255.255.0 {

default-lease-time 600;#Tiempo max que guarda la IP antes de liberarlamax-lease-time 7200;range 192.168.4.1 192.168.4.20;#Mascara del la ips#option subnet-mask 255.255.255.0;option broadcast-address# Dominio que le asignaria la los nombres de los clientesoption domain-name port.com;# Los DNS que dara al clienteoption domain-name-servers 192.168.4.1 ;# el GW por defectooption routers 192.168.4.1;use-host-decl-name on;}

Para asignar ipfijas según las MAC de las tarjetas de red se hace de la siguiente

27/71

Page 28: Adminlinux I

forma en el fichero de configuracion del dhcp.

host wxp-jsalom {harware ethernet 00:E5:34:4C:8E:68;fixed-address 192.168.4.5;server-names 192.168.4.1;

}

Para arrancar el servidor dhcp hacemos:

debian:/etc# /etc/init.d/dhcp restartStopping DHCP server: dhcp.Starting DHCP server: dhcpd.

Para hacer una prueba de recibir la ip desde un servidor DHCP podemos usar la utilidad dhclient eth0.

debian:/etc# dhclient eth0Internet Systems Consortium DHCP Client V3.0.4Copyright 2004-2006 Internet Systems Consortium.All rights reserved.For info, please visit http://www.isc.org/sw/dhcp/

Listening on LPF/eth0/00:11:43:b4:1b:edSending on LPF/eth0/00:11:43:b4:1b:edSending on Socket/fallbackDHCPDISCOVER on eth0 to 255.255.255.255 port 67 interval 3DHCPOFFER from 192.168.7.1DHCPREQUEST on eth0 to 255.255.255.255 port 67DHCPACK from 192.168.7.1bound to 192.168.7.21 -- renewal in 256 seconds.

Si queremos que el sevidor dhcpd no se reinicie cada vez habría que quitarlo de los ficheros de arranque de los diferentes niveles.Esto se puede hacer automáticamente con:

debian:/etc/network# update-rc.d -f dhcp remove Removing any system startup links for /etc/init.d/dhcp ... /etc/rc0.d/K20dhcp /etc/rc1.d/K20dhcp /etc/rc2.d/S20dhcp /etc/rc3.d/S20dhcp /etc/rc4.d/S20dhcp /etc/rc5.d/S20dhcp /etc/rc6.d/K20dhcp

Interfaces web muy bueno para administracion es webmin

28/71

Page 29: Adminlinux I

5.- NFS (Network File System)

Nos permite compartir carpetas en el mundo UNIXConsta de dos partes:

En la parte servidormountd : Montar los ficherros donde queramos.nfsd: El demonio que gestiona el tema portmap: para el RPC.

En el cliente solo necesitamoutdnfsd:

Instalación :

#apt-get install nfs-kernel-server#apt-get install portmap

El comando de portmap para ver las conexiones RPC que tenemos en el equipo debe ser.

#rpcinfo -p programa vers proto puerto 100000 2 tcp 111 portmapper 100000 2 udp 111 portmapper 100024 1 udp 32769 status 100024 1 tcp 52979 status 100003 2 udp 2049 nfs 100003 3 udp 2049 nfs 100003 4 udp 2049 nfs 100021 1 udp 32776 nlockmgr 100005 1 udp 658 mountd 100005 1 tcp 661 mountd 100005 2 udp 658 mountd 100005 2 tcp 661 mountd.....

El servidor para que exporte unos determinados directorios lo tengo qe poner en /etc/export con un formato como sigue.

/directorio MaquinaClientes (opciones)

Por defecto el NFS intenta asiciar los UID de los cliente con los que existan en el servidor . Esto puede generar problemas de seguridad.

Las opciones las tenemos el la página 86

root_squash: Traslada el UID/GID del root cliente al anonymous del servidor.all_squash : Cada usuario que mapee la carpeta traslada su UID al UID anonymous del servidor.map_daemon: Para que traslade los UID clientes en el Servidor.

29/71

Page 30: Adminlinux I

PRACTICA NFS.

debian:/mnt# mkdir remotoCreo un usuario para acceder a la carpetadebian:/mnt# useradd -u 3000 -s /bin/bash nfsuserLe doy permisos al usuaio.debian:/mnt# chown nfsuser /mnt/remoto

Para montar el directorio remoto al que quiero acceder pongo.

debian:/etc# mount 192.168.2.25:/mnt/remoto /mnt/remoto

En el mount podemos usar opciones rw : Lectura escriturahard, rsize=8192, wsize=8192 : Aumentar la velocidad de trasferencia

Cada vez que hagamos cambios en el fichero export, o reiniciamos el serv nfs o ejecutamos exportfs -ra

Esto puede ser util por ejemplo para poner en fstab los montajes de NFS y por ejemplo mapear los /homes de los usuarios en un servidor.

30/71

Page 31: Adminlinux I

INSTALAR VMWARE SERVER

NOTA: Copia remota con el ssh de un origen a un destino de forma encriptada. Necesitamos tener instalado el ssh.NOTA: Si la ethrnet de la maquina virtual la tengo en britged nos dara una ip a la maquina virtual y otra a la nuestra.

debian:/mnt# scp 192.168.2.25:/mnt/remoto/VM* /rootThe authenticity of host '192.168.2.25 (192.168.2.25)' can't be established.RSA key fingerprint is 8a:27:bd:1e:d7:27:b1:41:58:e9:f1:df:e9:ec:0b:18.Are you sure you want to continue connecting (yes/no)? yPlease type 'yes' or 'no': yesWarning: Permanently added '192.168.2.25' (RSA) to the list of known [email protected]'s password:VMware-server-1.0.4-56528.tar.gz 100% 102MB 9.2MB/s 00:11

Intenta conectarse con el mismo usuario local en la maquina remota, si queremos especificarle el usuario usar la @ antes de la IP remota:debian:/mnt# scp [email protected]:/mnt/remoto/VM* /root

Descomprimimos el fichero en un directorio

# tar -xzvf Vmware-server-1.0.4-56528.tar.gz

Para instalarlo tenemos que tener las headers del kernel.

# apt-get install linux-headers-2.6.18-4-686

Estas tambien se instalan cuando instalamos el paquete built-essential.

El instalador es vmware-install.pl

Lo ejecutamos y le damos a todo por defecto.

debian:~/vmware-server-distrib# ./vmware-install.plA previous installation of VMware software has been detected.

The previous installation was made by the tar installer (version 3).

Keeping the tar3 installer database format.

Uninstalling the tar installation of VMware Server.

Stopping VMware services: Virtual machine monitor done

The removal of VMware Server 1.0.4 build-56528 for Linux completedsuccessfully. Thank you for having tried this software.

Installing the content of the package.

In which directory do you want to install the binary files?[/usr/bin]

What is the directory that contains the init directories (rc0.d/ to rc6.d/)?[/etc]

31/71

Page 32: Adminlinux I

What is the directory that contains the init scripts?[/etc/init.d]

In which directory do you want to install the daemon files?[/usr/sbin]

In which directory do you want to install the library files?[/usr/lib/vmware]

The path "/usr/lib/vmware" does not exist currently. This program is going tocreate it, including needed parent directories. Is this what you want?[yes]

In which directory do you want to install the manual files?[/usr/share/man]

In which directory do you want to install the documentation files?[/usr/share/doc/vmware]

The path "/usr/share/doc/vmware" does not exist currently. This program isgoing to create it, including needed parent directories. Is this what you want?[yes]

The installation of VMware Server 1.0.4 build-56528 for Linux completedsuccessfully. You can decide to remove this software from your system at anytime by invoking the following command: "/usr/bin/vmware-uninstall.pl".

Before running VMware Server for the first time, you need to configure it byinvoking the following command: "/usr/bin/vmware-config.pl". Do you want thisprogram to invoke the command for you now? [yes]

Making sure services for VMware Server are stopped.

Stopping VMware services: Virtual machine monitor done

Leemos la licencia .....

Trying to find a suitable vmmon module for your running kernel.

None of the pre-built vmmon modules for VMware Server is suitable for yourrunning kernel. Do you want this program to try to build the vmmon module foryour system (you need to have a C compiler installed on your system)? [yes]

#Aquí es donde utilizará las cabeceras para compilar unos modulos.

Do you want networking for your virtual machines? (yes/no/help) [yes] yes

Configuring a bridged network for vmnet0.

The following bridged networks have been defined:

. vmnet0 is bridged to eth0

All your ethernet interfaces are already bridged.

Do you want to be able to use NAT networking in your virtual machines? (yes/no)[yes]

Configuring a NAT network for vmnet8.

32/71

Page 33: Adminlinux I

Do you want this program to probe for an unused private subnet? (yes/no/help)[yes]

Probing for an unused private subnet (this can take some time)...

...

Type XXXXX-XXXXX-XXXXX-XXXXX or 'Enter' to cancel: 92WRN-YH60K-282EM-4TJKR

Starting VMware services: Virtual machine monitor done Virtual ethernet done Bridged networking on /dev/vmnet0 done Host-only networking on /dev/vmnet1 (background) done Host-only networking on /dev/vmnet8 (background) done NAT service on /dev/vmnet8 done

VMware Server sobre Debianhttp://www.marqueta.org/linux/vmware-debian/¿Por qué olvido siempre cómo se llama el paquetito que tengo que instalar cada vez que se actualiza el kernel para poder compilar los módulos de VMware? apt-get install linux-headers-$(uname -r)ln -s /usr/src/linux-headers-2.6.18-5-686 /usr/src/linux

La consola se cuelga al pulsar el botón browse

Seguir las instrucciones de este enlace: Workaround

1. Open a terminal and su to root. su

2. Change to the libpng12.so.0 directory. cd /usr/lib/vmware/lib/libpng12.so.0

3. Rename the libpng12.so.0 file within that directory. mv libpng12.so.0 libpng12.so.0.old

4. Create a new soft link for this file. ln -sf /usr/lib/libpng12.so.0 libpng12.so.0

5. Now change the the libgcc_s.so.1 directory. cd /usr/lib/vmware/lib/libgcc_s.so.1

6. Rename the libgcc_s.so.1 file within that directory. mv libgcc_s.so.1 libgcc_s.so.1.old

7. Create a new soft link for this file. ln -sf /lib/libgcc_s.so.1

8. Restart VMware and you should now be able to use the browse option.

33/71

Page 34: Adminlinux I

WEBMIN

Hay que ir a www.webmin.com

Nos bajamos el fichero *.deb

Para instalarlo dpkg -i paquete.deb

debian:/home/jose# dpkg -i webmin_1.380_all.debSeleccionando el paquete webmin previamente no seleccionado.(Leyendo la base de datos ...82819 ficheros y directorios instalados actualmente.)Desempaquetando webmin (de webmin_1.380_all.deb) ...dpkg: problemas de dependencias impiden la configuración de webmin: webmin depende de libnet-ssleay-perl; sin embargo: El paquete `libnet-ssleay-perl' no está instalado. webmin depende de libauthen-pam-perl; sin embargo: El paquete `libauthen-pam-perl' no está instalado. webmin depende de libio-pty-perl; sin embargo: El paquete `libio-pty-perl' no está instalado. webmin depende de libmd5-perl; sin embargo: El paquete `libmd5-perl' no está instalado.dpkg: error al procesar webmin (--install): problemas de dependencias - se deja sin configurarSe encontraron errores al procesar: webmin

34/71

Page 35: Adminlinux I

Pero falla por que hay algunas dependencias .

Si ponemos a continuación apt-get -f install me lo instala con lo que falta

debian:/home/jose# apt-get -f installLeyendo lista de paquetes... HechoCreando árbol de dependencias... HechoCorrigiendo dependencias... ListoSe instalarán los siguientes paquetes extras: libauthen-pam-perl libio-pty-perl libmd5-perl libnet-ssleay-perlSe instalarán los siguientes paquetes NUEVOS: libauthen-pam-perl libio-pty-perl libmd5-perl libnet-ssleay-perl0 actualizados, 4 se instalarán, 0 para eliminar y 5 no actualizados.1 no instalados del todo o eliminados.Necesito descargar 273kB de archivos.Se utilizarán 1221kB de espacio de disco adicional después de desempaquetar.¿Desea continuar [S/n]? s

Ahora entramos a la aplicaciónhttps://localhost:10000

35/71

Page 36: Adminlinux I

6.- OpenLDAP

¿Que vamos a hacer?

Lo que vamos a intentar es tener un servidor Ldap donde tendremos la cuentas de usuario/ grupos y los host. Las maquinas clientes se validarán todos con esas cuentas de usuario. Podríamo hacer tambien que el directorio de usuario levantara su home como NFS para que lo pueda ver en cualquier lado. Esto es solo para Linux.

En el Serv LDAP guardaría objetos de la red y atributos de estos.La información se estructura en una estructura de tipo arbol. Toda entrada viene identificada inequivocamente por el DN (Distingiser Name).Para darle funcionalidad existen esquemas (que definen la extructura ) para almacenar los datos. Por defecto viene posixAccount. Para samba tendremos que poner otro esquema.

dn: uid=pepe, ou=People, dc=admon, dc=comobjectClass: personcn: Jose Garcíasn: Garcíadescription: alumnomail: [email protected]

El formato en el que se han mostrado los atributos del objeto se denomina LDIF (LDAP Data Interchange Format), y resulta útil conocerlo porque es el formato que los servidores LDAP (y OpenLDAP entre ellos) utilizan por defecto para insertar y extraer información del directorio.

36/71

Page 37: Adminlinux I

INSTALACIÓN OpenLDAP.

Para ello instalamos el paquete slapd

apt-get install slapd

Nos pude instroducir la contraseña de administrador de LDAP. Luego para configurarlo hacermos

#dpkg-reconfigure slapd

Configuración:● Le ponemos el nombre de dominio.● Nombre de la orgranizacion ponemos tambien el dominio.● Ponemos contraseñas● Le decimos Base de datos BDB● En permitir protocolo LDAPv2 ponemos NO.

37/71

Page 38: Adminlinux I

La configuracion se guarda en /etc/default/slapdEl puerto 389 es donde trabaja LDAP.# netstat -tanCon esto tenemos instalado el servidor.

Instala utilidades para cambiar contraseñas, buscar (ej: ldapsearch ).... Pero nosotros para dar de alta usuario lo podemos hacer con una interface gráfica.phpldapadmin - web based interface for administering LDAP servers

apt-get install phpldapadmin

38/71

Page 39: Adminlinux I

apt-get install ldap-utils

Ejemplo # ldapsearch -x -b '' -s base '(objectclass=*)' namingContexts

Para migrar el /etc/passwd /etc/group ... debemos instalar el paquete de herramientas:

# apt-get install migrationtoolsO nos bajamos el paquete MigrationTools.tgz

debian:/home/jose# tar xvzf MigrationTools.tgzMigrationTools-47/MigrationTools-47/ads/MigrationTools-47/ads/migrate_passwd_ads.plMigrationTools-47/ads/migrate_all_online_ads.sh

Aquí tenemos un monton de script en sh y pl para hacer las migraciones.

Estos archivos shell estan preparados para un dominio especifico. Luego hay que ir al migrate_common.ph editarlo y poner el nuestro en DEFAULT_MAIL_DOMAIN y DEFAUL_MAIL_HOST y DEFAULT_BASE.

....# Default DNS domain$DEFAULT_MAIL_DOMAIN = "jose.es";...# Default base$DEFAULT_BASE = "dc=jose,dc=es";# domains (similiar to MASQUERADE_DOMAIN_FILE).$DEFAULT_MAIL_HOST = "mail.jose.es";...

Migracion de los datos locales al Directorio LDAP

Ahora ya podemos crear la base del directorio. Esto lo hacemos con migrate_base.plEsta informacion se guardará en un fichero tipo ldif.

#./migrate_base.pl > base.ldif

debian:/home/jose/MigrationTools-47# ./migrate_base.pl > base.ldif

Ahora agregamos este fichero a la base de datos de ldap.

debian:/home/jose/MigrationTools-47# ldapadd -x -c -D "cn=admin,dc=jose,dc=es" -W -f base.ldifEnter LDAP Password:adding new entry "dc=jose,dc=es"ldap_add: Already exists (68)f

Ahora migramos los usuario con sus passwords.# ./migrate_passwd.pl /etc/passwd > user.ldif

39/71

Page 40: Adminlinux I

Ahora editamos el fichero y solo dejaremos el root y los usuarios normales

Luego añadimos el usuario nuestro directorio LDAP

# ldapadd -x -c -D "cn=admin,dc=jose,dc=es" -W -f user.ldifEnter LDAP Password:adding new entry "uid=jose,ou=People,dc=jose,dc=es"

Ahora añadimos el /etc/group

# ./migrate_group.pl /etc/group > group.ldif

Limpiamos y dejamos los grupos de usuarios en group.ldif. y los añadimos al Ldap# ldapadd -x -c -D "cn=admin,dc=jose,dc=es" -W -f group.ldif

PARTE DEL CLIENTE

El archivo de conf de los clientes es /etc/ldap/ldap.conf

Donde solo tocaremos la variable HOST Y BASEdebian:/etc/ldap# cat ldap.conf# $OpenLDAP: pkg/ldap/libraries/libldap/ldap.conf,v 1.9 2000/09/04 19:57:01 kurt Exp $## LDAP Defaults#

# See ldap.conf(5) for details# This file should be world readable but not world writable.

BASE dc=jose, dc=esHOST 192.168.2.24

Para que el cliente pueda autenticar hay que instalar dos bibliotacas.PAM y NSS. Esto se instala en el cliente de la siguiente forma:

#apt-get install libpam-ldapPonemos la ip del servidor ldap://IPVersion 3Make local root database admin : Decir SI

40/71

Page 41: Adminlinux I

41/71

Page 42: Adminlinux I

# apt-get install libnss-ldap

Hay que editar el /etc/nsswitch.conf

De los datos de passwd /groups poner detras de “compat” la palabra “ldap” para decirle que despues de buscar el local si no lo encuentra lo busque en el ldap.

debian:/etc# cat nsswitch.conf# /etc/nsswitch.conf## Example configuration of GNU Name Service Switch functionality.# If you have the `glibc-doc-reference' and `info' packages installed, try:# `info libc "Name Service Switch"' for information about this file.

passwd: compat ldapgroup: compat ldapshadow: compat ldap

Luego en el directorio /etc/pam.d hay que retocar los archivos common-account common-session common-passwd

Luego hay que modificar los ficheros en los clientes de /etc/pam.d/

debian:/etc/pam.d# cat common-account

42/71

Page 43: Adminlinux I

## /etc/pam.d/common-account - authorization settings common to all services## This file is included from other service-specific PAM config files,# and should contain a list of the authorization modules that define# the central access policy for use on the system. The default is to# only deny service to users whose accounts are expired in /etc/shadow.#account required pam_unix.soaccount sufficient pam_ldap.so

debian:/etc/pam.d# cat common-session## /etc/pam.d/common-session - session-related modules common to all services## This file is included from other service-specific PAM config files,# and should contain a list of modules that define tasks to be performed# at the start and end of sessions of *any* kind (both interactive and# non-interactive). The default is pam_unix.#session required pam_limits.sosession required pam_unix.sosession optional pam_ldap.so

debian:/etc/pam.d# cat common-auth## /etc/pam.d/common-auth - authentication settings common to all services## This file is included from other service-specific PAM config files,# and should contain a list of the authentication modules that define# the central authentication scheme for use on the system# (e.g., /etc/shadow, LDAP, Kerberos, etc.). The default is to use the# traditional Unix authentication mechanisms.#auth sufficient pam_unix.soauth sufficient pam_ldap.so try_first_passauth required pam_env.soauth required pam_securetty.soauth required pam_unix_auth.soauth required pam_warn.soauth required pam_deny.so

debian:/etc/pam.d# cat common-password## /etc/pam.d/common-password - password-related modules common to all services## This file is included from other service-specific PAM config files,# and should contain a list of modules that define the services to be#used to change user passwords. The default is pam_unix

# The "nullok" option allows users to change an empty password, else# empty passwords are treated as locked accounts.## (Add `md5' after the module name to enable MD5 passwords)## The "obscure" option replaces the old `OBSCURE_CHECKS_ENAB' option in# login.defs. Also the "min" and "max" options enforce the length of the

43/71

Page 44: Adminlinux I

# new password.

#password required pam_unix.so nullok obscure min=4 max=8 md5

# Alternate strength checking for password. Note that this# requires the libpam-cracklib package to be installed.# You will need to comment out the password line above and# uncomment the next two in order to use this.# (Replaces the `OBSCURE_CHECKS_ENAB', `CRACKLIB_DICTPATH')## password required pam_cracklib.so retry=3 minlen=6 difok=3# password required pam_unix.so use_authtok nullok md5password required pam_cracklib.so retry=3 nimlen=8 difok=4password sufficient pam_unix.so use_authtok md5 shadowpassword sufficient pam_ldap.so use_authtokpassword required pam_warn.sopassword required pam_deny.so

Ahora de debe instalar el paquete libpam-cracklib

debian:/etc/pam.d# apt-get install libpam-cracklibLeyendo lista de paquetes... HechoCreando árbol de dependencias... HechoSe instalarán los siguientes paquetes extras: cracklib-runtime cracklib2

Para comprobar que funciona poner

getent passwdgetent groupgetent host

La herramienta grafica para gestionar el LDAP es phpldapadmin

apt-get install phpldapadmin

Directorio HOME centralizado

Lo siguiente seria que los usuario tuvieran el dir $HOME en red .

Para eso en el servidor serviriamos por NFS el directorio

Modificando /etc/exportcon /home 192.168.2.0/24 (rw)

# /etc/exports: the access control list for filesystems which may be exported# to NFS clients. See exports(5).## Example for NFSv2 and NFSv3:# /srv/homes hostname1(rw,sync) hostname2(ro,sync)## Example for NFSv4:# /srv/nfs4 gss/krb5i(rw,sync,fsid=0,crossmnt)# /srv/nfs4/homes gss/krb5i(rw,sync)#

44/71

Page 45: Adminlinux I

/home 192.168.2.0/24 (rw)

En el cliente Poniendo en ftab

192.168.2.1:/home home nfs ...

PRACTICA OpenLDAP

Creamos una maquina virtual debian con Ethernet 1 como britged.Tomamos ip en la MV con #dhcpclient

Instalamos OpenLdap en el Servidor.

45/71

Page 46: Adminlinux I

SERVIDOR DE IMPRESION CUPS

Sirve tanto de sev. de impresion como de cliente.

Para instalarlo.#apt-get install cupsys

Para ver si entá en funcionamiento. Vemos si está escuchando por su puerto 631

#netstat -tan

La configuracion de CUPS está en /etc/cups/cupsd.confRetocamos algunos datos del fichero para que funcione.

cat cupsd.conf### Sample configuration file for the Common UNIX Printing System (CUPS)# scheduler. See "man cupsd.conf" for a complete description of this# file.#

# Log general information in error_log - change "info" to "debug" for# troubleshooting...LogLevel warning

# Administrator user group...SystemGroup lpadmin

# Only listen for connections from the local machine.Listen localhost:631Listen /var/run/cups/cups.sock

# Show shared printers on the local network.Browsing OnBrowseOrder allow,deny

# JAS Indicamos a quien dejamos ver nuestras impresoras.#BrowseAllow @LOCALBrowseAllow 192.168.2.255

# JAS para decirle a quien queremos ser visibles.BrowseAddress 192.168.2.255

# Default authentication type, when authentication is required...DefaultAuthType Basic

# Restrict access to the server...# JAS Para permitir imprimir a la gente añadir la dir de nuestra red<Location /> Order allow,deny Allow localhost Allow 192.168.2.255

46/71

Page 47: Adminlinux I

</Location>

# Restrict access to the admin pages...# JAS Para decir a quien dejamos administrar<Location /admin> Encryption Required Order allow,deny Allow localhost</Location>....

Vamos al navegador y ponemos localhost:631 y aparecerá el administrador de CUPS

AÑADIR UNA IMPRESORA

En AddPrinter añadimos una impresoraPonemos un nombre a la impresoraSeleccionamos el dispositivo (ej: LPT1)Seleccionamos el tipo de impresora.Si faltan driver instalar más con el paquete. foomatic-filters.ppds o bajarse un fichero PPD del proveedor de la impresora.

Añadir una impresora de redEn el dispositivo poner internet protocol (htpp).El nombre sería

47/71

Page 48: Adminlinux I

Red . Impresora con tarjeta de red. Como las de HP.socket://______:9100

Red CUPShttp://_________:631/printers/cola

Red SAMBA

SMB://____________:__/nombre_impr

Para reiniciar el servicio de CUPS

# /etc/init.d/cupsys restart

Configurar un cliente linux para imprimir por impresoras remotas de CUPS

Dentro del fichero ponemos

servername IP_DEL_SERV_DE IMPRESION.Con esto cuando ponemos añadir impresoras me muestra la lista de impresoras de este servidor.

48/71

Page 49: Adminlinux I

COPIAS DE SEGURIDAD.

Software Libre de copia de seguridad. amanda o vacula

Aquí utilizaremos uno mas sencillo:rsysn

Ibstalarlo con

apt-get install rsync

man rsysn

Nos sirve para sincronizar directorios y el origen y destino podrán ser local o remoto.

#rsync *.c server:/var/datos

Con esto sincronizariamos todos los *.c a /var/datos del servidor. Esto la primera vez los pasa todo y luego solo envia los cambios.Este comando se debe poner como una tarea en el cron para que lo haga

Se puede hacer al revés

rsync -avvz server:/var/datos /roota Conseva propiedades del archivovv Verbose. Da informaciónz Para quecomprima

Por defecto en el destino solo añade (no borra).Si queremos que borre debemos ponerrsync -avvz --delete server:/var/datos /root

Hay que tener cuidado con hacer...rsync /var/datos IP:/backup

Cogera el directorio destino y lo creará (el dir datos) debajo de backup

rsync /var/datos/ IP:/backup

En este caso no crea el directorio sino que copia los ficheros.Por defecto se conecta como nobody.

PARA CONFIGURAR UN SERVIDOR DE RSYC Que es donde tenemos lo datos.Para configurar el servidor rsync se hace en Debe existir /etc/rsyncd.conf si no lo creamos.

Configuraremos los usuario

uid=root

49/71

Page 50: Adminlinux I

gid=rootuse chroot=nosyslog facility=daemon# Definimos la gente que se puede conectar.host allow=*max connections=4uid=rootgid=rootuse chroot=nosyslog facility=daemon# Definimos la gente que se puede conectar.host allow=*max connections=4

IMPORTANTE.Poner el /etc/default/rsinc RSYNC_ENABLE a true# defaults file for rsync daemon mode

# start rsync in daemon mode from init.d script?# only allowed values are "true", "false", and "inetd"# Use "inetd" if you want to start the rsyncd from inetd,# all this does is prevent the init.d script from printing a message# about not starting rsyncd (you still need to modify inetd's config yourself).RSYNC_ENABLE=true

Si queremos que desde el cliente lanzamos el rsync

#rsync -avvz IP_SERVER::datos /var/backup/datos

/etc/init.d/rsync restart

Para guardar los datos del proceso y los errores en el mismo fichero podemos añadir al comando que se ejecuta en el cliente.#rsync -avvz IP_SERVER::datos /var/backup/datos > log_proceso 2>&1

Compresión y Empaquetado de ficheros

EMPAQUETADOtar cvf backyp.tar /hometar xvzf backyp.tgz /home

c Empaquetarx Desempaquetarl Listarv Verbosef nombre del ficheroz comprimir en zipj cimprimir en bzip2

50/71

Page 51: Adminlinux I

PARTIMAGE

# apt-get install partimage

Description: backup partitions into a compressed image file Partition Image is a partition imaging utility. It has support for the following file systems: * Ext2/3, the linux standard * Reiser3, a journalised and powerful file system * FAT16/32, DOS and Windows file systems * HPFS, IBM OS/2 file system * JFS, journalised file system, from IBM, used on AIX * XFS, another journalised and efficient file system, from sgi, used on Irix * UFS (beta), Unix file system * HFS (beta), MacOS File system * NTFS (experimental), Windows NT, 2000 and XP Only used blocks are copied and stored into an image file. The image file can be compressed in the GZIP/BZIP2 formats to save disk space, and split into multiple files to be copied onto removable media (ZIP for example), burned on a CD-R, etc. . This makes it possible to save a full Linux/Windows system with a single operation. In case of a problem (virus, crash, error, etc.), you just have to restore, and after several minutes, your entire system is restored (boot, files, etc.), and fully working. . This is very useful when installing the same software on many machines: just install one of them, create an image, and restore the image on all other machines.

#partimage

51/71

Page 52: Adminlinux I

PARTED.

Puedes redimensionar particiones Para hacer cambios sobre una partición debe de estar desmontada.

apt-get parted# parted /dev/hdaGNU Parted 1.7.1Using /dev/hdaWelcome to GNU Parted! Type 'help' to view a list of commands.(parted)(parted) print

Disk /dev/hda: 40,0GBSector size (logical/physical): 512B/512BPartition Table: msdos

Number Start End Size Type File system Flags 1 32,3kB 10,7GB 10,7GB primary ext3 boot 2 10,7GB 11,8GB 1078MB primary linux-swap 3 11,8GB 21,8GB 10,0GB primary ext3 4 21,8GB 40,0GB 18,2GB primary reiserfs

gparted -> Entorno gráfico de parted#apt-get install gparted

52/71

Page 53: Adminlinux I

IMAGEN DEL SO en FORMATO ISO (como ghost)

Copiado de un disco del sistema 1.- Entrar con un live-CD2.- Harcer una imagen del disco.dd if=/dev/hdaX of=copia

dd if=/dev/hda1 of=/mnt/usb

Cuando tengamos que hacer una Restauracion 1.-Entrar con un live-CD2.- Restarurardd if=copia of=/dev/hdaX

SYSTEM RESCUE CD *Descargar.

Es un cd-live de linux orientada a recate de sistema. Incluye aplicaciones como partimage, gparted, ntpass (te funde contraseñas de windows), parted

53/71

Page 54: Adminlinux I

SAMBA y WINBIND

Se utiliza para compartir recursos mediante el protocolo SMB.Tambien nos permitirá pertenecer a una red windows.

#apt-get install samba smbclientdebian:~/backup# apt-get install samba smbclientLeyendo lista de paquetes... HechoCreando árbol de dependencias... HechoSe instalarán los siguientes paquetes extras: samba-commonPaquetes sugeridos: smbfsPaquetes recomendados smbldap-toolsSe instalarán los siguientes paquetes NUEVOS: samba samba-common smbclient...

Tiene dos partes que las gestiona mediante lo demonios:

nmbd Gestiona los nombres de NETBIOSsmbd Gestiona los recursos de red y como accedor a estos

Para reiniciar el servicios de SAMBA hacemos:

# /etc/init.d/samba restartStopping Samba daemons: nmbd smbd.Starting Samba daemons: nmbd smbd.

La configuración está en:

/etc/samba/smb.conf

Para que un usuario de windows pueda entrar en samba ese usuario debe existir en la maquina linux tambien (no hace falta que el password coincida o exista).

Puedo crearlo sin shell ni password#useradd -m -d /home/userwin -s /bin/false userwin

Luego lo puedo añadir a samba y ponemos la contraseña.#smbpasswd -a userwin

Para que el samba mire los usuario de un dominio windows utilizaremos winbindapt-get install winbind

Para comprobar si esta escuchando mirar si escucha en los puertos 139 y 445

54/71

Page 55: Adminlinux I

Tiene varias secciones

[global]

[homes]Según el usuario que se conecte desde un máquina windows verá un recurso que se ofrece.

[printers]

Estudio del fichero de configuración

debian:/etc/samba# cat smb.conf## Sample configuration file for the Samba suite for Debian GNU/Linux.### This is the main Samba configuration file. You should read the# smb.conf(5) manual page in order to understand the options listed# here. Samba has a huge number of configurable options most of which# are not shown in this example## Any line which starts with a ; (semi-colon) or a # (hash)# is a comment and is ignored. In this example we will use a ## for commentary and a ; for parts of the config file that you# may wish to enable## NOTE: Whenever you modify this file you should run the command# "testparm" to check that you have not made any basic syntactic# errors.#

#======================= Global Settings =======================

[global]

## Browsing/Identification ###

# Change this to the workgroup/NT-domain name your Samba server will part of workgroup = CURSO# Esto hay que añadirlo para que tenga nombre de NetBIOS netbios name = SERVIDOR-9# server string is the equivalent of the NT Description field server string = %h server

# JAS Añadimos username map = /etc/samba/smbusers

# Windows Internet Name Serving Support Section:# WINS Support - Tells the NMBD component of Samba to enable its WINS Server; wins support = no

# WINS Server - Tells the NMBD components of Samba to be a WINS Client# Note: Samba can be either a WINS Server, or a WINS Client, but NOT both

55/71

Page 56: Adminlinux I

; wins server = w.x.y.z

# This will prevent nmbd to search for NetBIOS names through DNS. dns proxy = no

# What naming service and in what order should we use to resolve host names# to IP addresses; name resolve order = lmhosts host wins bcast

#### Networking ####

# The specific set of interfaces / networks to bind to# This can be either the interface name or an IP address/netmask;# interface names are normally preferred# JAS Si tibieramos mas de una interface la definiriamos; interfaces = 127.0.0.0/8 eth0

# Only bind to the named interfaces and/or networks; you must use the# 'interfaces' option above to use this.# It is recommended that you enable this feature if your Samba machine is# not protected by a firewall or is a firewall itself. However, this# option cannot handle dynamic or non-broadcast interfaces correctly.; bind interfaces only = true

#### Debugging/Accounting ####

# This tells Samba to use a separate log file for each machine# that connects log file = /var/log/samba/log.%m

# Put a capping on the size of the log files (in Kb). max log size = 1000

# If you want Samba to only log through syslog then set the following# parameter to 'yes'.; syslog only = no

# We want Samba to log a minimum amount of information to syslog. Everything# should go to /var/log/samba/log.{smbd,nmbd} instead. If you want to log# through syslog you should set the following parameter to something higher. syslog = 0

# Do something sensible when Samba crashes: mail the admin a backtrace panic action = /usr/share/samba/panic-action %d

####### Authentication ######## JAS Hay cuatro tipos de seguridad de SAMBA.;share: Le ponemos contraseña al recurso (como Win98) ya no se gasta;user : Para cada recurso de la red pedirá autenticacion de usuario y contraseña;server: La autencación será mediante un servidor determinado (KERBEROS o Win2000);domain: Que pertenece a un dominio

# "security = user" is always a good idea. This will require a Unix account# in this server for every user accessing the server. See# /usr/share/doc/samba-doc/htmldocs/Samba3-HOWTO/ServerType.html# in the samba-doc package for details.# JAS Puede tener varios tipos USER/SHARE /SERVER /DOMAIN

56/71

Page 57: Adminlinux I

# El tipo DOMAIN con wmind security = user

# You may wish to use password encryption. See the section on# 'encrypt passwords' in the smb.conf(5) manpage before enabling. encrypt passwords = true

# If you are using encrypted passwords, Samba will need to know what# password database type you are using.# Tipo de base de datos passdb backend = tdbsam

obey pam restrictions = yes

; guest account = nobody# Si lo gastamos como PDC si que hay que comentar la line siguiente invalid users = root

# This boolean parameter controls whether Samba attempts to sync the Unix# password with the SMB password when the encrypted SMB password in the# passdb is changed.; unix password sync = no

# For Unix password sync to work on a Debian GNU/Linux system, the following# parameters must be set (thanks to Ian Kahan <<[email protected]> for# sending the correct chat script for the passwd program in Debian Sarge). passwd program = /usr/bin/passwd %u passwd chat = *Enter\snew\sUNIX\spassword:* %n\n *Retype\snew\sUNIX\spassword:* %n\n *password\supdated\ssuccessfully* .

# This boolean controls whether PAM will be used for password changes# when requested by an SMB client instead of the program listed in# 'passwd program'. The default is 'no'.; pam password change = no

########## Domains ###########

# Is this machine able to authenticate users. Both PDC and BDC# must have this setting enabled. If you are the BDC you must# change the 'domain master' setting to no#

# JAS Es para decir que este SAMBA se controlador de Dominio; domain logons = yes## The following setting only takes effect if 'domain logons' is set# It specifies the location of the user's profile directory# from the client point of view)# The following required a [profiles] share to be setup on the# samba server (see below)

# Donde guardaria los perfiles de los usuarios; logon path = \\%N\profiles\%U# Another common choice is storing the profile in the user's home directory; logon path = \\%N\%U\profile

# The following setting only takes effect if 'domain logons' is set# It specifies the location of a user's home directory (from the client# point of view)# JAS Donde podremos sus unidad de home

57/71

Page 58: Adminlinux I

; logon drive = H:; logon home = \\%N\%U

# The following setting only takes effect if 'domain logons' is set# It specifies the script to run during logon. The script must be stored# in the [netlogon] share# NOTE: Must be store in 'DOS' file format convention# JAS La estructura tipica es /home/samba/profiles# /home/samba/netlogon# JAS Los scripts de arranque

; logon script = logon.cmd

# This allows Unix users to be created on the domain controller via the SAMR# RPC pipe. The example command creates a user account with a disabled Unix# password; please adapt to your needs; add user script = /usr/sbin/adduser --quiet --disabled-password --gecos "" %u

########## Printing ##########

#JAS Samba se integran con CUPs para eso descomentamos las lineas (*)## If you want to automatically load your printer list rather# than setting them up individually then you'll need this#(*) load printers = yes

# lpr(ng) printing. You may wish to override the location of the# printcap file; printing = bsd ; printcap name = /etc/printcap

# CUPS printing. See also the cupsaddsmb(8) manpage in the# cupsys-client package.#(*) printing = cups#(*) printcap name = cups

# When using [print$], root is implicitly a 'printer admin', but you can# also give this right to other users to add drivers and set printer# properties; printer admin = @ntadmin

############ Misc ############

# Using the following line enables you to customise your configuration# on a per machine basis. The %m gets replaced with the netbios name# of the machine that is connecting; include = /home/samba/etc/smb.conf.%m

# Most people will find that this option gives better performance.# See smb.conf(5) and /usr/share/doc/samba-doc/htmldocs/Samba3-HOWTO/speed.html# for details# You may want to add the following on a Linux system:# SO_RCVBUF=8192 SO_SNDBUF=8192 socket options = TCP_NODELAY

# The following parameter is useful only if you have the linpopup package# installed. The samba maintainer and the linpopup maintainer are

58/71

Page 59: Adminlinux I

# working to ease installation and configuration of linpopup and samba.; message command = /bin/sh -c '/usr/bin/linpopup "%f" "%m" %s; rm %s' &

# Domain Master specifies Samba to be the Domain Master Browser. If this# machine will be configured as a BDC (a secondary logon server), you# must set this to 'no'; otherwise, the default behavior is recommended.# JAS Dirimamos que si, en caso que queremos que sea controlador de dominio; domain master = auto

# Some defaults for winbind (make sure you're not using the ranges# for something else.); idmap uid = 10000-20000; idmap gid = 10000-20000; template shell = /bin/bash;; The following was the default behaviour in sarge; but samba upstream reverted the default because it might induce; performance issues in large organizations; See #368251 for some of the consequences of *not* having; this setting and smb.conf(5) for all details# JAS Tambien para tema de Domino; winbind enum groups = yes; winbind enum users = yes

#======================= Share Definitions =======================

# Aquí definimos los recursos a compartir, las secciones van de corcheres a corchetes[homes] comment = Home Directories browseable = no ; Que sea visible

# By default, the home directories are exported read-only. Change next# parameter to 'yes' if you want to be able to write to them.# JAS Para permitir o no escribir en el directorio writable = no ; Para que pueda o no escribir en el recurso.

# File creation mask is set to 0700 for security reasons. If you want to# create files with group=rw permissions, set next parameter to 0775.# JAS Mascara de acceso a ficheros create mask = 0700

# Directory creation mask is set to 0700 for security reasons. If you want to# create dirs. with group=rw permissions, set next parameter to 0775.# JAS Mascara para directorios directory mask = 0700

# Restrict access to home directories# to the one of the authenticated user# This might need tweaking when using external authentication schemes valid users = %S ; %S Es el usuario que inicia la sesion

# Un-comment the following and create the netlogon directory for Domain Logons# (you need to configure Samba to act as a domain controller too.)# Esto es para cuando SAMBA haga de PDC;[netlogon] ; Defino el escrip; comment = Network Logon Service; path = /home/samba/netlogon; guest ok = yes; writable = no

59/71

Page 60: Adminlinux I

; share modes = no

# Compartir un recurso concreto[gestion] path = /var/datos/gestion# Si quiero dar permiso a un grupo de pongo una @ delante. valid users = curso,curso10, @grupo read only = No create mask = 0700 directory mask = 0700# available = No

# Un-comment the following and create the profiles directory to store# users profiles (see the "logon path" option above)# (you need to configure Samba to act as a domain controller too.)# The path below should be writable by all users so that their# profile directory may be created the first time they log on# Los perfiles del usuario para cuando haga de PDC se pondrán aquí;[profiles] ; Definimos el perfirles de los usuario.; comment = Users profiles; path = /home/samba/profiles; guest ok = no; browseable = no; create mask = 0600; directory mask = 0700

[printers]# JAS . Aquí se ponen las impresoras importadas de CUPS comment = All Printers browseable = no path = /var/spool/samba printable = yes public = no writable = no create mode = 0700

# Windows clients look for this share name as a source of downloadable# printer drivers# JAS aquí se meten los drivers.[print$] comment = Printer Drivers path = /var/lib/samba/printers# Es este path se ponen los drives de una forma especial #/var/lib/samba/printers/W3K.. browseable = yes read only = yes guest ok = no# Uncomment to allow remote administration of Windows print drivers.# Replace 'ntadmin' with the name of the group your admin users are# members of.; write list = root, @ntadmin

# A sample share for sharing your CD-ROM with others.;[cdrom]; comment = Samba server's CD-ROM; writable = no; locking = no; path = /cdrom; public = yes

# The next two parameters show how to auto-mount a CD-ROM when the

60/71

Page 61: Adminlinux I

# cdrom share is accesed. For this to work /etc/fstab must contain# an entry like this:## /dev/scd0 /cdrom iso9660 defaults,noauto,ro,user 0 0## The CD-ROM gets unmounted automatically after the connection to the## If you don't want to use auto-mounting/unmounting make sure the CD# is mounted on /cdrom#; preexec = /bin/mount /cdrom; postexec = /bin/umount /cdrom

PRÁCTICA DE SAMBA

Copiamos una imagen virtual de windows de prueba del servidor con scp:

# scp 192.168.2.3:/home/luis/Desktop/winxp.tar.gz /root/The authenticity of host '192.168.2.3 (192.168.2.3)' can't be established.RSA key fingerprint is d5:df:52:38:55:f6:87:4c:21:74:52:fa:31:b8:61:a4.Are you sure you want to continue connecting (yes/no)? yesWarning: Permanently added '192.168.2.3' (RSA) to the list of known [email protected]'s password:winxp.tar.gz 100% 668MB 1.7MB/s 06:44...

Creamos un usuario en linux para acceder a los recursos samba

61/71

Page 62: Adminlinux I

debian:~# useradd -m -d /home/curso -s /bin/false curso

Creamos tambien el usuario en samba y aquí le añadimos la contraseña:

debian:/etc/samba# smbpasswd -a cursoNew SMB password:Retype new SMB password:Added user curso.

Luego en el WINXP y como tenemos dado de alta el usuario curso accederá al recurso sin problemas.

Podremos entrar a un recurso llamado [curso] ya que la definición del recurso HOME reemplaza el nombre por el nombre del usuario.

[homes] comment = Home Directories browseable = no# By default, the home directories are exported read-only. Change next# parameter to 'yes' if you want to be able to write to them. writable = yes

Instalamos swat

# aptitude install swat

Accedemos a traber del puerto 901 del localhost. A traves de esta aplicación podemos administrar de forma grafica el SAMBA

62/71

Page 63: Adminlinux I

Tambien se pude configurar gráficamente con webmin

MONTAR UNA RECURSO CON SAMBA AL ESTILO NFS

Tenemossmbclient : Permite conectarnos a una maquina con el protocolo SMBsmbclient -L servidor -Uusuario

# smbclient -L localhost -UcursoPassword:Domain=[SERVIDOR-9] OS=[Unix] Server=[Samba 3.0.24]

Sharename Type Comment --------- ---- ------- print$ Disk Printer Drivers IPC$ IPC IPC Service (debian server) IMPRESORA_JOSE Printer IMPRESORA_JOSE curso Disk Home DirectoriesDomain=[SERVIDOR-9] OS=[Unix] Server=[Samba 3.0.24]

Server Comment --------- -------

Workgroup Master --------- ------- CURSO WINXP

63/71

Page 64: Adminlinux I

Para acceder al directorio y nos devuelba un shell en este ponemos.

#smbclient //SERVIDO/RECURSO -Uusuario

smbmount: Para montar carpetas de recursos compartidos.

#smbmount -t smbfs -o username=usuario, passwd=contraseña //SERVIDOR/RECURSO /mnt/punto_montaje

smbfs:

COMO HACER QUE EL SERVIDOR SAMBA HAGA FUNCIONES DE PDC.

Tenemos que agregar al fichero smbd.conf lo siguiente. en el apartado GLOBAL

Hay que descomentar estos apartados en globallocal master = yesdomain master = yes# Es el nivel que tiene el DOMINIOos level = 65prefered master = yesdomain logons = yeslogon path = \\%L\profile\%Ulogon drive = H:

add user script = /usr/sbin/useradd -m %udelete user script = /usr/sbin/userdel -r %uadd group script = /usr/sbin/groupadd %gdelete group script = /usr/sbin/groupdel %gadd user to group script = /usr/sbin/usermod -G %g %uadd machine script = /usr/sbin/useradd -s /bin/false -d /var/lib/nobody %uidmap uid = 15000-20000idmap gid = 15000-20000

Y ponemos invalid user a root. (Buscar la opción y corregir)#invalid users = root

Hay que crear el fichero smbuser y poner al root como administrador

#cat smbusersroot= Administrador

Modificamos tambien los apartador de [Netlogon] y [profile]

64/71

Page 65: Adminlinux I

# Esto es para cuando SAMBA haga de PDC#Hay que crear los directorios de netlogon y profiles de la siguiente forma:# mkdir -p /home/samba/profiles# mkdir -p /home/samba/netlogon# Deben de tener permisos 777#Poner writale =yes

[netlogon] ; Defino el escrip comment = Network Logon Service path = /home/samba/netlogon guest ok = yes writable = yes ;share modes = no

# Un-comment the following and create the profiles directory to store# users profiles (see the "logon path" option above)# (you need to configure Samba to act as a domain controller too.)# The path below should be writable by all users so that their# profile directory may be created the first time they log on# Los perfiles del usuario para cuando haga de PDC se pondrán aquí# aquí se guardaren lo que se ejecuta al princicio[profiles] ; Definimos el perfirles de los usuario. comment = Users profiles path = /home/samba/profiles writable =yes public=no create mask = 0777 directory mask = 0777; guest ok = no; browseable = no

Ahora creamos un usuario que no este en el windows para comprobar.

#useradd -m -d /home/curso11 -s /bin/false curso11#smbpasswd -a curso11

Luego añado una máquina en el dominio (en el linux se creará una cuenta de maquina que se distingue por que acaba en $). Para añadir usuario al dominio en el windows utilizo el usuario administrador del dominio. En este caso root.

Para hacer la prueba vamos a poner el serv Linux 192.168.17.1 y al Windows 192.168.17.2

#ifconfig eth0 192.168.17.1 netmask 255.255.255.0Creo los ficheros mkdir -p /home/samba/profiles mkdir -p /home/samba/netlogon# Deben de tener permisos 777

Asegurarme que el usuario root esta en samba#smbpasswd -a root

Creamos un usuario para probar #useradd -m -d /home/usudown -s /bin/false usudown

65/71

Page 66: Adminlinux I

#smbpasswd -a usudown

PRACTICA SAMBA

Creamos una carpeta en C:\curso del windows y la montaremos desde samba en el linux como si fuera un NFS.Hay que tener instalado el paquete smbfs

1.- Compartir el fichero en el Windows2.- En linux poner #mount -t smbfs //192.168.2.36/compartida /mnt/win -o username=curso,password=debian

3.-para ponetlo en fstab //192.168.2.x/compartida /destino smbfs defaults,credentials=/root/claves 0 0

Nota: Las claves no las ponemos directamente en fstab para que nadie las pueda ver.

Para comprobar si me valido en un windows con este servidor :

#smbclient -L IP_WIN -Uusuario

PRACTICA DE METER UN LINUX EN UN DOMINIO , con WINBIND

[global] security = domain netbios name = debian realm = PRUEBAS.LOCAL password server = ad.pruebas.local workgroup = PRUEBAS log level = 1 syslog = 0 idmap uid = 10000-29999 idmap gid = 10000-29999 winbind separator = + winbind enum users = yes winbind enum groups = yes winbind use default domain = yes template homedir = /home/%D/%U template shell = /bin/bash client use spnego = yes domain master = no server string = linux como cliente de AD encrypt passwords = yes

66/71

Page 67: Adminlinux I

Unir el equipo al dominio: net rpc join -S NOMBRE-DOMINIO -UAdministrador-dominio

Editar "/etc/nsswitch.conf" y modificar las siguientes lineas dejándolas así:

passwd: files winbindgroup: files winbindshadow: files winbindhosts: files dns winbind

# /etc/init.d/winbind restart

Verificar la integración del dominio:- "net rpc testjoin" muestra si esta correctamente integrada al dominio:

Join to 'PRUEBAS' is OK

- "net ads info" muestra información del dominio:

"net rpc info -U Usuario_de_dominio" muestra el dominio al que pertenece, numero de usuarios, grupos, etc:

Domain Name: PRUEBASDomain SID: x-x-x-xx-xxxxxxxxxx-xxxxxxxxxx-xxxxxxxxxSequence number: xxNum users: xxNum domain groups: xxNum local groups: xx

Verificar que winbind este funcionando:- "wbinfo -u" lista usuarios del dominio.- "wbinfo -g" lista grupos del dominio.- "getent passwd" muestra usuarios locales y del dominio.- "getent group" muestra grupos locales y del dominio.

* "su usuario-de-dominio" nos convertimos en usuario-de-dominio.

Configurar la autenticaciónPara configurar el acceso a usuarios del dominio a nuestro Linux mediante el entorno gráfico hay que configurar pam. Para ello editamos los siguientes archivos y agregamos/modificamos las siguientes lineas:

/etc/pam.d/common-accountaccount sufficient pam_winbind.soaccount required pam_unix.so try_first_pass

/etc/pam.d/common-authauth sufficient pam_winbind.soauth required pam_unix.so nullok_secure try_first_pass

/etc/pam.d/common-passwordpassword sufficient pam_winbind.sopassword required pam_unix.so nullok obscure min=4 max=8 md5

try_first_pass /etc/pam.d/common-session session required pam_mkhomedir.so skel=/etc/skel/ umask=0022

session sufficient pam_winbind.sosession required pam_unix.so try_first_pass

El modulo "pam_winbind.so" le indica a pam que los usuarios y grupos los obtenga mediante winbind. El modulo "pam_mkhomedir.so" nos crea el directorio home del usuario en caso de no existir.

67/71

Page 68: Adminlinux I

PRACTICA FINAL PERMISOS Y USUARIOS, SISTEMAS DE FICHEROS, MONITORIZACION DEL SISTEMA,

SAMBA Y RSYNC

Jefe Comerciales Secretari@s--------------------------------------------------------------------

jose esther ximocarlos pepa

-- Crear los siguientes usuarios y grupo en Linux.

#useradd -d /home/user -m -s/bin/bash -G grupo nombreuser

useradd -d /home/jose -m -s/bin/bash -G users joseuseradd -d /home/esther -m -s/bin/bash -G users estheruseradd -d /home/carlos -m -s/bin/bash -G users carlosuseradd -d /home/ximo -m -s/bin/bash -G users ximouseradd -d /home/pepa -m -s/bin/bash -G users pepa

-- Crear usuarios y grupos "comercio" y "secre" e incluir a quien corresponda.

addgroup comercioaddgroup secre

Edito /etc/group y añado los usuarios que a los que pertenecen cada uno:

comercio:x:1001:jose,esther,carlossecre:x:1002:jose,ximo,pepa

-- Crear carpetas departamentales "/var/datos/comercial" y "/var/datos/secretariado" con las siguientes caracteristicas:

- A la carpeta "/var/datos/comercial" SOLO podra entrar root y el grupo "comercio" con permisos totales.

- A la carpeta "/var/datos/secretariado" SOLO podra entrar root y el grupo "secre" con permisos totales.

- Ademas, a la carpeta "/var/datos/comercial", grupo "secre" podra entrar y tendra permisos de LECTURA.

mkdir -p /var/datos/comercialmkdir -p /var/datos/secretariado

#chgrp comercio /var/datos/comercial#chgrp secre /var/datos/ secretariado# chmod g+w+x+r *Instalamos el paquete ACL para dar permiso al grupo secre de lectua a comercial.

68/71

Page 69: Adminlinux I

# getfacl comercial/# file: comercial# owner: root# group: comerciouser::-w-group::rwxother::---

#setfacl -m group:secre:r /var/datos/comercial

getfacl /var/datos/comercial/getfacl: Removing leading '/' from absolute path names# file: var/datos/comercial# owner: root# group: comerciouser::-w-group::rwxgroup:secre:r--mask::rwxother::---

-- El usuario "jose" va a poder LEER TODO incluidas las carpetas departamentales.

Para que jose tambien acceda a los home :# chmod g+w+x+r /home/*o# chmod 770 /home/*

-- Crearemos una tarea que se ejecute 1 vez a la semana que creara un informe con el espacio ocupado por cada uno de los usuarios. Acto seguido, mandará un mail al usuario jose con este reporte.

Ponermos en el cron..

du -sh /home/esther /home/ximo /home/carlos /home/pepa /home/jose /var/datos/comercial /var/datos/secretariado > /home/jose/informe.txtcat /home/jose/informe.txt | mail -s ”INFORME” [email protected]

Metemos esto en un fichero.sh y le damos permisos de ejecucion.

Luego lo invocamos desde el fichero /etc/cron.weekly para que se ejecute semanalemte.

-- Crearemos 2 recursos samba que se llamarán 'secre' y 'comercio' que

69/71

Page 70: Adminlinux I

apuntaran a /var/datos/secre y /var/datos/comercio respectivamente y sólo podrán entrar los del grupo que corresponda y jose

[secre] path= /var/datos/secretariado valid users = @secre read only = No create mask = 0770 directory mask = 0770 writable = yes

[comercio] path= /var/datos/comercial valid users = @comercio read only = No create mask = 0770 directory mask = 0770 writable = yes

-- Crear recursos en rsync para sincronizar remotamente las carpetas de datos /var/datos/comercial y /var/datos/secretariado

rsync -avvz server:/var/datos/comercial /rootrsync -avvz server:/var/datos/secretariado /root

Nota: PARA DAR PERMISOS CON MAS DETALLE. Utilizamos las ACLsTodos los ficheros tiene ACL

1.- Instalar primero el paquete acl.

#apt-get install acl

2.- Hay que poner en el file system que queremos modificar las acl la opcion acl

# /etc/fstab: static file system information.## <file system> <mount point> <type> <options> <dump> <pass>proc /proc proc defaults 0 0/dev/hda3 / ext3 defaults,errors=remount-ro,acl 0 1

#getfacl fichero#serfacl fichero

Para dar a un usuario concrero permisos a un fichero sin que pertenezca a un grupo concreto y sin dar permisos a todos los usuario lo hacemos

#setacl -m user:usuario:rw fichero

70/71

Page 71: Adminlinux I

Nota: Para ver en tiempo real en una consola lo que pasa por syslog usar:

debian:/home/jose# tail -f /var/log/syslog

Nota: Para conectarte por Terminal server a Windows

# apt-get tsclient

Nota : VirtualBox

Nota :MAYUSCULA + FLECHA IZQ + PAG ARRIBA -- > Voy para arriba en la consola de texto

Nota: ALT+CONTROL+F1 : Nos lleva a la consola de textoALT+F7: Vuelve al entorno Xwindow

TRUCO: Para tener raton el la consola instalar paquete apt-get install gpm

Un comando para saber que tipo de fichero es:

#file ______

http://windowslibre.osl.ull.es/web/cdlibre.html

softonic.com

Para aprender sobre tec. Webhttp://www.w3schools.com/

[email protected]

[email protected]

71/71