Deep understanding of the last command and its data source under Linux __linux

Source: Internet
Author: User

Last
Data source
:/var/log/wtmp ( default records information on the number of logons per user and duration) and/var/log/btmp (details, including logon failure requests)
Data source Format : binary (can be read through the dump-utmp command)
Last [-adrx][-f][-n] [account name ...] [Terminal number ...]

Figure 1 Last Command format
Parameter description:
-a the host name or IP address from where to log into the system, displayed on the last line.
-D converts the IP address to the host name.
-F < record file > Specify record file, default is to display records of wtmp files in/var/log directory, but/var/log directory btmp can display more content, can display remote logins, such as SSH login, including failed logon requests.
-N < Show number of columns > or-< number of columns > sets the number of displayed columns in the list.
-R does not display the host name or IP address of the login system.
-X displays information such as system shutdown, reboot, and changes in execution levels.
-I display specific IP logins

-T displays information before YYYYMMDDHHMMSS

Instance 1

Last

Figure 2 Last
Normal command reboot is shown as down, and power is forced to reboot as crash

Field Description:

first column: User name

second column: terminal location

third column: Login IP or kernel

Fourth column: Start time

Fifth Column: End time (still login in has not yet exited down until the normal shutdown crash until forced shutdown)

Sixth column: Duration

Instance 2

Last-x

Figure 3 Last-x

Instance 3

Last-n

Figure 4 Last-x-N

Instance 4

last-f/var/log/btmp | head-100

Figure 5 Last-f/var/log/btmp | head-100

Instance 5

last-t 20130819090800

Show logon information before 09:09:00 2013-08-19

Figure 6 Last-t 20130819090800

Deep Understanding-promotion

structure

The utmp file holds information about the users who are currently in the system.
The wtmp file holds information about users who have logged on to the system.

The/var/log/wtmp file structure, like the/var/run/utmp file structure, is a reference to the struct utmp in/usr/include/bits/utmp.h

/* the ' struct utmp ' type, describing entries in the Utmp file.
   GNU version.
   Copyright (C) 1993, 1996, 1997, 1998, 1999, 2002 free Software Foundation, Inc.

   This is part of the GNU C Library. The GNU C Library is free software; Can redistribute it and/or modify it under the terms of the GNU lesser General public License as published by th e free Software Foundation;

   Either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it would be useful, but without any WARRANTY;  Without even the implied warranty of merchantability or FITNESS for A particular purpose.

   The GNU Lesser general public License to more details. You are should have received a copy of the GNU Lesser General public License with the GNU C Library;  If not, write to the free Software Foundation, Inc., Temple Place, Suite, Boston, MA 02111-1307 USA. * * #ifndef _utmp_h # error "Never include <bits/utmp.h> directly; Use <utmp.h> instead. "#endif #include <paths.h> #include <sys/time.h> #include <sys/types.h> #i Nclude <bits/wordsize.h> #define UT_LINESIZE #define UT_NAMESIZE #define UT_HOSTSIZE 256/* structure  Describing an entry in the database of previous logins. * * struct Lastlog {#if __wordsize = && defined __wordsize_compat32 int32_t; #else ll_time
Ll_time;
    #endif Char ll_line[ut_linesize];
  Char Ll_host[ut_hostsize];


};  /* The structure describing the status of a terminated process.  This type is used in ' struct utmp ' below.  * * struct Exit_status {short int e_termination; * Process termination status.		*/short int e_exit;  /* Process exit status.


*/
  };  /* The structure describing a entry in the user accounting database.		* * struct UTMP {short int ut_type;  /* Type of login.			* * pid_t ut_pid;  /* Process ID of the login process. * * Char Ut_line[Ut_linesize];  /* devicename.		* * Char ut_id[4];  /* Inittab ID.	* * Char ut_user[ut_namesize];  /* Username.	* * Char ut_host[ut_hostsize];  /* Hostname for remote login.	* * struct exit_status ut_exit;  /* Exit Status of a process marked as dead_process.  */* The ut_session and UT_TV fields must is the same size when compiled 32-and.  This allows the data files and shared memory to is shared between 32-and 64-bit applications.		* * #if __wordsize = = && defined __wordsize_compat32 int32_t ut_session;  /* Session ID, used for windowing.		* * struct {int32_t tv_sec;  /* Seconds.		* * int32_t tv_usec;  /* microseconds.			*/} UT_TV;  /* Time entry is made.		* * #else long int ut_session;  /* Session ID, used for windowing.		* * struct timeval ut_tv;  /* Time entry is made.	* * #endif int32_t ut_addr_v6[4];  /* Internet address of remote host.		* * Char __unused[20];  /* Reserved for future use.

