2012-08-02 104 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

相關問題