Question

Most system administrators would like to know the utilization of their systems by their users. On...

Most system administrators would like to know the utilization of their systems by their users. On a Linux system, each user's login records are normally stored in the binary file /var/log/wtmp. The login records in this binary file can not be viewed or edited directly using normal Linux text commands like 'less', 'cat', etc. The 'last' command is often used to display the login records stored in this file in a human readable form. Please check the man page of the 'last' command for available options. The following is the contents of the file named "usage_data_file", which is a sample output of the 'last' command with the '-Fiw' flag on:

$ last -Fiw > usage_data_file
$ cat usage_data_file
rchan    pts/9        10.40.91.236     Tue Feb 13 16:53:42 2018 - Tue Feb 13 16:57:02 2018  (00:03)    
cwsmith  pts/10       10.40.105.130    Wed Feb 14 23:09:12 2018 - Thu Feb 15 02:11:23 2018  (03:02)
rchan    pts/2        10.40.91.236     Tue Feb 13 16:22:00 2018 - Tue Feb 13 16:45:00 2018  (00:23)    
rchan    pts/5        10.40.91.236     Tue Feb 15 16:22:00 2018 - Tue Feb 15 16:55:00 2018  (00:33)    
asmith   pts/2        10.43.115.162    Tue Feb 13 16:19:29 2018 - Tue Feb 13 16:22:00 2018  (00:02)    
tsliu2   pts/4        10.40.105.130    Tue Feb 13 16:17:21 2018 - Tue Feb 13 16:30:10 2018  (00:12)    
cwsmith  pts/13       10.40.91.247     Tue Mar 13 18:08:52 2018 - Tue Mar 13 18:46:52 2018  (00:38)    
asmith   pts/11       10.40.105.130    Tue Feb 13 14:07:43 2018 - Tue Feb 13 16:07:43 2018  (02:00)

It is always desirable to have a daily, weekly, or monthly usage reports by user or by remote host based on the above information.

Complete a detail algorithm for producing monthly usage reports by user or by remote host based on the information stored in any given files generated from the 'last' command.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Working code implemented in Python & Shell and appropriate comments provided for better understanding:

Here I am attaching code for these files:

Note: I am not able to paste all the code here. That's why I am sharing whole project code through a link.

Link: gofile.io/d/IoblRq

Mirror Link: anonymousfiles.io/9QHjPnr2/

Source code for main.py:

#!/usr/bin/env python3

import os
import sys
import argparse
import time

#arg.parse info and options

def list(option, filename):
       '''
       Description
       '''
       if option =="user":
           k = open(filename, "r")
           print ("List of users for: " + filename)
           readlines = k.readlines()

           mylist=[]
           userlist=[]
           finl=[]

           for line in readlines:
               newline = line.split()
               mylist.append(newline)

           for listuser in mylist[0:31]:
               userlist.append(listuser[0])

           for user in userlist:
               if user not in finl:
                   finl.append(user)

       elif option =="host":

           k = open(filename,"r")

           print("List of hosts for: " + filename)

           readlines = k.readlines()
           mylist=[]
           userlist=[]
           finl=[]

           for line in readlines:
               newline = line.split()
               mylist.append(newline)

           for listuser in mylist[0:31]:
               userlist.append(listuser[2])

           for i in userlist:
               if i not in finl:
                   finl.append(i)

       print(*finl, sep = "\n")

def userlisting(name, filename, loginuser):
   '''
   This function
   '''

   tlist = []
   f = open(filename, "r")
   readlines = f.readlines()
   mylist = []

   for line in readlines:
       new_line = line.split()
       mylist.append(new_line)

   if loginuser == '-u':
       for i in mylist[0:31]:
           if i[0] == name:
               tlist.append(i[3:14])
   elif loginuser == '-r':
       for i in mylist[0:31]:
           if i[2] == name:
               tlist.append(i[3:14])

   return tlist


