The UNIX and Linux Forums  

Go Back   El UNIX y Linux Foros > Arriba Foros > Programación de scripts de shell y
.
google unix.com



Programación de scripts de shell y Plantear preguntas sobre KSH, CSH, SH, BASH, PERL, PHP, SED, AWK y otros scripts de shell y lenguajes de script de shell aquí.

Más UNIX y Linux Foro Temas usted puede encontrar útiles
Hilo Hilo para principiantes Foro Respuestas Último mensaje
su? Que entraron en primer lugar? varungupta UNIX para usuarios avanzados y expertos 2 01-24-2008 04:10 PM
usuarios de la sesión Roshni Publicar aquí para contactar con los administradores y moderadores del sitio 1 07-06-2007 04:02 AM
Encontrar última vez que los usuarios iniciar sesión jyoung UNIX for Dummies Preguntas y Respuestas 11 04-20-2005 03:03 PM
saber quién conectado y desconectado con sus tiempos vkandati UNIX for Dummies Preguntas y Respuestas 3 03-09-2005 10:04 AM
El usuario puede iniciar sesión? Provo UNIX for Dummies Preguntas y Respuestas 1 12-07-2001 05:41 PM

Closed Thread
English Japanese Spanish French German Portuguese Italian Dutch Swedish Russian Norwegian Hungarian Hebrew Danish Bulgarian Greek Powered by Powered by Google
 
Linkback vínculo Herramientas de hilo Buscar en este Hilo Tasa de Hilo Modos de visualización
  #1 (Enlace permanente)  
Old 04-23-2007
ughosting ughosting is offline
Usuario Registrado
  
 

Fecha: abril 2007
Publicaciones: 3
La última vez conectado

Trabajo en AIX (no hay fecha-d)

¿Cómo puedo mostrar todos los usuarios que no han identificado más de 40 días?

Un pequeño script rápida sería útil, mis escrituras son siempre teniendo a la larga a ejecutar, incluso antes de que se haya terminado.

Muchas gracias!
  #2 (Enlace permanente)  
Old 04-25-2007
Jim McNamara jim mcnamara is offline Forum Staff  
...@...
  
 

Fecha: febrero 2004
Ubicación: NM
Mensajes: 5.807
Viejo código C para comprobar / var / adm / wtmp - al igual que el último comando. Es posible compilar / ejecutar en el cuadro si el directorio / var / adm / wtmp existe y no es / var / adm / wtmpx - un formato diferente.


Código:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <utmp.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <time.h>
#include <errno.h>

/* error macro */
#define ck(x) if ((x)==NULL) \
{barf("Memory/File error");}

/* limits */
#define USER_NAME_LEN 8
#define MAX_USERS 2000

/* array of usernames and times */
typedef struct
{
	char user[12];
	time_t logtime;
} ulog_t;
ulog_t array[MAX_USERS]={ {0x0}, 0 };

/* exit point for errors */
void barf(const char *msg)
{
	perror(msg);
	exit(EXIT_FAILURE);	
}

/* return size of file in bytes */
size_t filesize(const int fd)
{
	struct stat st;

	if(fstat(fd, &st) == (-1) )	
		barf("Cannot stat file");			

	return st.st_size;
}
/* return time_t seconds for ndays in the past */
time_t days_ago(const time_t ndays)
{
	time_t then=0;

    errno=0;
    then=time(NULL);
	if(then == (time_t)-1 && errno)	
		barf("");		
	then-=(86400 * ndays);
			
	return then;
}

/* map the utmp file into memory */
void *mappit(FILE *u, size_t ulen)
{
	void *addr=mmap((void *)0, ulen, PROT_READ, MAP_PRIVATE, fileno(u),0);

	if (addr==MAP_FAILED)
		barf("mmap failed");		
	
	return addr;
}
/* unmap file */
int unmappit(void *addr, size_t len)
{
	if( munmap(addr,len)==(-1))
		return 1;
		
	return 0;	
}
/* find user in array, change time or (if not found) add to array */
void find(const struct utmp *src, int *cnt)
{
	int i=0;
	int found=0;
	int limit=*cnt;	
	char tmp[10]={0x0};

	snprintf(tmp, USER_NAME_LEN+1, "%s",src->ut_user);
	if(strlen(tmp)> 0 )
	{
		for(i=0; !found && i < limit; i++)
		{
			if(strncmp(tmp, array[i].user, USER_NAME_LEN)==0)
			{
				found=1;
				if(src->ut_time > array[i].logtime)
					array[i].logtime=src->ut_time;					
			}
		}		
		if(found==0)
		{
			memcpy(array[limit].user, tmp, USER_NAME_LEN);			
			array[limit].logtime=src->ut_time;			
			limit++;
		}			
		*cnt=limit;
    }
}

