Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a Bash Script automatically upon login

Tags:

bash

unix

centos

I wrote a script that sends the date and username of the person who logs in to a log file to keep a record of who has logged in. I am wondering how can you set this script to execute automatically when a user logs in rather than have to manually run it in the terminal. NOTE: the USERNAME is the current user that is logged in.

my code:

#!/bin/bash

printf "$(date) $HOSTNAME booted!\n" >> /home/USERNAME/boot.log
like image 787
Jason Gagnon Avatar asked Dec 21 '22 00:12

Jason Gagnon


1 Answers

A more elegant way to solve this problem is to read from log files that are already being written and cannot be changed by the user. No one could say it better than Bjørne Malmanger's in his answer:

I wouldn't trust the user to GIVE you the information. As root you TAKE it ;-)

A nice way to do this is the last command, which is great because it neatly displays all logins: Graphical, console and SSH.

last

A less elegant but still secure way is to do a grep on /var/log/auth.log. On my Gnome/Ubuntu system I can use this to track graphical logins:

grep "session opened for user USERNAME"

The right pattern for your machine needs to be found for each login type: graphical, console and SSH. This is cumbersome, but you might need to do it if you need information that goes further back than last reaches.

To directly answer your question:

You can modify the script like this to get the username

#!bin/bash
printf "$(date) $HOSTNAME booted!\n" >> /home/$(whoami)/boot.log

And add this line to /etc/profile

. /path/to/script.sh

This is not secure though because the user will be able to edit his own log

like image 194
cmc Avatar answered Dec 30 '22 12:12

cmc