viernes, 26 de junio de 2015

Como montar un cdrom en una maquina virtual linux redhat

Para montar un cdrom en una maquina virtual linux redhat debemos identificar el dispositivo que lo controla y entonces montar el dispositivo en una ruta o directivo previamente creado:


Listamos el dispositivo del cdrom:

[root@lnxsgcpdev shm]# more /proc/sys/dev/cdrom/info
CD-ROM information, Id: cdrom.c 3.20 2003/12/17

drive name:             sr1     sr0
drive speed:            32      32
drive # of slots:       1       1
Can close tray:         1       1
Can open tray:          1       1
Can lock tray:          1       1
Can change speed:       1       1
Can select disk:        0       0
Can read multisession:  1       1
Can read MCN:           1       1
Reports media changed:  1       1
Can play audio:         1       1
Can write CD-R:         0       0
Can write CD-RW:        0       0
Can read DVD:           1       1
Can write DVD-R:        0       0
Can write DVD-RAM:      0       0
Can read MRW:           1       1
Can write MRW:          1       1
Can write RAM:          1       1

Montamos el dispositivo sr1 en /mnt/cdrom

[root@lnxsgcpdev shm]# mount /dev/sr1 /mnt/cdrom
mount: block device /dev/sr1 is write-protected, mounting read-only

Ahora el dispositivo se encuentra listo para ser utilizado.

jueves, 11 de junio de 2015

dbando agregar y formatear un disco Solaris en VirtualBox

En un ambiente linux es facil y mas entendible agregar discos, particionarlos y montarlos. En un ambiente Solaris es muy diferente por lo cual hago este post, la metodologia es la siguiente:



Agregar un nuevo disco a VirtualBox Solaris

-->Apagar la maquina virtual

-->Ir al administrador de maquinas virtuales (VirtualBox)

-->Click derecho Configurar (a la maquina virtual que deseamos a gregar un disco)

-->Almacenamiento

-->Controlador SATA

-->Agregar un disco duro

-->Crear nuevo disco

-->seleccionar el tipo de disco (en este caso VMDK )

-->seleccionar el tipo de almacenamiento (en este caso Tamaño fijo)

-->Escribir el nombre del disco

-->Elegir el tamaño del disco

-->Crear

-->Iniciar la maquina virtual

-->Loguearse como root (super usuario)

-->Ingresar los siguientes comandos

devfsadm -->Nos permitira reescanear los dispositivos disponibles
format -->Nos mostrara los discos disponibles 

AVAILABLE DISK SELECTIONS:
       0. c0d0 <Úxäþ¢ÿþ©ÿþ¬@©üþ cyl 2085 alt 2 hd 255 sec 63>
          /pci@0,0/pci-ide@1,1/ide@0/cmdk@0,0
       1. c2t0d0 <ATA    -VBOX HARDDISK  -1.0  cyl 3341 alt 2 hd 224 sec 56>
          /pci@0,0/pci8086,2829@d/disk@0,0
Specify disk (enter its number):

-->Seleccionar el disco que acabamos de anexar, para estar seguros de cual es.
-->seleccionamos un numero (0 o 1 en este caso), he seleccionado el 0 para probar lo siguiente:

##En caso de que el disco ya este ocupado aparecera algo similar a esto:
 
 Specify disk (enter its number): 0
selecting c0d0
Controller working list found
[disk formatted, defect list found]
Warning: Current Disk has mounted partitions.
/dev/dsk/c0d0s0 is currently mounted on /. Please see umount(1M).
/dev/dsk/c0d0s1 is currently used by swap. Please see swap(1M).
/dev/dsk/c0d0s7 is currently mounted on /export/home. Please see umount(1M).


-->Ahora verificamos la opcion 1:

format

Searching for disks...
Inquiry failed for this logical diskdone


AVAILABLE DISK SELECTIONS:
       0. c0d0 <Úxäþ¢ÿþ©ÿþ¬@©üþ cyl 2085 alt 2 hd 255 sec 63>
          /pci@0,0/pci-ide@1,1/ide@0/cmdk@0,0
       1. c2t0d0 <ATA    -VBOX HARDDISK  -1.0 cyl 3340 alt 2 hd 224 sec 56>
          /pci@0,0/pci8086,2829@d/disk@0,0
-->Selccionamos 1
Specify disk (enter its number): 1
selecting c2t0d0
[disk formatted]


