Home > Back-end >  Append list of logged in users to a log file using crontab?
Append list of logged in users to a log file using crontab?

Time:12-10

I need to create a basic log file through the use of a crontab job that appends a timestamp, followed by a list of logged in users. It must be at 23:59 each night. (I have used 18 18 * * * as an example to make sure the job works for now)

So far, I have;

!#/bin/bash
59 23 * * * (date ; who) >> /root/userlogfile.txt

for my crontab script, the output;

Fri Dec 9 18:18:01 UTC 2022
root console 00:00 Dec 9 18:15:15

My required output is something similar to;

Fri 09 Dec 23:59:00 GMT 2022

user1   tty2    2017-11-30 22:00 (:0) 

user5   pts/1   2017-11-30 20:35 (192.168.1.1) 

How would I go about this?

CodePudding user response:

To create the desired output, you will need to modify the command that you are using in your crontab script. The date command allows you to specify the format in which the date and time should be output, using the -d and FORMAT options. For example, the following command will output the date and time in the format that you have specified:

date -d "now"  "%a %d %b %H:%M:%S %Z %Y"

In addition to modifying the date command, you will also need to modify the who command to include the user's login time and the name of their terminal. The -T option can be used to include the terminal name, and the -u option can be used to include the user's login time. The -m option can be used to output the information in a more compact format, which is useful for logging purposes.

With these changes, your crontab script should look something like this:

59 23 * * * (date -d "now"  "%a %d %b %H:%M:%S %Z %Y"; who -m -T -u) >> /root/userlogfile.txt

This script will run at 23:59 each night, and will append the current date and time, followed by a list of logged in users and their login times, to the file /root/userlogfile.txt. The output will be in the format that you have specified.

  • Related