2012-08-02 101 views
2

我有用Xcode编写的Mac原生应用程序。我想在远程服务器上使用该应用程序执行一些SSH命令,并将结果返回给用户。使用本机Mac应用程序在远程Linux计算机上执行SSH命令。 (Obj-C)

是否有任何库/框架存在?那可能吗?

+0

system(“ssh .....”)? – KevinDTimm 2012-08-02 22:17:31

+0

@KevinDTimm我需要在远程机器上执行它! – Mojtaba 2012-08-03 16:44:55

+0

不,它会运行'ssh',它会(可以)连接到远程机器并在那里运行命令。请参阅下面的答案以获得丰富的版本。 – KevinDTimm 2012-08-03 18:34:10

回答

7

您将需要使用NSTask类来执行ssh命令。

下面的代码是从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. 
+0

这将在本地计算机(Mac OS)上执行,但我需要连接到运行Linux的远程计算机。 – Mojtaba 2012-08-03 16:46:03

+0

非常抱歉,我忘了一个参数!需要有用户和主机名。 – ikdc 2012-08-03 17:08:37

+0

@Mojtaba更新的代码是否工作? – ikdc 2012-08-04 03:43:40

相关问题