FORMAT MENU:
        disk       - select a disk
        type       - select (define) a disk type
        partition  - select (define) a partition table
        current    - describe the current disk
        format     - format and analyze the disk
        fdisk      - run the fdisk program
        repair     - repair a defective sector
        label      - write label to the disk
        analyze    - surface analysis
        defect     - defect list management
        backup     - search for backup labels
        verify     - read and display labels
        save       - save new disk/partition definitions
        inquiry    - show vendor, product and revision
        volname    - set 8-character volume name
        !<cmd>     - execute <cmd>, then return
        quit
-->Generamos la particion con el comando partition

format> partition


PARTITION MENU:
        0      - change `0' partition
        1      - change `1' partition
        2      - change `2' partition
        3      - change `3' partition
        4      - change `4' partition
        5      - change `5' partition
        6      - change `6' partition
        7      - change `7' partition
        select - select a predefined table
        modify - modify a predefined partition table
        name   - name the current table
        print  - display the current table
        label  - write partition map and label to the disk
        !<cmd> - execute <cmd>, then return
        quit

##Para simplificar, vamos a hacer el segmento 0 del tamaño de la unidad completa con la opcion modify.
##Seleccionaos la opción de "All Free Hog", que debería ser la opción 1, y pulse ENTER.


partition> modify
Select partitioning base:
        0. Current partition table (original)
        1. All Free Hog
-->Seleccionamos la opcion 1
Choose base (enter number) [0]? 1

Part      Tag    Flag     Cylinders        Size            Blocks
  0       root    wm       0               0         (0/0/0)           0
  1       swap    wu       0               0         (0/0/0)           0
  2     backup    wu       0 - 3339       19.98GB    (3340/0/0) 41896960
  3 unassigned    wm       0               0         (0/0/0)           0
  4 unassigned    wm       0               0         (0/0/0)           0
  5 unassigned    wm       0               0         (0/0/0)           0
  6        usr    wm       0               0         (0/0/0)           0
  7 unassigned    wm       0               0         (0/0/0)           0
  8       boot    wu       0 -    0        6.12MB    (1/0/0)       12544
  9 alternates    wm       0               0         (0/0/0)           0
Do you wish to continue creating a new partition

-->Seleccionamos yes
table based on above table[yes]? yes
Free Hog partition[6]? 0
Enter size of partition '1' [0b, 0c, 0.00mb, 0.00gb]:
Enter size of partition '3' [0b, 0c, 0.00mb, 0.00gb]:
Enter size of partition '4' [0b, 0c, 0.00mb, 0.00gb]:
Enter size of partition '5' [0b, 0c, 0.00mb, 0.00gb]:
Enter size of partition '6' [0b, 0c, 0.00mb, 0.00gb]:
Enter size of partition '7' [0b, 0c, 0.00mb, 0.00gb]:

Part      Tag    Flag     Cylinders        Size            Blocks
  0       root    wm       1 - 3339       19.97GB    (3339/0/0) 41884416
  1       swap    wu       0               0         (0/0/0)           0
  2     backup    wu       0 - 3339       19.98GB    (3340/0/0) 41896960
  3 unassigned    wm       0               0         (0/0/0)           0
  4 unassigned    wm       0               0         (0/0/0)           0
  5 unassigned    wm       0               0         (0/0/0)           0
  6        usr    wm       0               0         (0/0/0)           0
  7 unassigned    wm       0               0         (0/0/0)           0
  8       boot    wu       0 -    0        6.12MB    (1/0/0)       12544
  9 alternates    wm       0               0         (0/0/0)           0

-->Seleccionamos yes
Okay to make this the current partition table[yes]? yes
Enter table name (remember quotes): disk_prueba1

--Seleccionamos yes
Ready to label disk, continue? yes

-->Salimos de partition con quit
partition> quit


FORMAT MENU:
        disk       - select a disk
        type       - select (define) a disk type
        partition  - select (define) a partition table
        current    - describe the current disk
        format     - format and analyze the disk
        fdisk      - run the fdisk program
        repair     - repair a defective sector
        label      - write label to the disk
        analyze    - surface analysis
        defect     - defect list management
        backup     - search for backup labels
        verify     - read and display labels
        save       - save new disk/partition definitions
        inquiry    - show vendor, product and revision
        volname    - set 8-character volume name
        !<cmd>     - execute <cmd>, then return
        quit
-->Guardamos los cambios en format con save

format> save
Saving new disk and partition definitions
Enter file name["./format.dat"]: /etc/format.dat

-->Salimos del format
format> quit

-->Creamos el nuevo filesystem
# newfs /dev/rdsk/c2t0d0s0

