登录时自动运行 Bash 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9674176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:46:12  来源:igfitidea点击:

Run a Bash Script automatically upon login

bashunixcentos

提问by Jason Gagnon

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.

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

my code:

我的代码:

#!/bin/bash

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

采纳答案by cmc

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:

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

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

我不相信用户会向您提供信息。作为根,你接受它;-)

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

执行此操作的一个好方法是last命令,它很棒,因为它整齐地显示所有登录:图形、控制台和 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:

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

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 lastreaches.

需要为每种登录类型找到适合您机器的正确模式:图形、控制台和 SSH。这很麻烦,但如果您需要更远的信息,您可能需要这样做last

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

并将这一行添加到 /etc/profile

. /path/to/script.sh

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

但这并不安全,因为用户将能够编辑自己的日志

回答by Bj?rne Malmanger

Why don't you use the lastcommand?

你为什么不使用last命令?

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

我不相信用户会向您提供信息。作为根,你接受它;-)

回答by gpojd

Put it in ~/.bash_profile. It will be run each time they log in.

把它放在 ~/.bash_profile 中。每次登录时都会运行它。

More information is available at the women's rights page (i.e. man bash).

更多信息可在妇女权利页面 (即man bash) 获得