【发布时间】:2020-11-27 22:03:11
【问题描述】:
我正在开发一个mac应用程序,它获取用户帐户的用户名和密码并切换到该用户帐户。
我有执行此操作的 AppleScript。当我从脚本编辑器运行它时,它工作正常。但是当我在 mac 应用程序中使用它时,相同的脚本不起作用。
Apple 脚本切换到名为 test 的用户:
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 中编写代码时遗漏了什么,请告诉我。或者是否有任何其他方式可以在用户之间切换。
【问题讨论】:
-
至少不要忽略可能的错误。传递一个
NSDictionary指针并查看它包含的内容。应用程序是否被沙盒化?如果是,您将无法使用NSAppleScript运行脚本 -
应用没有沙盒化。