我试图找出当用户启动会话时如何执行 root 命令。
我发现向这个文件添加命令/etc/rc.local
应该在启动后执行命令,但是我的命令没有被执行,或者可能系统还没有准备好执行它。 (该命令运行良好)
也许一个例子可以澄清我想要做什么。几乎所有桌面管理器中的设置窗口都有一个名为“会话和启动”的选项,在“应用程序自动启动”部分下,可以添加当前用户登录后将执行的命令。
我想这样做,但使用需要 root 权限的命令。
答案1
我找到了一个解决方案,创建一个扫描用户的脚本。
这是我的 /etc/rc.local 脚本:
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
/usr/bin/detect_login
exit 0
这是 detector_login 脚本:
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
import os, time
Buffer_list=[]
while True:
users=os.popen('''who | cut -d' ' -f1 | sort | uniq''')
users=users.read()
Current_List=users.split('\n')
Current_List=filter(None,Current_List)
if Current_List:
if Current_List != Buffer_list:
if len(Current_List) > len(Buffer_list):
#HERE YOU ADD THE COMMANDS, inside the triple quotes.
# add each command in a new line
# i let you an example for turning the brightness down..
os.system('''/usr/bin/xdotool key XF86MonBrightnessDown''')
Buffer_list=Current_List
time.sleep(0.5)
我建议以 root 身份运行一次脚本来检查它是否正常工作,因为如果出现一个错误 rc.local 将停止。 (愚蠢的错误可能是例如缩进空格,从 stackexchange 论坛复制 python 脚本时经常发生)
答案2
您可能感兴趣pam_exec
。我用它来打开额外的端口到已成功通过身份验证的地址sshd
。我的/etc/pam.d/sshd
有
account optional pam_exec.so /usr/local/bin/update-whitelist
脚本update-whitelist
看起来像
#!/bin/sh
set -e
# Called from PAM when logging in via SSH.
# Adds current client to SSH whitelist.
WHITELIST=/proc/net/xt_recent/WHITELIST
test -n "$PAM_RHOST"
test -f "$WHITELIST"
# Handle PAM_RHOST as hostname or IPv4 dotted-quad
if echo "$PAM_RHOST" | /bin/grep -P -q '^\d+\.\d+\.\d+\.\d+$'
then echo "+$PAM_RHOST" >"$WHITELIST"
else /usr/bin/host "$PAM_RHOST" | /bin/sed -n -e 's/.* has address /+/p' >"$WHITELIST"
fi
(我有与 一起iptables
使用的规则)。xt_recent
WHITELIST
另外有趣的可能是libpam-script
,它可以运行任意命令作为身份验证或会话启动的一部分:
$ aptitude show libpam-script
Package: libpam-script
Version: 1.1.4-1
Priority: extra
Section: universe/admin
Description: PAM module which allows executing a script
This module will allow you to execute scripts during authorization, password
changes and sessions. This is very handy if your current security application
has no PAM support but is accessible with perl or other scripts.
Homepage: http://sourceforge.net/projects/pam-script
我实际上没有使用过这个,但它可能值得研究。