void setup_array(const void *addr, int *arrlen, const size_t ulen)
{
	
	int i=0;
	int max=ulen/sizeof(struct utmp);
	int cnt=0;
	const struct utmp *f=(const struct utmp *)addr;

	for(i=0; i<max; i++, f++)
	{
		if(f->ut_type==USER_PROCESS && strlen(f->ut_user))
		{
			find(f, &cnt);
		}
	}
	*arrlen=cnt;
}
int between(const time_t ckval, const time_t low, const time_t high)
{
	int retval=(ckval >= low && ckval <= high);
	return retval;
}

int search(const time_t low_limit, const time_t high_limit, int arrlen)
{
	int i=0;
	char tmp[80]={0x0};
	time_t lt=0;
	ulog_t *p=array;

	for(i=0; i < arrlen; i++, p++)
	{
		if( (high_limit && between(p->logtime, low_limit, high_limit)) ||
			(!high_limit && p->logtime < low_limit) )
		{
			lt=p->logtime;
			strftime(tmp, sizeof(tmp), "%c", localtime(&lt));
			printf("%s: last login %s\n", p->user, tmp);
		}
	}
	
	return 0;
}

/*************************
* 
* search for the last time each one logged on
* if logon in time range prt it
***************************/

int process(FILE *u, const time_t low_limit, const time_t high_limit)
{
	int retval=0;
	size_t ulen=filesize(fileno(u));
	int arrlen=0;
	void *addr=mappit(u, ulen);

	setup_array(addr, &arrlen, ulen);
	retval=search(low_limit, high_limit, arrlen);
	retval|=unmappit(addr, ulen);
    
	return retval;
}



/*
   first argument req'd: # days
   read from /var/adm/wtmp - (file used by last)
   print all users with last logins < low_limit or with
         last logins between low_limit and high_limit when 
         high_limit is non-zero
*/
int main(int argc, char **argv)
{
	int retval=0;
	const time_t low_limit= (argc>1) ? days_ago(atoi(argv[1])): 0;
	const time_t high_limit=(argc>2) ? days_ago(atoi(argv[2])): 0;
	FILE *u=fopen("/var/adm/wtmp", "r");

 	ck(u);
	if ( low_limit > 0 && (high_limit==0 || high_limit >= low_limit))
		retval=process(u, low_limit, high_limit);
	else
	{
		fprintf(stderr,
			"Bad parameters.\n\tONE required: <number days ago>\n\tOptional: <most recent day>\n");
		fprintf(stderr,"     usage: utmp 10 5\n");	
		retval=1;
	}
    
	return retval;
}

  #3 (Enlace permanente)  
Old 04-25-2007
jgt jgt is online now
Usuario Registrado
  
 

Fecha: abril 2007
Ubicación: 44.21.48N 80.50.15W
Posts: 455
¿Existe una ". Lastlogin" en el directorio de usuarios. Si esto existe, tiene un tamaño de 0 y su mtime es igual a la última conexión, tiempo.
Por lo tanto, presumiblemente:
find /-name. lastlogin-mtime 40

Si no existe, se podrían agregar "toque. Lastlogin" para cada usuario. Perfil
y esperar 40 días para la primera aparición
  #4 (Enlace permanente)  
Old 04-25-2007
Jim McNamara jim mcnamara is offline Forum Staff  
...@...
  
 

Fecha: febrero 2004
Ubicación: NM
Mensajes: 5.807
Él también puede querer red de acceso ...

Lectura de un archivo de contabilidad es bastante garantizado para encontrar todos.
  #5 (Enlace permanente)  
Old 04-26-2007
ughosting ughosting is offline
Usuario Registrado
  
 

Fecha: abril 2007
Publicaciones: 3
Muchas gracias hasta ahora!

Gracias por las sugerencias!

Mientras tanto he llegado a esto!

No es rápido, pero hace el trabajo!

#! / usr / bin / ksh

#####
#
# Configuración de variables globales
#
#####

MIN_DAYS \u003d 2
MAX_DAYS \u003d 90
DEF_GROUP \u003d "CPX"
DATECALC \u003d "<patch_to_datecalc>"

#####
#
# Pruebas preliminares
#
#####

#
# Prueba de los parámetros correctos se pasan o informe de uso
#

$ # en el caso

1)

NUM_DAYS \u003d $ 1
SEARCH_GROUP \u003d $ DEF_GROUP
;;

2)

NUM_DAYS \u003d $ 1
SEARCH_GROUP \u003d $ 2
;;

*)

echo "Uso: $ (basename $ 0) <num_days> [<grupo>]"
salida 1
;;

esac

#
# Prueba de que el número de días que se aprobó en el rango (y, por tanto, un número)
#

if [$ () NUM_DAYS-lt $ () MIN_DAYS] | | [$ NUM_DAYS ()-gt $ (MAX_DAYS)]
entonces