-->Selccionamos yes
newfs: construct a new file system /dev/rdsk/c2t0d0s0: (y/n)? yes
Warning: 5376 sector(s) in last cylinder unallocated
/dev/rdsk/c2t0d0s0:     41884416 sectors in 6818 cylinders of 48 tracks, 128 sectors
        20451.4MB in 427 cyl groups (16 c/g, 48.00MB/g, 5824 i/g)
super-block backups (for fsck -F ufs -o b=#) at:
 32, 98464, 196896, 295328, 393760, 492192, 590624, 689056, 787488, 885920,
Initializing cylinder groups:
........
super-block backups for last 10 cylinder groups at:
 40997024, 41095456, 41193888, 41292320, 41390752, 41489184, 41587616,
 41686048, 41784480, 41882912
 
-->Montamos el disco en una ruta previamente creada (mkdir /opt/oracle)
# mount /dev/rdsk/c2t0d0s0 /opt/oracle
mount: /dev/rdsk/c2t0d0s0 not a block device ---Es necesario montar desde /dev/dsk

-->Ejecutamos la sentencia correcta
# mount /dev/dsk/c2t0d0s0 /opt/oracle

-->Revisamos que el filesystem este creado
# df -h .
Filesystem   

/dev/dsk/c2t0d0s0       20G    20M    19G     1%    /opt/oracle



  
 Saludos!












lunes, 8 de junio de 2015

dbando Trigger que mata sesiones atrapadas

Buen dia,


El siguiente Trigger mata sesiones de usuarios atrapadas, lo hace de manera automatica, esto en caso de que nuestra solucion al perder conexion por lluvia, apagones, etc no pueda matar las sesiones en automatico, y si tenemos reestriccion en el numero de sesiones por usuario, este Trigger nos ayudara mucho.

El codigo es el siguiente:


CREATE OR REPLACE TRIGGER KILL_SESSIONS_LETG
AFTER LOGON ON DATABASE
DECLARE

--Declaracion de variables

  t_prog sys.v_$session.program%TYPE;
  v_numsid integer;
  v_sid sys.v_$session.sid%TYPE;
  v_serial sys.v_$session.serial#%TYPE;
  sidd integer;
  seriall integer;
  sid2 integer;
  serial2 integer;
  v_user varchar2(20);
    
BEGIN

--Se evita el error comun de procesos background de oracle

  SELECT count(PROGRAM)
  into t_prog
  from sys.v_$session
  where program like 'oracle@osgc-oracle (J00%)'
  AND audsid = USERENV('SESSIONID')
  AND  ROWNUM = 1;
  
  IF t_prog >0
  
  THEN
  
  NULL;
    
  ELSE
  
  --Se obtiene el usuario del sesion actual
  
  SELECT username,sid,serial#
  INTO v_user,v_sid,v_serial
  FROM sys.v_$session
  WHERE  audsid = USERENV('SESSIONID')
  AND  audsid != 0 
  AND  ROWNUM = 1;  
  
 --Se generan los usuarios que no se veran afectados por el trigger

     IF UPPER(v_user)='ADMON' OR
     UPPER(v_user)='BATCH' OR
     UPPER(v_user)='CESFI2014' OR
     UPPER(v_user)='PERRITO'
  
  THEN
NULL;

ELSE

--Se estima el valor maximo de conexiones a la base de datos
--en general este trigger es para soluciones donde las sesiones 
--quedan atrapadas y es necesario desconectar usuarios

 select count(sid)
 into v_numsid
 from v$session
 where username=v_user
 and program like 'opensgc%';

 IF v_numsid >2
  
 THEN

 --Hacemos la comparacion para no matar nuestra sesion actual
  select sid,serial#
  into sidd,seriall
  from v$session
  where username=v_user 
  and sid != v_sid
  AND serial# != v_serial
  and program like 'programa_con_el_que_nos_conectamos%'
  and rownum=1;
  
  --EXECUTE IMMEDIATE 'alter system kill session ''' || sidd || ',' || seriall || '''';
  EXECUTE IMMEDIATE 'alter system disconnect session ''' || sidd || ',' || seriall || '''immediate';
  
  
  --Hacemos la comparacion para no matar nuestra sesion actual
  select sid,serial#
  into sid2,serial2
  from v$session
  where username=v_user 
  and sid != v_sid
  AND serial# != v_serial
  and program like 'programa_con_el_que_nos_conectamos2%'
  and rownum=1;
  
  --EXECUTE IMMEDIATE 'alter system kill session ''' || sidd || ',' || seriall || '''';
  EXECUTE IMMEDIATE 'alter system disconnect session ''' || sidd || ',' || seriall || '''immediate';
  
  ELSE

 NULL;

END IF;
 END IF;
  END IF;
END;
/



Saludos!!

viernes, 5 de junio de 2015

dbando script para monitorear cambios realizados a datos sensibles

Buen dia,


El siguiente script en shell fue un requerimiento para tener un monitoreo de los usuarios que realizan cambios a datos sensibles en una tabla critica y enviar correo al momento para tomar acciones en caso de cualquier aclaracion, para esto existe un Trigger que inserta los datos modificados en una tabla de logs de donde se obtienen los datos de los usuarios que han cambiado dicho valor, tambien se utiliza la tabla donde se realizan los cambios y ademas se utiliza una tabla donde se tienen registrados los nombres completos de los usuarios y su nombre de "usuario", por ejemplo el mio seria LTORRES y mi nombre completo Luis Torres.


El script es el siguiente:

#!/bin/ksh

# |----------------------------------------------------------|
# |--  Script que monitorea cambios de CUALQUIERCOSA     --|
# |----------------------------------------------------------|

#LETG 14 de Mayo del 2015#

# |-------------------------------|
# |--  Declaracion de variables --|
# |-------------------------------|

#En /opt/oracle/scripts/variable10g.scipts se encuentran las variables de ambiente

while read VARIABLE
do
export $VARIABLE
done < /opt/oracle/scripts/variable10g.scipts
export PATH=$PATH:$ORACLE_HOME/bin:.

#Se genero con anterioridad el password encryptado con OPENSSL

PASS_ENTRADA=$(${OPENSSL} enc ${OPENSSL_ENCRIPTION} -d -in ${DIRECCION_ACTUAL}/.passdecrypt -pass pass:$((cat ${MASTER_PASS})|awk -F":" '{print $2}'))
USER_PASS=$(${OPENSSL} enc ${OPENSSL_ENCRIPTION} -d -in ${DIRECCION_ACTUAL}/.pwd${USUARIO_ORACLE} -pass pass:${PASS_ENTRADA})

# |--- ------------------------------------------------|
# |-- Rutas constantes para desposito de informacion --|
# |----------------------------------------------------|

USR_INFO=/opt/oracle/scripts/allinf.csv
MAIL_INFO=/opt/oracle/scripts/allinf2.csv
TABLE_INFO=/opt/oracle/scripts/allinf3.csv
NOMBRE_USR=/opt/oracle/scripts/allinf6.csv
DATE_INFO=/opt/oracle/scripts/allinf4.out
DATE_INFO2=/opt/oracle/scripts/allinf7.out
DATE_COUNT=/opt/oracle/scripts/allinf5.out
GOLD_LIST='juancho_casitas_@algo.mx'
today_date=$(date +"%d_%m_%Y_%H_%M_%S")
SENDER='Security_Manager@algo.mx'
TMP_MAIL_FILE=/tmp/salida_cambio.out


# |----------------------------------------------------|
# |--  Obtencion de fecha de logueo para comparacion --|
# |----------------------------------------------------|

#El script corre cada 5 minutos por lo cual se obtiene la fecha de cambio del registro
#entre los ultimos cinco minutos y la fecha actual, para evitar que se siga enviando
#el correo cada que corra el cron

sqlplus -s ${USUARIO_ORACLE}/${USER_PASS}@$ORACLE_SID<<EOF
set feed off;
set pagesize 0;
column machine format a17;
column sid format 999;
ALTER SESSION SET NLS_DATE_FORMAT='dd-mm-yyyy hh24:mi:ss';
spool $DATE_COUNT
SELECT COUNT(FECHA_CAMBIO) FROM DUEÑO.TABLA where FECHA_CAMBIO BETWEEN SYSDATE-.084/24 AND SYSDATE
and rownum=1;

spool off;
EOF

compare=$(cat $DATE_COUNT)

if [  $compare -gt 0 ]

then

sqlplus -s ${USUARIO_ORACLE}/${USER_PASS}@$ORACLE_SID<<EOF
ALTER SESSION SET NLS_DATE_FORMAT="MM/DD/YYYY";
set feed off;
set pagesize 0;
spool $DATE_INFO
SELECT FECHA_CAMBIO FROM DUEÑO.TABLA where TRUNC (FECHA_CAMBIO) = TRUNC (SYSDATE)
and rownum=1;
spool off;
EOF

sqlplus -s ${USUARIO_ORACLE}/${USER_PASS}@$ORACLE_SID<<EOF
ALTER SESSION SET NLS_DATE_FORMAT='dd-mm-yyyy hh24:mi:ss';
set feed off;
set pagesize 0;
spool $DATE_INFO2
SELECT FECHA_CAMBIO FROM DUEÑO.TABLA where FECHA_CAMBIO BETWEEN SYSDATE-.084/24 AND SYSDATE;
spool off;
EOF

# |-----------------------------------------------------|
# |--  Generacion de archivo maestro de comparacion   --|
# |-----------------------------------------------------|

sqlplus -s ${USUARIO_ORACLE}/${USER_PASS}@$ORACLE_SID<<EOF
ALTER SESSION SET NLS_DATE_FORMAT='dd-mm-yyyy hh24:mi:ss';
set feed off;
set pagesize 0;
set lines 300;
spool $USR_INFO
SELECT DISTINCT USUARIO ||','||F_ACTUAL||','||PROGRAMA||','||FECHA_CAMBIO||','||USU_MODIF||','||COD_PROV||','||COD_DEPTO||','||
COD_MUNIC||','||COD_LOCAL||','||NOM_LOCAL||','||AREA_EJEC||','||USR_NUMBER1||','||USR_NUMBER2||','||
USR_NUMBER3||','||USR_VARCHAR1||','||USR_VARCHAR2||','||USR_VARCHAR3||','||USR_DATETIME1||','||USR_DATETIME2
FROM (
SELECT DISTINCT USUARIO, F_ACTUAL, PROGRAMA, FECHA_CAMBIO, USU_MODIF, COD_PROV, COD_DEPTO, COD_MUNIC, COD_LOCAL,
 NOM_LOCAL, AREA_EJEC, USR_NUMBER1,USR_NUMBER2, USR_NUMBER3, USR_VARCHAR1, USR_VARCHAR2,
 USR_VARCHAR3, USR_DATETIME1, USR_DATETIME2 FROM DUEÑO.TABLA where FECHA_CAMBIO BETWEEN SYSDATE-.084/24 AND SYSDATE and rownum=1);
spool off;
EOF

CODIGO=$(cat ${USR_INFO}|awk -F"," '{printf "%s\n", $9}')
USUARIO_MAIL=$(cat ${USR_INFO}|awk -F"," '{printf "%s\n", $5}')


# |-----------------------------------------------------|
# |--  Obtencion de datos de usuario para denunciarlo --|
# |-----------------------------------------------------|

sqlplus -s ${USUARIO_ORACLE}/${USER_PASS}@$ORACLE_SID<<EOF
ALTER SESSION SET NLS_DATE_FORMAT='dd-mm-yyyy hh24:mi:ss';
set pagesize 0;
set lines 300;
spool $MAIL_INFO
SELECT DISTINCT USUARIO ||','||F_ACTUAL||','||PROGRAMA||','||FECHA_CAMBIO||','||USU_MODIF||','||COD_PROV||','||COD_DEPTO||','||COD_MUNIC||','||COD_LOCAL||','||NOM_LOCAL||
','||AREA_EJEC||','||USR_NUMBER1||','||USR_NUMBER2||','||USR_NUMBER3||','||USR_VARCHAR1||','||USR_VARCHAR2||','||USR_VARCHAR3||','||USR_DATETIME1||','||USR_DATETIME2
 FROM (
SELECT DISTINCT USUARIO, F_ACTUAL, PROGRAMA, FECHA_CAMBIO, USU_MODIF, COD_PROV, COD_DEPTO, COD_MUNIC, COD_LOCAL, NOM_LOCAL, AREA_EJEC, USR_NUMBER1, USR_NUMBER2, USR_NUMBE
R3, USR_VARCHAR1, USR_VARCHAR2, USR_VARCHAR3, USR_DATETIME1, USR_DATETIME2 FROM DUEÑO.TABLA where FECHA_CAMBIO BETWEEN SYSDATE-.084/24 AND SYSDATE and row
num=1 order by 4 desc);
spool off;
EOF

USUARIO=$(cat ${MAIL_INFO}|awk -F"," '{printf "%s\n", $1}')
F_ACTUAL=$(cat ${MAIL_INFO}|awk -F"," '{printf "%s\n", $2}')
#PROGRAMA=$(cat ${MAIL_INFO}|awk -F"," '{printf "%s\n", $3}')
FECHA_CAMBIO=$(cat ${MAIL_INFO}|awk -F"," '{printf "%s\n", $4}')
USU_MODIF=$(cat ${MAIL_INFO}|awk -F"," '{printf "%s\n", $5}')
COD_PROV=$(cat ${MAIL_INFO}|awk -F"," '{printf "%s\n", $6}')
COD_DEPTO=$(cat ${MAIL_INFO}|awk -F"," '{printf "%s\n", $7}')
COD_MUNIC=$(cat ${MAIL_INFO}|awk -F"," '{printf "%s\n", $8}')
COD_LOCAL=$(cat ${MAIL_INFO}|awk -F"," '{printf "%s\n", $9}')
NOM_LOCAL=$(cat ${MAIL_INFO}|awk -F"," '{printf "%s\n", $10}')
AREA_EJEC=$(cat ${MAIL_INFO}|awk -F"," '{printf "%s\n", $11}')
USR_NUMBER1=$(cat ${MAIL_INFO}|awk -F"," '{printf "%s\n", $12}')
USR_NUMBER2=$(cat ${MAIL_INFO}|awk -F"," '{printf "%s\n", $13}')



# |-----------------------------------------------------|
# |--  Obtencion de datos de tabla para comparacion   --|
# |-----------------------------------------------------|

sqlplus -s ${USUARIO_ORACLE}/${USER_PASS}@$ORACLE_SID<<EOF
ALTER SESSION SET NLS_DATE_FORMAT='dd-mm-yyyy hh24:mi:ss';
set feed off;
set pagesize 0;
set lines 300;
spool $TABLE_INFO
SELECT DISTINCT USUARIO ||','||F_ACTUAL||','||PROGRAMA||','||COD_PROV||','||COD_DEPTO||','||COD_MUNIC||','||COD_LOCAL||','||NOM_LOCAL||','||AREA_EJEC||','||USR_NUMBE
R1||','||USR_NUMBER2||','||USR_NUMBER3||','||USR_VARCHAR1||','||USR_VARCHAR2||','||USR_VARCHAR3||','||USR_DATETIME1||','||USR_DATETIME2 FROM (
SELECT USUARIO, F_ACTUAL, PROGRAMA, COD_PROV, COD_DEPTO, COD_MUNIC, COD_LOCAL, NOM_LOCAL, AREA_EJEC,USR_NUMBER1, USR_NUMBER2, USR_NUMBER3, USR_VARCHAR1, USR_VARCHAR2
, USR_VARCHAR3,USR_DATETIME1, USR_DATETIME2 FROM DUEÑO.TABLA2 where COD_LOCAL=$CODIGO);
spool off;
EOF


# |-----------------------------------------------------|
# |--  Obtencion de datos de usuario para cotejar     --|
# |-----------------------------------------------------|

sqlplus -s ${USUARIO_ORACLE}/${USER_PASS}@$ORACLE_SID<<EOF
set feed off;
set pagesize 0;
set lines 300;
spool $NOMBRE_USR
SELECT USUARIO ||','||F_ACTUAL||','||PROGRAMA||','||NOM_USR||','||DESC_USR||','||COD_UNICOM||','||COD_CENTEC||','||MAX_NUM_SESSIONES||','||PAN_COD_ALMACE
FROM (
SELECT USUARIO,F_ACTUAL,PROGRAMA,NOM_USR,DESC_USR,COD_UNICOM,COD_CENTEC,MAX_NUM_SESSIONES,PAN_COD_ALMACE
FROM OPENS.USUARIOS
WHERE NOM_USR='$USUARIO_MAIL');
spool off;
EOF


NOM_USR=$(cat ${NOMBRE_USR}|awk -F"," '{printf "%s\n", $5}')
USUARIO_TABLE=$(cat ${TABLE_INFO}|awk -F"," '{printf "%s\n", $1}')
FECHA_ACTUAL=$(cat ${TABLE_INFO}|awk -F"," '{printf "%s\n", $2}')
#PROGRAMA_TABLE=$(cat ${TABLE_INFO}|awk -F"," '{printf "%s\n", $3}')
CODIGO_PROVINCIA=$(cat ${TABLE_INFO}|awk -F"," '{printf "%s\n", $4}')
CODIGO_DEPARTAMENTO=$(cat ${TABLE_INFO}|awk -F"," '{printf "%s\n", $5}')
CODIGO_MUNICIPIO=$(cat ${TABLE_INFO}|awk -F"," '{printf "%s\n", $6}')
CODIGO_SENSIBLE=$(cat ${TABLE_INFO}|awk -F"," '{printf "%s\n", $7}')
DATO_SENSIBLE=$(cat ${TABLE_INFO}|awk -F"," '{printf "%s\n", $8}')
AREA_EJECUCION=$(cat ${TABLE_INFO}|awk -F"," '{printf "%s\n", $9}')
CODIGO_POSTAL=$(cat ${TABLE_INFO}|awk -F"," '{printf "%s\n", $10}')
ESTRATO=$(cat ${TABLE_INFO}|awk -F"," '{printf "%s\n", $11}')
USR_NUMBER3=$(cat ${TABLE_INFO}|awk -F"," '{printf "%s\n", $12}')
USR_VARCHAR1=$(cat ${TABLE_INFO}|awk -F"," '{printf "%s\n", $13}')
USR_VARCHAR2=$(cat ${TABLE_INFO}|awk -F"," '{printf "%s\n", $14}')
USR_VARCHAR3=$(cat ${TABLE_INFO}|awk -F"," '{printf "%s\n", $15}')
USR_DATETIME1=$(cat ${TABLE_INFO}|awk -F"," '{printf "%s\n", $16}')
USR_DATETIME2=$(cat ${TABLE_INFO}|awk -F"," '{printf "%s\n", $17}')

FECHA=$(cat ${DATE_INFO2})


if [  "$NOM_LOCAL" = "$DATO_SENSIBLE" ];

then

echo "Nada que hacer";

else

cat /dev/null>$TMP_MAIL_FILE

echo "MIME-Version: 1.0
From: $SENDER
To: $GOLD_LIST
Subject: Importante, un usuario ha cambiado el valor de un campo
Content-Type: text/html

<html>
<body>
<table>
  <tr>
     <td colspan=4><center><b>Reporte de cambios en datos sensibles</b></center></td></tr>
  </tr>
  <tr>
    <td>Campo modificado      </td>
    <td>NOMBRE_CAMPO      </td>
  </tr>
  <tr>
    <td>Usuario que realizo el cambio      </td>
    <td>$USUARIO_MAIL - $NOM_USR      </td>
  </tr>
  <tr>
    <td>Dato Anterior      </td>
    <td>$NOM_LOCAL      </td>
  </tr>
  <tr>
    <td>Dato Nuevo      </td>
    <td>$DATO_SENSIBLE      </td>
  </tr>
    <tr>
    <td>Codigo del dato sensible    </td>
    <td>$CODIGO_SENSIBLE      </td>
  </tr>
    <tr>
    <td>Fecha de modificacion    </td>
    <td>$FECHA      </td>
  </tr>


</table>
<br><br>

 Reporte de cambios realizados a datos sensibles, para notificar y tomar acciones en caso de ser requerida cualquier aclaracion. Equipo de seguridad NOMBRE_EMPRESA

Security_Manager@algo.com
<br>
<br>
<br>
<FONT FACE="arial" SIZE=1 COLOR=grey>
<i> * Este es un email auto generado. Favor de no responderlo. *</i>
<br>
<br>

<i>Este correo electronico es confidencial y/o puede contener informacion privilegiada.</i>
<i>Si usted no es su destinatario o no es alguna persona autorizada por este para recibir sus correos electronicos,</i>
<i>NO debera usted utilizar, copiar, revelar, o tomar ninguna accion basada en este correo electronico o cualquier otra informacion incluida en el, favor de borrar e
ste correo electronico totalmente y sus anexos.</i>

<i>Nota: Los acentos y caracteres especiales fueron omitidos para su correcta lectura en cualquier medio electronico.</i>

<i>This e-mail is confidential and/or may contain privileged information.</i>
<i>If you are not the addressee or authorized to receive this for the addressee, you must not use, copy, disclose, or take any action based on this message or any ot
her information herein, delete this e-mail and its attachments.</i>
</FONT>

<br>


</body>

</html>

" >> $TMP_MAIL_FILE


cat $TMP_MAIL_FILE| /usr/sbin/sendmail -t

fi

rm /tmp/salida_cambio.out
rm $USR_INFO
rm $DATE_INFO
rm $DATE_INFO2
rm $TABLE_INFO
rm $MAIL_INFO
rm $NOMBRE_USR
fi
rm $DATE_COUNT





Saludos!!

jueves, 4 de junio de 2015

dbando Trigger After Logon, denegando usuarios, Toad,cmd,putty

Buen dia,


El siguiente script deniega accesos no permitidos de usuarios que intentan ingresar a la base de datos mediante herramientas como lo son, putty, MobaXterm, cmd, Toad, PlsqlDeveloper, Excel, etc.



Esta solucion es mediante un trigger (disparador) que se activa al despues de loguearse, la solucion es perfecta para sistemas comerciales que funcionan mediante el cliente de Oracle instalado en sus maquinas, ya sean cajeros o atencion a clientes, con el fin de evitar filtracion de datos sensibles a usuarios con algo de experiencia en bases de datos.



El Trigger es el siguiente:


CREATE OR REPLACE TRIGGER SYSTEM.DENY_ACCESS_LETG
AFTER LOGON ON DATABASE
DECLARE

--Se declaran variables

  t_prog sys.v_$session.program%TYPE;
  v_prog sys.v_$session.program%TYPE;
  l_count integer;
  v_date sys.v_$session.logon_time%TYPE;
 
BEGIN

--El parametron de bd job_queue_processes seteado arriba de 0 genera errores en el alert
--Con la siguiente excepcion se evita el error (prueben el trigger sin la excepcion y monitoreen el alert)

  SELECT count(PROGRAM)
  into t_prog
  from sys.v_$session
  where program like 'oracle@osgc-oracle (J00%)'
  AND audsid = USERENV('SESSIONID')
  AND  ROWNUM = 1;

  IF t_prog >0

  THEN

  NULL;

  ELSE

  SELECT program INTO v_prog
  FROM sys.v_$session
  WHERE  audsid = USERENV('SESSIONID')
  AND  audsid != 0  -- No revisa conexiones de sys
  AND  ROWNUM = 1;

 SELECT LOGON_TIME INTO v_date
 FROM sys.v_$session
 WHERE audsid = USERENV('SESSIONID')
 AND  audsid != 0  -- No revisa conexiones de sys
 AND  ROWNUM = 1;

     IF UPPER(v_prog) LIKE '%TOAD%' OR UPPER(v_prog) LIKE '%T.O.A.D%' OR -- Toad
     UPPER(v_prog) LIKE '%SQLNAV%' OR     -- SQL Navigator
     UPPER(v_prog) LIKE '%PLSQLDEV%' OR -- PLSQL Developer
     UPPER(v_prog) LIKE '%SQL%' OR -- PLSQL Developer
     UPPER(v_prog) LIKE '%BUSOBJ%' OR   -- Business Objects
     UPPER(v_prog) LIKE '%EXCEL%'       -- MS-Excel plug-in
  THEN

--Seleccionar uno o mas roles para tomarlos como parametro de acceso
--Los usuario con el role elegido podran accesar sin problemas

  SELECT COUNT (*)
  INTO l_count
  FROM dba_role_privs
  WHERE     granted_role in ('NOMBRE_ROLE','NOMBRE_ROLE2')
  AND grantee = SYS_CONTEXT ('userenv', 'session_user');
  IF l_count=0 THEN

--Si el role del usuario no se encuentra dentro de los permitidos entonces insertamos sus datos en una tabal de log
--La tabla de log debe haberse creado con anteioridad

  EXECUTE IMMEDIATE ('ALTER SESSION SET NLS_DATE_FORMAT=''MM/DD/YY HH:MI:SSAM''');
