Variable in NSTask - Objective-C Cocoa - objective-c

I want to use command line in Cocoa for record of the password in a bunch of keys.
But I can't insert a variable at line. How to make it?
How $pass to provide me self.PassKey?
self.PassKey = [_PassTextField stringValue];
NSTask *taskPass = [[NSTask alloc] init];
[taskPass setLaunchPath:#"/bin/bash"];
[taskPass setArguments:[NSArray arrayWithObjects: #"-c", #"/usr/bin/security delete-generic-password -a ${USER} -s post | security add-generic-password -a ${USER} -s post -w $pass", nil]];
[taskPass launch];
Thanks for any help!
Thanks to all for the help and such prompt reply!
So works:
self.PassKey = [_PassTextField stringValue];
NSLog(#"text changed: %#", self.PassKey); ///I printed in a window the password 12345
NSString * command = [NSString stringWithFormat:#"/usr/bin/security delete-generic-password -a ${USER} -s post | security add-generic-password -a ${USER} -s post -w %#", self.PassKey]; ///I receive a line /usr/bin/security delete-generic-password -a ${USER} -s postftp | security add-generic-password -a ${USER} -s postftp -w 12345
NSLog(#"command line: %#", command);
NSTask *taskPass = [[NSTask alloc] init];
[taskPass setLaunchPath:#"/bin/bash"];
[taskPass setArguments:[NSArray arrayWithObjects: #"-c", command, nil]];
[taskPass launch];
Record of the password in a bunch of keys results.

Related

How check if output of bash script contains a certain string in Objective-C?

I would like to do something if the output of a shell script contains the string "Caddy 2 serving static files on :2015". This is what I have so far but the beach ball is just spinning. It seems it is because of the last command in my bash script which starts a server. There is no exit in the bash script so it does not end. The output of the bash script is correct and I can see "Caddy 2 serving static files on :2015". But it seems this code is only working with a bash script which has a end.
If someone wants to try, here you can download the executable caddy file which I am using in my bash script: https://caddyserver.com/download
- (IBAction)localHost:(id)sender
{
// execute bash script to start server
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:#"/bin/bash"];
[task setArguments:[NSArray arrayWithObjects:[[NSBundle mainBundle] pathForResource:#"caddy-start" ofType:#""], nil]];
NSPipe *pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
NSFileHandle *file = [pipe fileHandleForReading];
[task launch];
NSData *data = [file readDataToEndOfFile];
NSString *result = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(result);
NSString *string = result;
NSString *substring = #"Caddy 2 serving static files on :2015";
if ([string rangeOfString:substring].location != NSNotFound) {
NSLog(#"Yes it does contain that substring");
}
else if ([string rangeOfString:substring].location == NSNotFound) {
NSLog(#"No it does NOT contain that substring");
}
}
And here is my bash script:
#!/bin/bash
DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
cd "${DIR}"
pwd
#open http://localhost:2015
# kill server if already running
kill -9 $(lsof -ti:2015)
(./caddy_darwin_amd64 stop) &
(./caddy_darwin_amd64 file-server --listen :2015 --root Content/) &

Start Application as specific user from LaunchDaemon

I am currently trying to launch an Application in /Applications from a LaunchDaemon as specific user. Is there a way that I can launch this application without giving the program root privileges? I am writing the Daemon in objective C.
In your launch daemon's plist, which should reside in /Library/LaunchDaemons, you can set the UserName key:
<key>UserName</key>
<string>userForThisProcess</string>
where userForThisProcess is the user you want to use to run the application.
I have solved this issue in a little quirky way now. I use NSTask in conjunction with sudo and open. Maybe someone needs this in the future:
+ (bool)start_app_bundle_as_user:(NSString *)path with_user_name:(NSString *)user_name
{
NSString *cmd = [NSString stringWithFormat:#"/usr/bin/sudo -i -u %# -- open -a %#", user_name, path];
NSTask *task = [[NSTask alloc] init];
NSArray *args = [NSArray arrayWithObjects:#"-c", cmd, nil];
[task setLaunchPath:#"/bin/sh"];
[task setArguments:args];
[task launch];
[task waitUntilExit];
return [task terminationStatus] == 0;
}

Running shell script with NSTask causes posix_spawn error

I'm trying to run a shell script with NSTask with the following code:
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:#"/Users/username/connect.sh"];
[task launch];
But I get An uncaught exception was raised and Couldn't posix_spawn: error 8
If I just run the script in terminal, everything works.
Here is what the script contains:
if [ ! -d ~/Remote/username/projects ]
then
sshfs -C -p 22 user#remotecomputer.com:/home/username ~/Remote/username
fi
You can also add #!/bin/bash to the start of your script:
#!/bin/bash
if [ ! -d ~/Remote/username/projects ]
then
sshfs -C -p 22 user#remotecomputer.com:/home/username ~/Remote/username
fi
You need to use setLaunchPath like this:
[task setLaunchPath:#"/bin/sh"];
Then use setArguments for your script:
[task setArguments: [NSArray arrayWithObjects: #"~/connect.sh", nil]];

Running shell script using NSTask in Mac OS

I have written a shell script and the purpose of that script is to capture packet using TCPDUMP and write that capture packet to .pcap file
Script is: TCPDumpScript.sh
echo "peter" | sudo -S tcpdump -i rv0 -n -s 0 -w dumpfile.pcap tcp
I am launching (TCPDumpScript.sh) using NSTask. Getting following output
tcpdump: WARNING: rv0: That device doesn't support promiscuous mode
(BIOCPROMISC: Operation not supported on socket)
tcpdump: WARNING: rv0: no IPv4 address assigned
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on rv0, link-type PKTAP (Packet Tap), capture size 65535 bytes
Problem 1:
Using NSTask. "dumpfile.pcap" is being created.
but when I run the same script using Terminal, its being created with desired captured packets.
Problem 2:
Whenever making changes in TCPDumpScript.sh and then launching script using NSTask. I am getting following error
"launch path not accessible"
But I do via terminal
chmod +x TCPDumpScript.sh
Then I am able to launch this script without any error using NSTask.
So, my question is Can't I create file (Problem 1) "dumpfile.pcap" using NSTask ?
And Do I always require to run permission change command on script file (Problem 2) ?
Please guide me.
(void)runScript:(NSArray*)arguments {
dispatch_queue_t taskQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
dispatch_async(taskQueue, ^{
self.isRunning = YES;
#try {
NSString *path = [NSString stringWithFormat:#"%#", [[NSBundle mainBundle] pathForResource:#"TcpDumpScript" ofType:#"sh"]];
self.buildTask = [[NSTask alloc] init];
self.buildTask.launchPath = path;
self.buildTask.arguments = arguments;
// Output Handling
self.outputPipe = [[NSPipe alloc] init];
self.buildTask.standardOutput = self.outputPipe;
[[self.outputPipe fileHandleForReading] waitForDataInBackgroundAndNotify];
[[NSNotificationCenter defaultCenter] addObserverForName:NSFileHandleDataAvailableNotification object:[self.outputPipe fileHandleForReading] queue:nil usingBlock:^(NSNotification *notification){
NSData *output = [[self.outputPipe fileHandleForReading] availableData];
NSString *outStr = [[NSString alloc] initWithData:output encoding:NSUTF8StringEncoding];
dispatch_sync(dispatch_get_main_queue(), ^{
self.outPutTxt.string = [self.outPutTxt.string stringByAppendingString:[NSString stringWithFormat:#"\n%#", outStr]];
// Scroll to end of outputText field
NSRange range;
range = NSMakeRange([self.outPutTxt.string length], 0);
[self.outPutTxt scrollRangeToVisible:range];
});
[[self.outputPipe fileHandleForReading] waitForDataInBackgroundAndNotify];
}];
[self.buildTask launch];
[self.buildTask waitUntilExit];
}
#catch (NSException *exception) {
NSLog(#"Problem Running Task: %#", [exception description]);
}
#finally {
[self.Start setEnabled:YES];
[self.spinner stopAnimation:self];
self.isRunning = NO;
}
});
}

How to unzip file via terminal in Objective-c

I want to unzip the file via terminal on Mac instead of using ZipArchive or SSZipArchive.
In terminal, I tried "unzip" command and it works good, but I do not how to express via objective c code.
I've tried this way (link: Unzip without prompt) It works but only unzipped half of my files instead of all the files.
Thanks !!
Have you tried the system() function?
system("unzip -u -d [destination full path] [zip file full path]");
You'll need to construct an NSString with your full command (including the file paths), and turn it into a C string for the system command, something like this:
NSString *myCommandString =
[NSString stringWithFormat:#"unzip -u -d %# %#", destinationPath, zipPath];
system([myCommandString UTF8String]);
This won't return any of the command's output, so you'd be better off with the solution from the Unzip without prompt question if you want details about how the operation went, but if your project doesn't need error-handling this should be fine.
See the following. I've revised a bit.
- (void)unzipme {
NSTask *task = [[NSTask alloc] init];
NSMutableString *command = [[NSMutableString alloc] initWithString:#""];
NSArray *args;
[task setLaunchPath:#"/bin/sh"];
[command appendString:#"unzip "];
[command appendString:[self convertShell:sourcePath];
[command appendString:#" "];
[command appendString:-d ];
[command appendString:[self convertShell:[self exportPath]]];
args = [NSArray arrayWithObjects:#"-c",command,nil]; // Line 10
[task setArguments:args];
NSPipe *pipe1;
pipe1 = [NSPipe pipe];
[task setStandardOutput: pipe1];
[task launch];
[task waitUntilExit];
}
- (NSString *)convertShell: (NSString *)path {
static NSString *chr92 = #"\\";
NSMutableString *replace = [[NSMutableString alloc]initWithString:chr92];
[replace appendString:#" "];
NSString *sPath = [self Replace:path :#" " :replace];
return sPath;
}
convertShell converts the Objective-C path to Shell path. Moreover, according to the unzip Man Page, this command-line tool takes a switch (-d) to specify a directory where to unzip an archive. sourcePath is a source zip file to unzip. exportPath is a destination folder. If you get an error, insert NSLog(#"%#",command); before Line 10 and show me what the command says.