Run Bash Script automatically at login

I wrote a script that sends the date and username, which is logged in a log file, to record who is logged in. I am wondering how you can set this script to run automatically when the user logs in, rather than having to manually run it in the terminal. NOTE. User USERNAME is the current user who is logged in.

my code is:

#!/bin/bash printf "$(date) $HOSTNAME booted!\n" >> /home/USERNAME/boot.log 
+4
source share
3 answers

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

I would not trust the user to provide you with information. As root you take it; -)

The last command is a good way to do this, which is great because it accurately displays all logins: graphical, console, and SSH.

 last 

A less elegant but safe way is to make grep on /var/log/auth.log. On my Gnome / Ubuntu system, I can use this to track graphical inputs:

 grep "session opened for user USERNAME" 

For each type of login, you need to find the right template for your computer: graphic, console, and SSH. This is cumbersome, but you may need to do this if you need information that goes further than last .

To directly answer your question:

You can modify the script as follows 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 safe because the user will be able to edit their own log.

+4
source

Put it in the ~ / .bash_profile file. It will start every time you log in.

More information can be found on the women's rights page (i.e. man bash ) .

+3
source

Why aren't you using the last command?

I would not trust the user to provide you with information. As root you accept it ,-)

+2
source

Source: https://habr.com/ru/post/1401050/


All Articles