登录后自动运行Bash脚本 [英] Run a Bash Script automatically upon login

查看:122
本文介绍了登录后自动运行Bash脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个脚本,该脚本将登录人员的日期和用户名发送到日志文件中,以记录登录的人员。我想知道如何设置此脚本以在用户登录时自动执行而不是必须在终端中手动运行它。注意:USERNAME是当前登录的用户。

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.

我的代码:

#!/bin/bash

printf "$(date) $HOSTNAME booted!\n" >> /home/USERNAME/boot.log


推荐答案

更优雅解决此问题的方法是从已写入且用户无法更改的日志文件中读取。没有人会比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

这篇关于登录后自动运行Bash脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