且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

登录后自动运行Bash脚本

更新时间:2023-12-04 10:26:52

更优雅解决此问题的方法是从已写入且用户无法更改的日志文件中读取。没有人会比BjørneMalmanger的回答更好地说

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 ;-)

一个不错的方法是 last 命令,这很好,因为它可以整齐地显示所有登录信息:图形,控制台和SSH。

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

last

一种不太优雅但仍然安全的方法是在/var/log/auth.log上执行grep 。在我的Gnome / Ubuntu系统上,我可以使用它来跟踪图形登录:

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"

需要为每种登录类型(图形,控制台和SSH)找到适合您计算机的正确模式。这很麻烦,但是如果您需要比最后到达的信息更远的信息,则可能需要这样做。

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.

直接回答您的问题:

您可以像这样修改脚本以获取用户名

You can modify the script like this to get the username

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

并将此行添加到/ etc / profile

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