miércoles, 29 de junio de 2011

REDES LINUX 2

Servidores en Redes Linux

lunes, 27 de junio de 2011

PROCEDIMIENTOS O SCRIPTS


Una secuencia de comandos de Shell, usada muy frecuentemente, puede almacenarse en un fichero. El nombre del fichero puede ser usado más tarde para ejecutar la secuencia almacenada con un comando sencillo.

Variables: El usuario puede controlar la conducta del Shell, como también otros programas y utilidades, almacenando información en las variables.

Construcciones de programación: El Shell incluye características que permiten su uso como lenguaje de programación.

Tales características se pueden usar para construir los procedimientos que ejecuten operaciones complejas.

Caracteres especiales: echo : Esta orden sirve para imprimir una cadena de texto en la pantalla.


Definición de variables: Una vez definidas las variables guardan un valor que el usuario puede modificar para variar el comportamiento del Shell.

Para fijar un valor se teclea read  seguido de un espacio y el nombre de la variable que desea asignarle.


Mostrar el valor de la variable: El Shell detecta el carácter $ que le indica que lo que sigue es el nombre de una variable, reemplazando todo por su valor.


5.3 EJEMPLOS DE SCRIPTS EN SHELL

$ vi   programa_1
clear
echo “digite un nombre:”
read nom
clear
echo “mi nombre es:$nom”

:wq!
$ sh   programa_1

$ vi   programa_2
clear
tput cup 3 5; echo “ Entre un número: “
read num1
tput cup 4 5; echo “ Entre segundo número “
read num2
sum=`expr  $num1  +  $num2`
clear
tput cup 5 6;  echo  “ El  Total de la suma es:  $sum  “
:x
$ sh  programa_2

En el anterior ejemplo el programa añade las siguientes funciones.

1. tput cup fila columna: Posiciones de pantalla de filas y columnas

2. variable=`expr $variable  +  $variable`: Permite realizar operaciones matemáticas como por ejemplo sumas, restas, multiplicación, división.

Comparación entre números:

-eq  “ = “
-ne  “ <> “
-gt  “ >  “
-ge  “ >= “
-le   “ <= “
-lt   “ < “

Ejemplo:

Entrar dos números y decir cual es el mayor

$vi  programa_3
clear
echo “ entre un numero: “
read num1
echo  “ entre otro numero: “
read  num2

if   test  $num1 -gt  $num2
    then
        echo “ el mayor es $num1 “
     else
         echo “ el mayor es $num2 “
fi
:x
$ sh programa_3

Ejemplos de scripst:

1)

clear
echo -n    "Primer Numero: "
read     num1
echo -n    "Segundo Numero: "
read     num2
echo -n    "Tercer Numero: "
read     num3
clear
if     test    $num1   -ge    $num2   -a    $num2   -gt    $num3
       then
       tput   cup   15    5;echo   "El mayor es:   $num1"
       tput   cup   17   5;echo   "En orden ascendente:    $num3   $num2    $num1"

elif    test    $num1    -ge    $num3    -a    $num3    -gt    $num2
          then 
          tput    cup   15   5;  echo   "El mayor es:   $num1"
          tput    cup   17   5;  echo   "En orden ascendente:    $num2   $num3    $num1"

elif    test    $num2    -ge    $num1    -a    $num1    -gt    $num3
         then 
         tput    cup   15    5;   echo    "El mayor es:   $num2"
         tput    cup   17    5;   echo    "En orden ascendente:    $num3   $num1    $num2"

elif    test    $num2    -ge    $num3   -a    $num3   -gt    $num1
         then 
         tput   cup   15    5;  echo   "El mayor es:   $num2"
         tput   cup   17    5;  echo   "En orden ascendente:    $num1   $num3    $num2"

elif   test    $num3    -ge    $num2   -a    $num2   -gt    $num1
         then 
         tput   cup    15    5;   echo    "El mayor es:   $num3"
         tput   cup    17    5;   echo    "En orden ascendente:    $num1   $num2    $num3"

