首页 > 解决方案 > Applescript 在脚本编辑器中有效,但在 Xcode 中无效

问题描述

我正在开发一个 mac 应用程序,它获取用户帐户的用户名和密码并切换到该用户帐户。

我有执行此操作的 AppleScript。当我从脚本编辑器运行它时,它工作正常。但是当我在 mac 应用程序中使用它时,相同的脚本不起作用。

切换到名为test的用户的 Apple 脚本:

set theUser to "test"
set thePassword to "test@123"
set theUser to do shell script "/usr/bin/id -u " & theUser
do shell script "/System/Library/CoreServices/'Menu Extras'/user.menu/Contents/Resources/CGSession -switchToUserID " & theUser
repeat 2 times
    delay 2
    try
        tell application "System Events"
            tell process "SecurityAgent"
                set value of text field 1 of window "Login" to thePassword
                key code 36
            end tell
        end tell
        exit repeat
    on error
        delay 1
    end try
end repeat

Mac 应用程序中使用的 Objective-C 代码:

NSAppleScript *switchUser = [[NSAppleScript alloc] initWithSource:
    @"set theUser to \"test\" \n"
    @"set thePassword to \"test@123\" \n"
    @"set theUser to do shell script \"/usr/bin/id -u \" & theUser \n"
    @"do shell script \"/System/Library/CoreServices/'Menu Extras'/user.menu/Contents/Resources/CGSession -switchToUserID \" & theUser \n"
    @"repeat 2 times \n"
    @"   delay 1 \n"
    @"   try \n"
    @"       tell application \"System Events\" \n"
    @"           tell process \"SecurityAgent\" \n"
    @"               set value of text field 1 of window \"Login\" to thePassword \n"
    @"               key code 36 \n"
    @"            end tell \n"
    @"       end tell \n"
    @"        exit repeat \n"
    @"    on error \n"
    @"        delay 1 \n"
    @"    end try \n"
    @"end repeat" ];
NSDictionary *err = nil;
[switchUser executeAndReturnError:&err];
if(err) {
        NSLog(@"***** Apple script returned error: %@", err);
    }

如果我在目标 C 中编写代码时遗漏了什么,请告诉我。或者是否有任何其他方式可以在用户之间切换。

标签: objective-capplescript

解决方案


得到了问题。该脚本工作正常,但是当我们尝试切换用户时,当前用户的所有应用程序都会被杀死。这就是为什么它不起作用。

为了完成这项工作,我必须在守护程序服务中运行此脚本,该服务将运行而与用户帐户无关。


推荐阅读