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

查看:26
本文介绍了登录时自动运行 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!
" >> /home/USERNAME/boot.log

推荐答案

解决这个问题的一个更优雅的方法是从已经写入且用户无法更改的日志文件中读取.没有人能比 Bjørne Malmanger 在他的回答中说得更好:

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.这很麻烦,但如果您需要比 last 更早的信息,则可能需要这样做.

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!
" >> /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天全站免登陆