1

cmd を実行するために管理者権限が必要な Cocoa アプリケーションがありますが、二重引用符を含むファイル名などの極端な場合、このコードは機能しません。

 NSString *fileName = @"~/Documents/My\" File/";
 NSString *cmd = [NSString stringWithFormat:@"chown -R '%@' '%@';NSUserName(), fileName];
 NSString *cmd_execute = [NSString stringWithFormat:@"do shell script
 \"%@\" with administrator privileges",cmd_execute]; 
//This line is the problem, our %@ contains double quote, so cocoa 
//cannot interpret correctly.
4

1 に答える 1

2

NSAppleScript を使用して AppleScript ハンドラに引数を渡す正しい方法は次のとおりです。

// load/compile AppleScript
NSAppleScript *scpt = [[NSAppleScript alloc] initWithSource:
        @"on joinText(a, b)\n"
        @"  return a & b\n"
        @"end addTo"];

NSString *arg1 = @"Hello ";
NSString *arg2 = @"World!";

// pack positional parameters
NSAppleEventDescriptor *params = [NSAppleEventDescriptor listDescriptor];
[params insertDescriptor: [NSAppleEventDescriptor descriptorWithString: arg1] atIndex: 1];
[params insertDescriptor: [NSAppleEventDescriptor descriptorWithString: arg2] atIndex: 2];

// build Apple event to invoke user-defined handler in script
NSAppleEventDescriptor *eventDesc = [NSAppleEventDescriptor appleEventWithEventClass: 'ascr'
                                                            eventID: 'psbr'
                                                            targetDescriptor: [NSAppleEventDescriptor nullDescriptor]
                                                            returnID: 0
                                                            transactionID: 0];
[eventDesc setDescriptor: params forKeyword: '----'];
[eventDesc setDescriptor: [NSAppleEventDescriptor descriptorWithString: @"joinText"] forKeyword: 'snam'];

 // invoke handler
 NSDictionary *errorInfo = nil;
 NSAppleEventDescriptor *resultDesc = [scpt executeAppleEvent: eventDesc error: &errorInfo];
 if (resultDesc)
     NSLog(@"Result: %@\n", [resultDesc stringValue]);
 else
     NSLog(@"Error: %@\n", errorInfo);

これにより、AS スクリプトをその場で変更してコンパイルする必要がなくなります。これは、元の ObjC コードが示すように、サニタイズが不十分なためにプログラムにバグやセキュリティ ホールを導入する絶好の機会です。

...

AppleScript でシェル スクリプト文字列を組み立てる正しい方法は次のとおりです。

do shell script ("chown -R " & quoted form of username & " " & quoted form of filepath)

AppleScript のdo shell scriptコマンドは、引数を渡すための安全なメカニズムを提供しません (他の多くの点でも不十分です) が、AS 文字列にはquoted form、シェル スクリプト文字列に連結するのに適した、引用符で囲みエスケープされたバージョンのテキストを少なくとも返すプロパティがあります。 .

...

もちろん、昇格した特権で実行するためdo shell scriptだけに AppleScriptを介してシェルを呼び出すことchmod自体は、ハッキングされているわけではありませんが、これはほとんどの場合、そうするための単純な公式 API を提供していない (たとえば、「管理者特権で実行する」オプションを追加することによって) Apple の責任です。へNSUserScriptTask)。

Apple は、Service Management フレームワークと launchd を使用して特権プロセスを追加および実行する方法を示すサンプル プロジェクトSMJobBlessを提供しています。しかし、これは非常に複雑なソリューションであり、多くの人が (故意または無意識のうちに) 手抜きをしたり、完全に間違ったことをしたりします。しかし、あなたはそれを Apple に相談する必要があります。

于 2013-11-04T18:38:33.307 に答える