echo "<num_days> ($ () NUM_DAYS) debe ser> MIN_DAYS) ($ & & <$ MAX_DAYS ()"
salida 1

fi

#
# Prueba de que el nombre del grupo pasó existe
#

grep-q "^ $ () SEARCH_GROUP" / etc / group

if [$? \u003d 1]
entonces

echo "<grupo> ($ () SEARCH_GROUP) No encontrado!"
salida 1

fi

#####
#
# Declare local y poblar matrices Funciones
#
#####

dateformat () (

DATE_MONTH \u003d $ (echo "enero \ nFeb \ nMar \ nApr \ nMay \ nJun \ nJul \ nAug \ nSep \ NOCT \ nNov \ nDec" | grep-n $ 2 | awk-F ':' '(print $ 1)')

print "$ 5 $ () DATE_MONTH $ 3"
return 0
)

#####
#
# Inicie el programa!
#
#####

SEARCH_NUM \u003d $ (grep "^ $ () SEARCH_GROUP" / etc / group | awk-F ':' '(print $ 3)')

HOY \u003d $ (dateformat $ (date | awk '(print $ 1 "" $ 2 "" $ 3 "" $ 4 "" $ 6)'))

i en $ (grep "$ () SEARCH_NUM" / etc / passwd | awk-F ':' '(print $ 1)')
hacer

#
# Asegúrese de que este usuario ha registrado antes de intentar el tratamiento de esos
#

grep-p "^ $ (i)" / etc / security / lastlog | grep-q time_last_login

if [$? \u003d 0]
entonces

LOGGED_DATE \u003d $ (perl -le "imprimir escalar localtime cambio" $ (grep-p "^ $ (i)" / etc / security / lastlog | grep time_last_login | awk '(print $ 3)'))
LOGGED_IN \u003d $ (dateformat $ LOGGED_DATE ())

DIFF_DAYS \u003d$(${ DATECALC)-a $ () HOY - LOGGED_IN $ ())

if [$ () DIFF_DAYS ge-NUM_DAYS $ ()]
entonces

tipografiada-L9 USUARIO \u003d "$ (i):"
tipografiada R4-NUMBER \u003d $ () DIFF_DAYS
echo "$ (USER) $ (NUMBER) días ($ () LOGGED_DATE)"

fi

fi

hecho


Por supuesto, mi codificación AIX es un poco de basura, de modo que si cualquier persona puede ver la forma de acelerar este hasta me interesaría.

He utilizado el script datecalc de este foro para realizar una fecha para llevar a los demás!
  #6 (Enlace permanente)  
Old 04-26-2007
ughosting ughosting is offline
Usuario Registrado
  
 

Fecha: abril 2007
Publicaciones: 3
Mi código de Linux para los interesados

#! / bin / bash

NUM_DAYS \u003d "0"
TODAY_CODE \u003d $ (echo "$ (date +% s) / 86400" | bc)

i en $ (cat / etc / passwd | awk-F ':' '(print $ 1)')
hacer

última | grep $ (i)> / dev / null 2> & 1

if [$? -eq 0]
entonces

DATE_TEXT \u003d $ (último | grep $ (i) | head -1 | awk '(print $ 5 "" $ 6)')
DATE_CODE \u003d $ (echo "$ (date-d" $ () DATE_TEXT "+% s) / 86400" | bc)
DIFF_DAYS \u003d $ (echo "$ (TODAY_CODE) - $ () DATE_CODE" | bc)

if [$ () DIFF_DAYS ge-NUM_DAYS $ ()]
entonces

echo "$ (i) - $ () DIFF_DAYS"

fi

fi

hecho
Closed Thread

Marcadores

Etiquetas
linux, mtime, perl, perl cambio, turno, cambio de perl

Herramientas de hilo Buscar en este Hilo
Buscar en este Hilo:

Búsqueda avanzada
Modos de visualización Vota a este hilo
Vota a este hilo:

Normas de envío
puede que no nuevo puesto de hilos
puede que no enviar respuestas
puede que no enviar archivos adjuntos
puede que no editar sus puestos

Código BB es Encendido
Emoticones son Encendido
[IMG] código Encendido
Código HTML es Apagado
Trackbacks son Encendido
Pingbacks son Encendido
Refbacks son Encendido




Todas las horas son GMT -4. La hora es 12:54 PM.


Powered by: vBulletin, Copyright © 2000 - 2006, Jelsoft Enterprises Limited. Traducciones de idiomas Powered by .
vBCredits v1.4 Copyright © 2007 - 2008, PixelFX Estudios
El UNIX y Linux Foros Contenido Copyright © 1993-2009. Todos los derechos Reserved.Ad Gestión por RedTyger

Las direcciones URL de contenido vBSEO 3.2.0