def daily(listofusers):
   '''
   This function
   '''
   datetime= 0
   totaltime = 0
   datelist = []
   daytime = []

   for x in listofusers:
       test = x[1:5]
       del test[2]
       strlist1 = ' '.join(x[0:5])
       strlist2 = ' '.join(x[6:])
       strlist3 = ' '.join(test[0:])

       a = time.mktime(time.strptime(strlist1, "%a %b %d %H:%M:%S %Y"))
       b = time.mktime(time.strptime(strlist2, "%a %b %d %H:%M:%S %Y"))

       timeinsec = time.mktime(time.strptime(strlist3, "%b %d %Y"))
       datetime = time.strftime("%Y %m %d", time.localtime(timeinsec))
       totaltime = totaltime + (b - a)
       reductime = b - a
       datelist.append(datetime)
       daytime.append(int(reductime))
  
   rounduplist = []

   sumlist = []

   for t, y in zip(datelist, daytime):
      
       if t not in rounduplist:
           rounduplist.append(t)
           sumlist.append(y)
      
      
       elif t in rounduplist:
           sumlist[-1] = sumlist[-1] + y

   print("<><><><><><><><><><><><><><>")
   print("Date\t\tUsage in Seconds")

   for j, k in zip(rounduplist, sumlist):
       print(j, "\t", k)
  
   print("Total\t\t", int(totaltime))


def weekly(listofusers):
   '''
   function
   '''

   datetime= 0
   totaltime = 0
   datelist = []
   daytime = []

   for x in listofusers:
       test = x[1:5]

       del test[2]
       strlist1 = ' '.join(x[0:5])
       strlist2 = ' '.join(x[6:])
       strlist3 = ' '.join(test[0:])

       a = time.mktime(time.strptime(strlist1, "%a %b %d %H:%M:%S %Y"))
       b = time.mktime(time.strptime(strlist2, "%a %b %d %H:%M:%S %Y"))

       timeinsec = time.mktime(time.strptime(strlist3, "%b %d %Y"))
      
       weekoftheyear = time.strftime("%Y %W", time.localtime(timeinsec))
      
       datetime = time.strftime("%Y %m %d", time.localtime(timeinsec))
       totaltime = totaltime + (b - a)
       reducetime = b - a
      
       datelist.append(weekoftheyear)
       daytime.append(int(reducetime))

   rounduplist = []
   sumlist = []
   for t, y in zip(datelist, daytime):
       if t not in rounduplist:
           rounduplist.append(t)
           sumlist.append(y)          
       elif t in rounduplist:
           sumlist[-1] = sumlist[-1] + y

   print("<><><><><><><><><><><><><><>")
   print("Date\t\tUsage in Seconds")
   for j, k in zip(rounduplist, sumlist):
       print(j, "\t", k)

   print("Total\t\t", int(totaltime))

def monthly(listofusers):
   '''
   function
   '''

   datetime= 0
   totaltime = 0
   datelist = []
   daytime = []

   for x in listofusers:
       test = x[1:5]

       del test[2]
       strlist1 = ' '.join(x[0:5])
       strlist2 = ' '.join(x[6:])
       strlist3 = ' '.join(test[0:])

       a = time.mktime(time.strptime(strlist1, "%a %b %d %H:%M:%S %Y"))
       b = time.mktime(time.strptime(strlist2, "%a %b %d %H:%M:%S %Y"))

       timeinsec = time.mktime(time.strptime(strlist3, "%b %d %Y"))
      
       weekoftheyr = time.strftime("%Y %m", time.localtime(timeinsec))
      
       datetime = time.strftime("%Y %m %d", time.localtime(timeinsec))
       totaltime = totaltime + (b - a)
       reducetime = b - a
      
       datelist.append(weekoftheyr)
       daytime.append(int(reducetime))

   rounduplist = []
   sumlist = []
   for t, y in zip(datelist, daytime):
       if t not in rounduplist:
           rounduplist.append(t)
           sumlist.append(y)          
       elif t in rounduplist:
           sumlist[-1] = sumlist[-1] + y

   print("<><><><><><><><><><><><><><>")
   print("Date\t\tUsage in Seconds")
   for j, k in zip(rounduplist, sumlist):
       print(j, "\t", k)

   print("Total\t\t", int(totaltime))

def verbose():
   '''
   This function
   '''
   print("Files to be processed", args.F)
   print("Type of args for files", type(args.F))

