The UNIX and Linux Forums  

Go Back   O UNIX e Linux Forum > Top Fóruns > Programação Shell Script e
.
google unix.com



Programação Shell Script e Post perguntas sobre ksh, CSH, SH, BASH, Perl, PHP, SED, Awk e outros scripts shell e shell scripts línguas aqui.

Mais UNIX e Linux Fórum Tópicos Você pode achar Helpfull
Fio Thread Starter Fórum Respostas Última postagem
su? Quem está autenticado Primeira? varungupta UNIX & avançada para usuários experientes 2 01-24-2008 04:10
desconectado usuários roshni Post Aqui para administradores e moderadores do site Contato 1 07-06-2007 04:02
Encontrar usuários registrados na última vez jyoung UNIX para Dummies Perguntas & Respostas 11 04-20-2005 03:03
saber quem conectado e desconectado com os seus horários vkandati UNIX para Dummies Perguntas & Respostas 3 03-09-2005 10:04
Usuário é conectado? Provo UNIX para Dummies Perguntas & Respostas 1 12-07-2001 05:41

Closed Thread
English Japanese Spanish French German Portuguese Italian Dutch Swedish Russian Norwegian Hungarian Hebrew Danish Bulgarian Greek Powered by Powered by Google
 
Linkback Thread Tools Pesquisar este Thread Rate Thread Display Modes
  #1 (permalink)  
Old 04-23-2007
ughosting ughosting is offline
Usuário
  
 

Join Date: Apr 2007
Posts: 3
A última vez registrado no

Trabalhando em AIX (então nenhuma data-d)

Como posso visualizar todos os utilizadores que não tenham registado em mais de 40 dias?

Um pequeno script rápida seria útil, meus scripts estão sempre a tomar tempo para executar, mesmo antes de serem acabadas.

Muito obrigado!
  #2 (permalink)  
Old 04-25-2007
jim McNAMARA jim mcnamara is offline Forum Staff  
...@...
  
 

Join Date: Feb 2004
Localização: NM
Mensagens: 5.770
Antigo código C para verificar / var / adm / wtmp - como o último comando. Pode compilar / rodar em sua casa se o / var / adm / wtmp existe e não é / var / adm / wtmpx - um 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 (permalink)  
Old 04-25-2007
jgt jgt is offline
Usuário
  
 

Join Date: Apr 2007
Localização: 44.21.48N 80.50.15W
Posts: 452
Existe um ". Lastlogin" arquivo no diretório home dos usuários. Se isso existe, tem um tamanho de 0 e sua mtime é igual ao último login tempo.
Então, presumivelmente:
find /-name. lastlogin-mtime 40

Se não existir você pode adicionar "touch. Lastlogin" para cada usuário do. Perfil
e esperar 40 dias para a primeira ocorrência
  #4 (permalink)  
Old 04-25-2007
jim McNAMARA jim mcnamara is offline Forum Staff  
...@...
  
 

Join Date: Feb 2004
Localização: NM
Mensagens: 5.770
Ele pode também querem rede logins ...

Ler um arquivo contabilidade é bastante garantido para encontrar todos.
  #5 (permalink)  
Old 04-26-2007
ughosting ughosting is offline
Usuário
  
 

Join Date: Apr 2007
Posts: 3
Muito obrigado até agora!

Obrigado pela sugestão!

Entretanto, eu vim com essa!

Não é rápido, mas ele faz o trabalho!

#! / usr / bin / ksh

#####
#
# Configurar Variáveis globais
#
#####

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

#####
#
# Testes preliminares
#
#####

#
# Teste para o correto parâmetros são passados ou relatório Uso
#

no caso $ #

1)

NUM_DAYS \u003d $ 1
SEARCH_GROUP \u003d $ DEF_GROUP
;

2)

NUM_DAYS \u003d $ 1
SEARCH_GROUP \u003d $ 2
;

*)

echo "Usage: $ (basename $ 0) <num_days> [<group>]"
saída 1
;

esac

#
# Teste de que o número de dias passados está na faixa (e, portanto, um número)
#

if [$ (NUM_DAYS)-lt $ (MIN_DAYS)] | | [$ (NUM_DAYS)-gt $ (MAX_DAYS)]
então

echo "<num_days> ($ (NUM_DAYS)) deve ser> $ (MIN_DAYS) & & <$ (MAX_DAYS)"
saída 1

fi

#
# Teste de que o nome do grupo passou existe
#

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

if [$? \u003d 1]
então

echo "<group> ($ (SEARCH_GROUP)) não foi encontrado!"
saída 1

fi

#####
#
# Declare local Funções e povoar arrays
#
#####

Dateformat () (

DATE_MONTH \u003d $ (echo "janeiro \ 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 o programa!
#
#####

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

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

for i in $ (grep "$ (SEARCH_NUM)" / etc / passwd | awk-F ':' '(print $ 1)')
fazer

#
# Certifique-se que este usuário tiver efetuado login antes de tentar processá-los
#

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

if [$? \u003d 0]
então

LOGGED_DATE \u003d $ (perl -le 'print scalar localtime turnos' $ (grep-p "^ $ (i)" / etc / security / lastlog | grep time_last_login | awk' (print $ 3) '))
LOGGED_IN \u003d $ (Dateformat LOGGED_DATE $ ())

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

if [$ (DIFF_DAYS)-ge $ (NUM_DAYS)]
então

compor-L9 USER \u003d "$ (i):"
compor-R4 NÚMERO \u003d $ (DIFF_DAYS)
echo "$ (USER) $ (NUMBER) dias ($ (LOGGED_DATE))"

fi

fi

feito


Claro, meu AIX codificação é um pouco lixo, por isso, se qualquer pessoa pode ver como esta velocidade até eu estaria interessado.

Tenho utilizado o script de datecalc este fórum para executar a uma data tirais os outros!
  #6 (permalink)  
Old 04-26-2007
ughosting ughosting is offline
Usuário
  
 

Join Date: Apr 2007
Posts: 3
Meu código Linux para aqueles interessados

#! / bin / bash

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

for i in $ (cat / etc / passwd | awk-F ':' '(print $ 1)')
fazer

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

if [$? -eq 0]
então

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

if [$ (DIFF_DAYS)-ge $ (NUM_DAYS)]
então

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

fi

fi

feito
Closed Thread

Marcadores

Tags
linux, mtime, perl, perl turnos, deslocar, turnos perl

Thread Tools Pesquisar este Thread
Pesquisar este Thread:

Pesquisa Avançada
Display Modes Esta taxa Thread
Esta taxa Thread:

Destacamento Regimento
Você não pode postar novas threads
Você não pode postar respostas
Você não pode postar anexos
Você não pode editar suas postagens

BB code é Ligado
Smilies são Ligado
[IMG] código é Ligado
Código HTML é Desligado
Trackbacks são Ligado
Pingbacks são Ligado
Refbacks são Ligado




Todos os horários são GMT -4. A hora é agora 12:17.


Powered by: vBulletinCopyright © 2000 - 2006, Jelsoft Enterprises Limited. Língua Traduções Powered by .
vBCredits v1.4 Copyright © 2007 - 2008, PixelFX Studios
O UNIX e Linux Fóruns Content Copyright © 1993-2009. Todos os Direitos Reserved.Ad Gestão por RedTyger

Content Relevant URLs por vBSEO 3.2.0