AppleScript 以管理员身份运行程序

时间:2021-10-15 14:45:35

以下这条Apple Script可以用管理员身份去执行一个命令或程序, 权限是继承的。

do shell script "chmod 777 /tmp" with administrator privileges

在Objective-C里也可以

        NSDictionary *error = [NSDictionary new];
        NSString *script = @"do shell script \"chmod 777 /tmp\" with administrator privileges";
        
        NSAppleScript *appleScript = [[NSAppleScript alloc] initWithSource:script];
        
        if ([appleScript executeAndReturnError:&error]) {
            NSLog(@"sucess");
        }
        else
        {
            NSLog(@"fail!");
        }

用whoami来获取当前的权限,  输出到/tmp/me文件里

        NSDictionary *error = [NSDictionary new];
        NSString *script = @"do shell script \"whoami > /tmp/me\" with administrator privileges";
        
        NSAppleScript *appleScript = [[NSAppleScript alloc] initWithSource:script];
        
        if ([appleScript executeAndReturnError:&error]) {
            NSLog(@"sucess");
        }
        else
        {
            NSLog(@"fail!");
        }