elif   test    $num3    -ge    $num1    -a    $num1    -gt    $num2
        then
        tput    cup   15    5;   echo    "El mayor es:   $num3"
        tput    cup   17    5;   echo    "En orden ascendente:    $num2   $num1    $num3"
fi

2) Leer 3 números imprimir cual es mayor, medio y menor

clear
echo "digite primer numero:\c"
read num1
echo "digite segundo numero:\c"
read num2
echo "digite tercer numero:\c"
read num3
if test $num1 -gt $num2
   then
   if test $num1 -gt $num3
      then
      may=$num1
      if test $num2 -gt $num3
         then
         med=$num2
         men=$num3
        else
         med=$num3
         men=$num2
       fi
else     
            may=$num3
            med=$num1
            men=$num2
    fi
     
 else
        if test $num2 -gt $num3
           then   
            may=$num2
                 if test $num1 -gt $num3
                     then
                      med=$num1
                      men=$num3
                      else
                      med=$num3
                      men=$num1
                  fi
                 else
            may=$num3
            med=$num2
            men=$num1
fi
fi
clear
tput cup 2 21;echo "El mayor es $may"
tput cup 4 21;echo "El mediano es $med"
tput cup 6 21;echo "El menor es $men"

3) Código para hallar números pares:

clear
tput   cup   3   20;echo     " NUMEROS PARES E IMPARES "
tput   cup   5   22;echo     -n   "DIGITE UN NUMERO: "
read num
myo=`expr    $num    %     2`
if   test    $myo    =    0
    then
    tput   cup   6   22;   echo    "$num ES NUMERO PAR"
     else
      tput   cup   7   22; echo     "$num ES NUMERO IMPAR"
fi


4)

clear
tput cup 1 10;tput smso;echo "Q U I N C E N A   D E   T R A B A J A D O R E S";
tput rmso
tput cup 3 1;echo "codigo empleado [          ]  apellido [              ]"
tput cup 3 18;tput smso;read cod ;tput rmso
tput cup 3 41;tput smso;read ape ;tput rmso
tput cup 5 1;echo "nombre empleado [                       ]"
tput cup 5 18;tput smso;read nom;tput rmso
tput cup 7 1;echo "basico [$            ] dias trabajados [  ]"
tput cup 7 10;tput smso;read bas;tput rmso
tput cup 7 41;tput smso;read "dias";tput rmso

if test $dias -le 30
   then
quin1=`expr $bas / 30`
quin2=`expr $quin1 \* $dias`
ret=0
if test $bas -le 900000
   then
    sub=`expr 30000 / 30`
    sub1=`expr $sub \* $dias`
     else
     sub1=0
fi
if test $bas -ge 900000 -a $bas -le 1199999
   then
    ret=12000
    elif test $bas -ge 1200000 -a $bas -le 1499999
         then
         ret=18000
    elif test $bas -ge 1500000 -a $bas -le 1799999
         then
         ret=24000
      elif test $bas -gt 1800000
         then
          ret=36000
    fi
    
      devengado=`expr $quin2 + $sub1`
     neto=`expr $devengado - $ret`
     tput cup 9 1;tput smso;echo "basico: $bas";tput rmso
     tput cup 11 1;tput smso;echo "quincena: $quin2";tput rmso
     tput cup 13 1;tput smso;echo "subsidio de trans: $sub1";tput rmso
     tput cup 15 1;tput smso;echo "retefuente: $ret";tput rmso
     tput cup 17 1;tput smso;echo "neto: $neto";tput rmso
else
if test $dias -ge 31
   then
   tput cup 19 4;echo "NO SE LE PUEDE PAGAR MAS DE 31 DIAS TRABAJADOS"
   sleep 2
   sh quin
fi
fi

Ejemplo de menu

clear
tput   cup   2   19;  echo   "MENU PRINCIPAL"
tput   cup   4   19;  echo   "1.  OPERACIONES"
tput   cup   5   19;  echo   "2.  MAYORES O MENORES 150"
tput   cup   6   19;  echo   "3.  TRES NUMEROS"
tput   cup   7   19;  echo   "4.  PARES O IMPARES"
tput   cup   8   19;  echo   "9.  SALIR"
tput   cup   9   19;  echo   "DIGITE OPCIÓN:[    ]  "
tput   cup   9   34;  read   op
if   test   $op   -eq   1
  then
   clear
   sh   operaciones
   sleep 5
