首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSTask运行脚本

NSTask运行脚本
EN

Stack Overflow用户
提问于 2012-05-08 22:53:30
回答 2查看 1.3K关注 0票数 4

我正在尝试使用NSTask运行以下命令:

代码语言:javascript
复制
$sudo launchctl load /Users/admin/Library/LaunchAgents/com.devdaily.crontabtest.plist

下面是我使用的代码:

代码语言:javascript
复制
NSTask *server = [NSTask new];
[server setLaunchPath:@"/bin/launchctl"];
[server setArguments:[NSArray arrayWithObjects:@"load",@"com.devdaily.crontabtest.plist",nil]];
[server setCurrentDirectoryPath:@"/Users/admin/Library/LaunchAgents/"];

NSPipe *outputPipe = [NSPipe pipe];
[server setStandardInput:[NSPipe pipe]];
[server setStandardOutput:outputPipe];

[server launch];
[server waitUntilExit]; // Alternatively, make it asynchronous.
[server release];

但是,由于sudo命令,它不能工作。我该如何解决这个问题呢?

EN

回答 2

Stack Overflow用户

发布于 2013-03-24 19:30:10

不幸的是,你不能。因为没有办法输入密码。

但是,您仍然可以通过使用NSAppleScript而不是NSTask来运行您的bash命令:编写如下applescript:

do shell script [your command] with administrator privileges

系统将要求您提供管理员密码。

示例:

代码语言:javascript
复制
NSDictionary *error = [NSDictionary new]; 
NSString *script =  @"do shell script \"launchctl load /Users/admin/Library/LaunchAgents/com.devdaily.crontabtest.plist\" with administrator privileges";  
NSAppleScript *appleScript = [[NSAppleScript new] initWithSource:script]; 
if ([appleScript executeAndReturnError:&error]) {
  NSLog(@"success!"); 
} else {
  NSLog(@"failure!"); 
}
票数 1
EN

Stack Overflow用户

发布于 2013-03-24 19:59:12

阅读苹果的Secure Coding Guide,并遵循Elevating Privileges Safely的推荐。

换句话说,不要使用sudo或类似的东西。使用SMJobBless()安装并启用启动代理。另请参阅SMJobBless sample project

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10501067

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档