insert into DUEÑO.TABLA_LOG VALUES(
USER,v_date,
sys_context('USERENV','SERVER_HOST'),
 sys_context('USERENV','SESSIONID'),
 sys_context('USERENV','HOST'),
 sys_context('USERENV','IP_ADDRESS'),
 sys_context('USERENV','OS_USER'),
 sys_context('USERENV','CLIENT_IDENTIFIER'));
commit;


--Hacemos un update con la informacion complementataria (el programa con el que se intento conectar)
 update DUEÑO.TABLA_LOG set CLIENT_IDENTIFIER=v_prog where LOGON_TIME=v_date;
 commit;

--Para que el usuario no se alarme y podamos identificarlo, generamos un mensaje en pantalla

 RAISE_APPLICATION_ERROR(-20000, 'Memoria insuficiente, espera 5 minutos e intentalo nuevamente');

  END IF;
  END IF;
  END IF;

END;
/

miércoles, 3 de junio de 2015

Como resolver el error ssh: connect to host port 22: Connection refused en solaris

Buen dia,

Hola me enfrenté este problema también, pero en un entorno VirtualBox, así que para resolverlo tenemos que configurar la dirección IP en el mismo segmento, por ejemplo:

Mi máquina (no la virtual):

Abrir el cmd y escribir ipconfig, me sale 100.2.2.1 (sólo por decir)

Así que en la máquina virtual debemos poner en / etc / hosts valores como 100.2.2.3, echar un vistazo en el número final, y rebotar la máquina virtual, pero antes de poner en marcha la máquina virtual configurar la red en  configuración de la  máquina virtual, por lo que necesitamos seleccionar configurar el adaptador de red en puente.

Todo esto es en un entorno Solaris.

Listo podemos realizar una conexion ssh desde un putty o MobaXterm hacia nuestra maquina virtual.

Espero les sirva, de igual modo este blog es para comentar cualquier tema de informatica, programacion, bases de datos, unix, etc y fomentar en Mexico la solucion de problemas del dba en nuestro idioma.

Saludos!