fi
if   test   $op   -eq   2
   then
    clear
    sh   mayores
    sleep 5
fi
if   test   $op  -eq   3
  then
  clear
  sh   3num
  sleep 5
fi
if   test   $op   -eq   4
  then
  clear
  sh   pares
  sleep 5
fi
if   test   $op   -eq   5
  then
  clear
  exit
fi



EJEMPLO DE CICLO WHILE

clear
tput cup 4 5;echo "CODIGO"
tput cup 4 15;echo "NOMBRE"
tput cup 4 25;echo "ASIGNATURA"
tput cup 4 39;echo "NOTA1"
tput cup 4 48;echo "NOTA2"
tput cup 4 57;echo "NOTA3"
tput cup 13 39;echo "PROMEDIO:"
tput cup 7 5;read cod
tput cup 7 15;read nom
tput cup 7 25;read asi
tput cup 7 39;read not1
while test $not1 -gt 5 -o $not1 -lt 0
   do
   tput cup 16 5;echo "El valor de la nota debe ser de 0 a 5"
   tput cup 7 39;echo "   "
   tput cup 7 39;read not1
    if test $not1 -le 5 -o $not1=""
       then
       tput cup 16 5;echo "                                      "  
   fi  
  done
  tput cup 7 48;read not2
   while test $not2 -gt 5 -o $not2 -lt 0
       do
   tput cup 16 5;echo "El valor de la nota debe ser de 0 a 5"
   tput cup 7 48;echo "   "   
   tput cup 7 48;read not2 
   if test $not2 -le 5  
      then  
      tput cup 16 5;echo "                                       " 
    fi  
   done
   tput cup 7 57;read not3
     while test $not3 -gt 5 -o $not3 -lt 0  
           do   
           tput cup 16 5;echo "El valor de la nota debe ser de 0 a 5"  
           tput cup 7 57;echo "  "      
           tput cup 7 57;read not3 
           if test $not3 -le 5  
              then  
              tput cup 16 5;echo "                                       " 
           fi  
            done
           suma=`expr $not1 + $not2 + $not3`
           prome=`expr $suma / 3`
           tput cup 13 50;echo "$prome"
           if test $prome -ge 0 -a $prome -lt 3  
              then  
              echo "DEFICIENTE"
           fi
           tput cup 21 0;echo ""



EJEMPLO MENU CASE ARCHIVOS Y DIRECTORIOS

clear
tput cup 2 19;echo "ARCHIVOS Y DIRECTORIOS"
tput cup 3 19;echo "ENTRE UN NOMBRE:"
tput cup 3 35;read a
  if test -d $a
     then
     clear
     l -d $a
     tput cup 5 20;echo "DIRECTORIO EXISTENTE"
      sleep 4
exit
fi
    if test  -r $a
       then
     cat $a
     tput cup 19 19;echo "ARCHIVO EXISTENTE"
     sleep 6
exit
     else
       clear
      tput cup 3 20;echo "$a NO ES ARCHIVO NI DIRECTORIO"
      sleep 3
fi

clear
tput cup 5 19;echo "QUE DESEA CREAR?"
tput cup 7 19;echo "1. ====>>  ARCHIVOS"
tput cup 8 19;echo "2. ====>>  DIRECTORIOS"
tput cup 9 19;echo "OPCION DESEADA:"
tput cup 9 34;read op
case $op in

1)
  clear
  tput cup 4 20;echo "DESEA CREARLO SI O NO:"
  tput cup 4 42;read b
  if test $b = "s" -o $b = "S"
     then
     tput cup 4 20;echo "PARA GUARDAR, PRESIONAR LAS TECLAS <CTRL> + <D>"
     cat > $a
     l $a
      else
     tput cup 5 20;echo "NO FUE CREADO"
     sleep 3
