美文网首页MacOS开发 技术集锦
MAC OS X中遇到的授权问题

MAC OS X中遇到的授权问题

作者: oh_flying | 来源:发表于2017-02-22 20:16 被阅读599次

关于MAC OS X##

去年十月份从iOS开发转到OS X开发,OS X主要由五大API来开发,分别是`Cocoa`、`Carbon`、`POSIX`、`X11`和`Java`。目前我用的是`Cocoa`来开发,OS X开发中考虑的问题更多一些,网上的资料更少一些,遇到问题后最好的解决办法就是查看[官方文档](https://developer.apple.com/search/?q=mac%20os%20x)。

什么时候需要授权?

在OS X开发中,我们会经常遇到权限的问题,比如你安装APP的时候,你如你需要删除一些配置文件的时候都需要权限,不然就无法操作,我们的项目中需要做一个卸载工具和退域工具,里面涉及到删除配置文件以及退出进程等一些需要权限的操作。

具体内容

删除配置文件的时候,通常情况下通过`NSTask`这个类打开终端,输入命令进行操作的,如:

[NSTask launchedTaskWithLaunchPath:@"/usr/bin/sudo" arguments: [NSArray arrayWithObjects:@"launchctl", @"unload", @"/Library/LaunchDaemons/com.tencent.MacScmClient.Daemon.plist",nil]];

这行代码就是用NSTask来调用终端来进行删除文件的,大概意思就是在终端输入sudo,然后执行launchctlunload的命令,但是呢,怎样写IE肯定是不行的,为什么呢,因为你没有权限这么做,有兴趣的同学可以在终端尝试一下,输入这个命令是需要输入密码的,所以怎么获取权限呢?
之前我们的工程中有获取授权的代码,这个下文再说,当时同事写了一段代码使用AppleScript来获取权限的,我再网上找了下,也找到了原文,具体的代码如下:

Boolean runProcessAsAdministrator( NSString *scriptPath, NSArray *arguments,BOOL isAdmin, NSString **output,NSString **errorDescription)
{
   NSString * allArgs = [arguments componentsJoinedByString:@" "];
   NSString *isAdminPre = @"";
   if (isAdmin) {
    isAdminPre = @"with administrator privileges";
   }
   NSString * fullScript = [NSString stringWithFormat:@"%@ %@", scriptPath, allArgs];
   NSDictionary *errorInfo = [NSDictionary new];
   NSString *script = [NSString stringWithFormat:@"do shell script \"%@\" %@", fullScript,      isAdminPre];
   NSLog(@"script = %@",script);
   NSAppleScript *appleScript = [[NSAppleScript new] initWithSource:script];
   NSAppleEventDescriptor * eventResult = [appleScript executeAndReturnError:&errorInfo];
   // Check errorInfo/var/tmp
   if (! eventResult)
   {
       // Describe common errors
       *errorDescription = nil;
       if ([errorInfo valueForKey:NSAppleScriptErrorNumber])
       {
           NSNumber * errorNumber = (NSNumber *)[errorInfo valueForKey:NSAppleScriptErrorNumber];
           if ([errorNumber intValue] == -128)
            *errorDescription = @"The administrator password is required to do this.";
       }
       // Set error message from provided message
       if (*errorDescription == nil)
       {
           if ([errorInfo valueForKey:NSAppleScriptErrorMessage])
            *errorDescription = (NSString *)[errorInfo valueForKey:NSAppleScriptErrorMessage];
       }
       return NO;
   }
   else
   {
       // Set output to the AppleScript's output
    *output = [eventResult stringValue];
       return YES;
   }
}

这段代码就是用AppleScript来获取权限的,使用方法如下:

NSString *output = @"";
NSString *error= @"";
runProcessAsAdministrator(@"", [NSArray arrayWithObjects:@"launchctl", @"unload", @"/Library/LaunchAgents/com.******.******.plist",nil],false, &output, &error);

但是这么写会有一个问题,就是我是获得权限了,但是卸载的时候往往不可能只删除一个配置文件,而是要删除很多个配置文件,起初我是这么写的:

runProcessAsAdministrator(@"", [NSArray arrayWithObjects:@"launchctl", @"unload", @"/Library/LaunchAgents/com.******.******.plist",nil],false, &output, &error);
    NSLog(@"output = %@, error = %@", output, error);
runProcessAsAdministrator(@"", [NSArray arrayWithObjects:@"launchctl", @"unload", @"/Library/LaunchDaemons/com.******.******.Daemon.plist",nil], true, &output, &error);
    NSLog(@"output = %@, error = %@", out

我就很开心的运行,但是问题来了,什么问题呢?就是你删除几个配置文件就需要输入几次用户名和密码,这样的话用户体验相当的不好,理想状态是什么呢?输入一次用户名和密码之后,获取的权限以后其他的删除配置文件的操作就不需要再次获取权限了,所以我就看了下前辈们是怎么写的,大概的代码如下:

int main(int argc, char * argv[]) {
@autoreleasepool {
    
    if (argc == 2) {
        NSLog(@"AuthHelperTool executing self-repair");
        OSStatus myStatus;
        AuthorizationFlags myFlags = kAuthorizationFlagDefaults;
        AuthorizationRef myAuthorizationRef;
        
        myStatus = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, myFlags, &myAuthorizationRef);
        if (myStatus != errAuthorizationSuccess)
            return myStatus;
        
        AuthorizationItem myItems = {kAuthorizationRightExecute, 0, NULL, 0};
        AuthorizationRights myRights = {1, &myItems};
        myFlags = kAuthorizationFlagDefaults |
        kAuthorizationFlagInteractionAllowed |
        kAuthorizationFlagPreAuthorize |
        kAuthorizationFlagExtendRights;
        
        myStatus = AuthorizationCopyRights (myAuthorizationRef, &myRights, NULL, myFlags, NULL );
        if (myStatus != errAuthorizationSuccess)
            return myStatus;
        
        char *myToolPath = argv[1];
        char *myArguments[] = {argv[1], "--fix", NULL};
        FILE *myCommunicationsPipe = NULL;
        
        myFlags = kAuthorizationFlagDefaults;
        //这句是获取管理员权限的代码
        myStatus = AuthorizationExecuteWithPrivileges(myAuthorizationRef, myToolPath, myFlags, myArguments, &myCommunicationsPipe);
        return 0;

    }
    else if (argc == 3){
    
    NSString *output = @"";
    NSString *error= @"";

    runProcessAsAdministrator(@"", [NSArray arrayWithObjects:@"launchctl", @"unload", @"/Library/LaunchAgents/com.******.******.plist",nil],false, &output, &error);
    runProcessAsAdministrator(@"", [NSArray arrayWithObjects:@"launchctl", @"unload", @"/Library/LaunchDaemons/com.******.******.Daemon.plist",nil], true, &output, &error);
}

这段代码是个可执行文件,然后在ViewController中调用的这个可执行文件。我们看到这个获取权限的方法是使用Authorization的类来获取权限的,这个也是官方文档中的获取权限的方法,具体的可以参考这里
,继续说上面的代码,前文说了这个是个可执行文件,是在ViewController中调用的,代码如下:

NSString *helperToolPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingString:@"/ExitDomain"] ;
NSLog(@"path = %@",helperToolPath);
NSArray *args = [NSArray arrayWithObjects:helperToolPath, nil];
[NSTask launchedTaskWithLaunchPath:helperToolPath arguments:args];

从这儿看到,我们是用NSTask这个类来打开终端来执行这个可执行文件的,参数为helperToolPath也就是这个可执行文件的路径,所以到了可执行文件的mian函数中,argc就是2,然后来执行下面的获取权限的代码的,下面获取权限的代码有个需要注意的地方:

char *myToolPath = argv[1];
        char *myArguments[] = {argv[1], "--fix", NULL};
        FILE *myCommunicationsPipe = NULL;
        
        myFlags = kAuthorizationFlagDefaults;
        //这句是获取管理员权限的代码
        myStatus = AuthorizationExecuteWithPrivileges(myAuthorizationRef, myToolPath, myFlags, myArguments, &myCommunicationsPipe);

这几行代码需要注意,首先myToolPath这个参数就是我们从ViewController中配置的那个参数,也就是可执行文件的路径,其次myArguments里面多了个--fix,这个不是命令,只是为了使argc的个数变为三,而

myStatus = AuthorizationExecuteWithPrivileges(myAuthorizationRef, myToolPath, myFlags, myArguments, &myCommunicationsPipe);

这行代码就是获取管理员权限的代码,从官方文档来看在10.1和10.7中是不能使用的,具体的可以看官方文档,如果想测试自己的系统能不能用,请参考github上的这个第三方库中用的测试方法,然后这行代码还有个作用,就是它又调用了一次这个可执行文件,方法中有个参数是myToolPath,这个就是可执行文件的路径,所以esle if中的代码才会执行,按照这种方法写完后就只需要输入一次用户名和密码,用户体验明显好转。

总结##

本文讲了两种获取权限的方法,一种是使用`AppleScript`来获取权限,这样写是能获取到权限,但是如多删除多个文件的话,就需要输入多次用户名和密码;另一种是用`Authorization`这个类来获取权限,先获取到权限后,然后再执行删除配置文件的操作就可以了,需要注意的地方就是,我再使用第二种方法的时候`esle if`中调用的还是`AppleScript`删除文件的方法,没有用`NSTask`这个类,这个说明一下,这儿完全可以使用`NSTask`这个类做这些事情,也就是下面这段代码:

runProcessAsAdministrator(@"", [NSArray arrayWithObjects:@"launchctl", @"unload", @"/Library/LaunchAgents/com.******.******.plist",nil],false, &output, &error);

完全可以用这段替换掉:

[NSTask launchedTaskWithLaunchPath:@"/usr/bin/sudo" arguments: [NSArray arrayWithObjects:@"launchctl", @"unload", @"/Library/LaunchDaemons/com.tencent.MacScmClient.Daemon.plist",nil]];

这个只是我项目中遇到的一些关于权限的问题以及解决办法,还有很多不足之处,希望各路大神多多指正,我也会再继续深入学习,及时修改这篇文章。

参考资料

[https://developer.apple.com/search/?q=Authorization&type=Guides]
[http://stackoverflow.com/questions/29796363/how-to-add-root-privileges-to-my-osx-application]
[http://codego.net/213006/]
[http://www.tanhao.me/pieces/1279.html/]
[https://github.com/sveinbjornt/STPrivilegedTask]

相关文章

网友评论

  • 5b9912977239:不会是同事吧,我在公司项目中看见过这段代码
    oh_flying:@Null8Pointer 哦,很巧啊
    5b9912977239:@Null8Pointer 哦哦,那应该就是同事了
    oh_flying:是吗?我之前做的iOA
  • 九剑仙:你好,我问个问题,我写了一段终端命令,用来将本地代码上传至github等远程仓库中,但是需要输入远程的仓库的用户名和密码,如何将这两个参数传到命令中去
    九剑仙:@oh_flying 3q
    oh_flying:[NSTask launchedTaskWithLaunchPath:@"/usr/bin/sudo" arguments: [NSArray arrayWithObjects:@"launchctl", @"unload", @"/Library/LaunchDaemons/com.tencent.MacScmClient.Daemon.plist",nil]];你看这一句,其实就是执行了launchctl和unload的命令,参数就是后面那个path,具体的你可以查查NSTask与这个终端命令/usr/bin/sudo看看具体怎么做
    oh_flying:@九剑仙 这个我还得想想看,我也好久没搞这个了。

本文标题:MAC OS X中遇到的授权问题

本文链接:https://www.haomeiwen.com/subject/ggwmwttx.html