Execute SSH Command on remote Linux Machine using

2020-07-27 02:39发布

问题:

I have a Mac Native app written with Xcode. I want to execute some SSH command using that application on remote servers and get the result back to user.

Is there any library/Framework exist for that? Is that possible?

回答1:

You will want to use the NSTask class to execute an ssh command.

The following code was adapted from the answer to this question.

NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"/usr/bin/ssh"]; // Tell the task to execute the ssh command
[task setArguments: [NSArray arrayWithObjects: @"<user>:<hostname>", @"<command>"]]; // Set the arguments for ssh to contain only your command. If other configuration is necessary, see the ssh(1) man page.

NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
NSFileHandle *file;
file = [pipe fileHandleForReading]; // This file handle is a reference to the output of the ssh command

[task launch];

NSData *data;
data = [file readDataToEndOfFile];

NSString *string;
string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; // This string now contains the entire output of the ssh command.