fi
  sleep 2 ;;
2)
  clear
  tput cup 4 20;echo "DESEA CREARLO SI O NO:"
  tput cup 4 42;read b
  if test $b = "s" -o $b = "S"
     then
     mkdir $a
     l -d $a
      else
     tput cup 5 20;echo "NO FUE CREADO"
     sleep 3
fi
  sleep 2 ;;
esac

EJEMPLO SUBSTR Y LONGITUD

clear
cv=0
cn=0
c=1
l=0
echo   -n  "digite texto:  "
read    k
l=`expr    length    $k`
while     test   $c   -le    $l
      do
      t=`expr   substr   $k   $c   1`
     if   test  $t  =   "a"  -o  $t  =  "e"  -o  $t  =  "i" -o $t = "o" -o $t = "u"
        then
        cv=`expr   $cv   +    1`
         else
                 cn=`expr   $cn   +   1`
         fi
c=`expr   $c   +   1`
done
echo   "$k   tiene   $l   vocales   y   consonantes"
echo   "las  vocales son $cv"
echo   "las consonantes son $cn"

EDITOR VI

EL EDITOR VI

VI es un programa pequeño y simple de utilizar que resulta de gran utilidad, especialmente para los administradores de sistemas; vi quiere decir “visual”.

Primeros pasos de VI:

Para comenzar a utilizar vi inicie una sesión y teclee.

$ vi programa (Donde programa es el nombre del archivo de texto que quiere editar)

El editor VI tiene dos modos de funcionamiento, el modo orden y el modo entrada:

En el primero VI interpreta la entrada desde el teclado como una orden y la ejecuta. Mediante este modo se puede acceder a las ordenes para guardar archivos, salir de vi o desplazar el cursor.

Por otro lado, el modo entrada permite introducir textos en la posición donde se encuentra el cursor, pudiendo especificar si el texto se añadirá delante del cursor, detrás de éste o bien al principio de la línea.

Órdenes básicas de vi para insertar y borrar texto en la posición del cursor:

Nota: Para poder trabajar en modo de entrada hay que presionar la tecla <ESC> o <ESCAPE> y seguido de la tecla de orden. De manera que pueda el usuario trabajar en el editor.

Orden............. Descripción

a...................... Insertar texto a la izquierda del cursor
A...................... Insertar texto al final de la línea actual
i....................... Insertar texto a la derecha del cursor
I....................... Insertar texto al principio de la línea actual
o...................... Introduce una línea por debajo de la línea actual.
O..................... Introduce una línea por encima de la línea actual.
x...................... Borra el carácter sobre el que se encuentra el cursor.

Ordenes para salir de VI:

Orden............. Descripción

:q..................... Sale si no se ha realizado ninguna modificación al archivo.
:q!.................... Sale descartando los cambios realizados al texto.
:wq.................. Sale grabando en disco los cambios realizados.
:x..................... Lo mismo que lo anterior.
ZZ.................... Lo mismo que lo anterior.

Órdenes para mover el cursor:

Orden............. Descripción

h...................... Mueve el cursor a la izquierda.
j....................... Mueve el cursor abajo.
k...................... Mueve el cursor arriba.
l....................... Mueve el cursor a la derecha.
0...................... Mueve el cursor al principio de la línea
$...................... Mueve el cursor al final de la línea
w...................... Avanza una palabra.
e...................... Mueve el cursor al final de la palabra actual.

<CTRL> <F>... Avanza una pantalla.
<CTRL> <B>... Retrocede una pantalla.

Ordenes para el manejo de bloques de texto

Orden............. Descripción
y$.................... Copia en el portapapeles el texto comprendido entre el cursor y el final de la línea.
yy.................... Copia la línea actual en el portapapeles.
dw................... Corta la palabra delante del cursor.
d$.................... Corta desde la posición actual hasta el final de la línea.
dd.................... Corta la línea actual.
P...................... Pega el contenido del portapapeles       a la derecha del cursor.
p...................... Pega el contenido del portapapeles a la izquierda del cursor.
Compartir English Portuguese Spain