如何在OS X中的登录/注销时运行脚本?


10

我正在构建一个自定义渲染场管理器,我想在不使用OS X机器时自动将它们添加到渲染场。

是否有一种方法可以在任何用户注销后触发脚本运行,然后在任何用户登录后停止运行?

Answers:


10

在OS X中,有几种方法可以在登录/注销时运行脚本,有些是较新的方法,仅适用于10.5及更高版本,有些则已弃用,但是最快的方法是添加Login Hook

首先,创建要运行的脚本。打开一个终端并输入:

touch ~/script.sh
open -e !$

这将打开一个文本编辑器。输入脚本,例如,包含以下内容:

#!/bin/sh
# insert your script here

保存文件。在您的终端中,运行:

chmod +x ~/script.sh

这将使文件可执行。现在,让我们将其添加为一个钩子:

sudo defaults write com.apple.loginwindow LoginHook /usr/local/bin/script.sh 

还有一个Logout Hook对应项:

sudo defaults write com.apple.loginwindow LogoutHook /usr/local/bin/script2.sh

我已经在OS X 10.6进行了测试,它应该工作,甚至高达10.8。请记住,脚本的运行方式为root,分别只有一个钩子可用于登录和注销。

要撤消所有操作,请输入

sudo defaults delete com.apple.loginwindow LoginHook
sudo defaults delete com.apple.loginwindow LogoutHook

请注意,不建议将这种方法用于部署或其他任何方式,但是如果仅按照问题说明使用它,那应该没问题。


不适用于
优胜美地

5

10.4中不推荐使用登录挂钩,而建议使用launchd。要在登录时运行脚本,请将这样的plist保存为~/Library/LaunchAgents/test.plist。即使您不运行,它也会在下次登录时加载launchctl load ~/Library/LaunchAgents/test.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC -//Apple Computer//DTD PLIST 1.0//EN
http://www.apple.com/DTDs/PropertyList-1.0.dtd>
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>test</string>
    <key>ProgramArguments</key>
    <array>
        <string>say</string>
        <string>test</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>

有关更多信息,请参见man launchd.plist这篇博客文章


根据链接的博客文章,这将在您首次登录时加载plist,并保持加载直到系统重新启动。您如何在每次登录时使用launchd运行脚本?还是注销时?
2014年

-1

为了使这些挂钩在10.10中工作,您需要执行以下操作:

  1. 打开/etc/ttys文件:在Finder中,从“转到”菜单中选择“转到文件夹”,键入/etc/,然后单击“转到”。

  2. 在出现的窗口中,ttys在您首选的文本编辑器(例如TextEdit)中打开文件。

  3. 查找以下内容:

    console "/System/Library/CoreServices/loginwindow.app/Contents/MacOS/loginwindow" vt100 on secure window=/System/Library/CoreServices/WindowServer onoption="/usr/libexec/getty std.9600"

  4. 编辑此行,使其内容如下(此行中没有中断):

    console "/System/Library/CoreServices/loginwindow.app/Contents/MacOS/loginwindow -LoginHook /path/to/script" vt100 on secure window=/System/Library/CoreServices/WindowServer onoption="/usr/libexec/getty std.9600"

    即,在第二个引号()标记之前添加(其中是用户登录时要执行的脚本的完整路径)。-LoginHook /path/to/script/path/to/script"

  5. 保存文件。

确保用于编辑此文件的文本编辑器不会将上面的行分成多行。


或按照此处的完整说明进行操作:

http://support.apple.com/zh-cn/HT2420


不适用于
优胜美地
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.