*/
}; /* Backwards compatibility haCks.  * * #define UT_NAME Ut_user #ifndef _no_ut_time/* We have a problem here: ' Ut_time ' is also used.  Define _no_ut_time If the compiler complains. * * Define Ut_time ut_tv.tv_sec #endif #define UT_XTIME ut_tv.tv_sec #define UT_ADDR ut_addr_v6[0]/* Values for the '  Ut_type ' field of a ' struct utmp '.  * * #define EMPTY 0/* No valid user accounting information.  * * #define RUN_LVL 1/* The system ' s runlevel.  * * #define BOOT_TIME 2/* Time of System BOOT.  * * #define NEW_TIME 3/* after system clock changed.  * * #define OLD_TIME 4/* time when system clock changed.  * * #define INIT_PROCESS 5/* Process spawned by the INIT process.  * * #define LOGIN_PROCESS 6/* Session leader of a logged in user.  * * #define USER_PROCESS 7/* Normal PROCESS.  * * #define DEAD_PROCESS 8/* terminated PROCESS.  * * #define ACCOUNTING 9/* Old Linux name for the EMPTY type. * * #define UT_UNKNOWN EMPTY/* Tell the user so we have a modern system with Ut_host, Ut_pid, UT_type, ut_id and Ut_tv fields.
 * #define _HAVE_UT_TYPE 1 #define _HAVE_UT_PID 1 #define _HAVE_UT_ID 1 #define _HAVE_UT_TV 1 #define _HAVE_UT_HOST 1


       The functions for reading and modifying these files are as follows (/USR/INCLUDE/UTMP.H):

/* Copyright (C) 1993, 1996, 1997, 1998, 1999 free Software Foundation, Inc.

   This is part of the GNU C Library. The GNU C Library is free software; Can redistribute it and/or modify it under the terms of the GNU lesser General public License as published by th e free Software Foundation;

   Either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it would be useful, but without any WARRANTY;  Without even the implied warranty of merchantability or FITNESS for A particular purpose.

   The GNU Lesser general public License to more details. You are should have received a copy of the GNU Lesser General public License with the GNU C Library;  If not, write to the free Software Foundation, Inc., Temple Place, Suite, Boston, MA 02111-1307 USA. * * #ifndef _utmp_h #define _UTMP_H 1 #include <features.h> #include <sys/types.h> __begin_decls/* Get S Ystem DEpendent values and data structures.  * * #include <bits/utmp.h>/* Compatibility names for the strings of the canonical file names. * * #define UTMP_FILE _path_utmp #define UTMP_FILENAME _path_utmp #define Wtmp_file _path_wtmp #define WTMP_FILENAME _path_
   WTMP/* Make FD is the controlling terminal, stdin, stdout, and stderr;  Then close FD.  Returns 0 on success and nonzero on error.


*/extern int login_tty (int __fd) __throw;  /* Write The given entry into utmp and wtmp.

* * extern void login (__const struct utmp *__entry) __throw;  /* Write The UTMP entry to say the user in Ut_line has logged out.

* * extern int logout (__const char *__ut_line) __throw;  /* Append to wtmp a entry for the current time and the given info.

* * extern void logwtmp (__const char *__ut_line, __const char *__ut_name, __const char *__ut_host) __throw;  /* Append entry UTMP to the Wtmp-like file wtmp_file.
    */extern void updwtmp (__const char *__wtmp_file, __const struct utmp *__utmp) __throw;  /* Change name of the Utmp file to is examined.

* * extern int utmpname (__const char *__file) __throw;  /* Read next entry from a Utmp-like file.

* * extern struct utmp *getutent (void) __throw;  * Reset the input stream to the beginning of the file.

* * extern void setutent (void) __throw;  /* Close the current open file.

* * extern void endutent (void) __throw;  * Search forward from the "the" Utmp file until the next entry with a ut_type matching.

* * extern struct utmp *getutid (__const struct utmp) *__id; * Search forward from the "the" Utmp file until the next entry with a ut_line matching  .

* * extern struct utmp *getutline (__const struct utmp) *__line;  /* Write out entry pointed to from utmp_ptr into the UTMP file.


* * extern struct utmp *pututline (__const struct utmp) *__utmp_ptr;  #ifdef __USE_MISC/* reentrant versions of the file for handling utmp files. * * extern INT Getutent_r (struct utmp *__buffer, struct, utmp **__result) __throw;

extern int Getutid_r (__const struct utmp *__id, struct utmp *__buffer, struct utmp) **__result;

extern int Getutline_r (__const struct utmp *__line, struct utmp *__buffer, struct utmp) **__result;  #endif/* Use Misc.
 * * __END_DECLS #endif/* utmp.h * *


The Utmpname () function sets the path where the UTMP file is located, and the default path is macro _path_utmp, which is defined in/usr/include/paths.h

#define _PATH_UTMP "/var/run/utmp"

The Setutent () function opens the file utmp and points the file pointer to the beginning of the file.
The Getutent () function reads one struct UTMP structure at a time from the file utmp. Read failed to return null.
The Endutent () function closes the file utmp.
The Pututline () function writes a struct UTMP structure into the file utmp.

Here's a little program that mimics the WHO command under Linux (MYWHO.C) based on this knowledge.

#include <stdio.h>

#include <stdlib.h>

#include <utmp.h>

#include <time.h>



int main ()

{

        struct utmp *p_utent;

        Long T;



        Setutent (); /* rewinds The file pointer to the beginning of the Utmp file/while

        (p_utent = Getutent ())!= NULL) {

                if (p_utent ->ut_type!= user_process) 

                        continue;

                printf ("%s\t", p_utent->ut_user); 

                printf ("%s\t", p_utent->ut_line); 

                t = p_utent->ut_tv.tv_sec;

                printf ("%.20s\t", CTime (&t) + 4);

                printf ("(%s) \ n", p_utent->ut_host);



        }

        Endutent (); /* Closes the utmp file. * * return



        0;

}

Compile

Gcc-o mywho mywho.c

Run

./mywho

Figure 7 Mywho Run Results

Add the following statement to the above program to read the user information that has been logged into the system

Utmpname (_PATH_WTMP); * * #define _PATH_WTMP "/var/log/wtmp" * *

#include <stdio.h>

#include <stdlib.h>

#include <utmp.h>

#include <time.h>



int main ()

{

        struct utmp *p_utent;

        Long T;



        Utmpname (_PATH_WTMP); * * #define _PATH_WTMP "/var/log/wtmp"



        /Setutent ()/* rewinds the file pointer to the beginning of the utmp file */< C9/>while ((p_utent = Getutent ())!= NULL) {

                if (p_utent->ut_type!=) user_process 

                        ;

                printf ("%s\t", p_utent->ut_user); 

                printf ("%s\t", p_utent->ut_line); 

                t = p_utent->ut_tv.tv_sec;

                printf ("%.20s\t", CTime (&t) + 4);

                printf ("(%s) \ n", p_utent->ut_host);



        }

        Endutent (); /* Closes the utmp file. * * return



        0;

}


Compile

Gcc-o mywho mywho.c

Run

./mywho

Figure 8 mywho Run results (so user login information)

The above functions are not thread-safe and cannot be reentrant because they store the returned results in a static variable that can be overwritten by the same call that follows.
The version that corresponds to Reentrant is as follows (/USR/INCLUDE/UTMP.H):

#define _GNU_SOURCE/* or _svid_source or _bsd_source *

/#include <utmp.h>



int getutent_r (struct utmp *ubuf , struct utmp **UBUFP);
int Getutid_r (struct utmp *ut, struct utmp *ubuf, struct utmp);
int Getutline_r (struct utmp *ut, struct utmp *ubuf, struct utmp);


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.