if __name__ == '__main__':
   parser = argparse.ArgumentParser(description="Usage Report based on the last command",epilog="Copyright 2019 - Igor Kossinov")
   parser.add_argument("-l", "--list", type=str, choices=['user','host'], help="generate user name or remote host IP from the given files")
   parser.add_argument("-r", "--rhost", help="usage report for the given remote host IP")
   parser.add_argument("-t","--type", type=str, choices=['daily','weekly','monthly'], help="type of report: daily, weekly, and monthly")
   parser.add_argument("-u", "--user", help="usage report for the given user name")
   parser.add_argument("-v","--verbose", action="store_true",help="turn on output verbosity")
   parser.add_argument("F", nargs = "+", help="list of files to be processed")
   args=parser.parse_args()
   select = sys.argv[2]
   filename = args.F[0]
   loginuser = sys.argv[1]
  
  
   if args.list:
       if args.verbose:
           print("Generating list for", select)
           verbose()
           print("processing usage report for the following:")
           print("reading login/logout record files", args.F)
       print("Generating list for", select)
       list(select, filename)
   elif args.rhost:
       timely = sys.argv[4]
       if args.verbose:
           verbose()
           print("usage report for remote host:", select)
           print("usage report for type:", timely)
           print("processing usage report for the following:")
           print("reading login/logout record files", args.F)
       if timely == "daily":
           print("Daily Usage Report for", select)
           daily(userlisting(select, filename, loginuser))
       elif timely == "weekly":
           print("Weekly Usage Report for", select)
           weekly(userlisting(select, filename, loginuser))
       elif timely == "monthly":
           print("Monthly Usage Report for", select)
           monthly(userlisting(select, filename, loginuser))
   elif args.user:
       timely = sys.argv[4]
       if args.verbose:
           verbose()
           print("usage report for user:", select)
           print("usage report for type:", timely)
           print("processing usage report for the following:")
           print("reading login/logout record files", args.F)
       if timely == "daily":
           print("Daily Usage Report for", select)
           daily(userlisting(select, filename, loginuser))
       elif timely == "weekly":
           print("Weekly Usage Report for", select)
           weekly(userlisting(select, filename, loginuser))
       elif timely == "monthly":
           print("Monthly Usage Report for", select)
           monthly(userlisting(select, filename, loginuser))  

Sample Output Screenshots:

output.txt - Notepad File Edit Format View Help [user@centos7 username ] $ bash -x test_run_final.bash + test_data-usage_data

Hope it helps, if you like the answer give it a thumbs up. Thank you.

Add a comment
Know the answer?
Add Answer to:
Most system administrators would like to know the utilization of their systems by their users. On...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Most system administrators would like to know the utilization of their systems by their users. On...

    Most system administrators would like to know the utilization of their systems by their users. On a Linux system, each user's login records are normally stored in the binary file /var/log/wtmp. The login records in this binary file can not be viewed or edited directly using normal Linux text commands like 'less', 'cat', etc. The 'last' command is often used to display the login records stored in this file in a human readable form. Please check the man page of...

  • Objective : Write a C Shell script which copies all files(*.java and *.class) from your home dire...

    Objective : Write a C Shell script which copies all files(*.java and *.class) from your home directory to a new one, and Analyze the new directory information such as number of files, user permissions, and disk usage. Sample Output:                                                    << CS Directory Analysis >>      Date:   ============================================================ Current Directory: /home/tomss New Directory Created : /home/tomss/pgm01 File information Total Number of files : 22 files Directory files:   0 files Plain text files:   10 files File have read permissions: 3 files File have...

  • Risk management in Information Security today Everyday information security professionals are bombarded with marketing messages around...

    Risk management in Information Security today Everyday information security professionals are bombarded with marketing messages around risk and threat management, fostering an environment in which objectives seem clear: manage risk, manage threat, stop attacks, identify attackers. These objectives aren't wrong, but they are fundamentally misleading.In this session we'll examine the state of the information security industry in order to understand how the current climate fails to address the true needs of the business. We'll use those lessons as a foundation...

  • All of the following questions are in relation to the following journal article which is available...

    All of the following questions are in relation to the following journal article which is available on Moodle: Parr CL, Magnus MC, Karlstad O, Holvik K, Lund-Blix NA, Jaugen M, et al. Vitamin A and D intake in pregnancy, infant supplementation and asthma development: the Norwegian Mother and Child Cohort. Am J Clin Nutr 2018:107:789-798 QUESTIONS: 1. State one hypothesis the author's proposed in the manuscript. 2. There is previous research that shows that adequate Vitamin A intake is required...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT