2016-08-17 61 views
-2

我試圖執行一個簡單的linux命令,通過我的java代碼將一些文本追加到遠程服務器中的文件。但它不起作用。當我在Linux中運行相同的命令時,它工作正常。'回聲'linux命令不通過Java代碼

try { 
     java.util.Properties config = new java.util.Properties(); 
     config.put("StrictHostKeyChecking", "no"); 
     JSch jsch = new JSch(); 

     Session sessionwrite = jsch.getSession(user2, host2, 22); 
     sessionwrite.setPassword(password2); 
     sessionwrite.setConfig(config); 
     sessionwrite.connect(); 
     System.out.println("Connected"); 

     Channel channel = sessionwrite.openChannel("exec"); 
     BufferedReader in = new BufferedReader(new InputStreamReader(
       channel.getInputStream())); 

     String command = "echo \"hello\" >> welcome.txt"; 
     ((ChannelExec) channel).setCommand(command); 
     System.out.println("done"); 
} 
+2

不工作是什麼意思?你覺得'welcome.txt'最終會成爲什麼?你嘗試過使用'shell'頻道嗎? –

回答

0
Channel channel = sessionwrite.openChannel("exec"); 
BufferedReader in = new BufferedReader(new InputStreamReader(
     channel.getInputStream())); 

String command = "echo \"hello\" >> welcome.txt"; 
((ChannelExec) channel).setCommand(command); 
System.out.println("done"); 

你錯過的呼叫channel.connect()connect()是實際將請求發送到遠程服務器以調用該命令的方法。完成通道後,您還應該撥打channel.disconnect()來終止它。您的代碼可能是這個樣子:

Channel channel = sessionwrite.openChannel("exec"); 
BufferedReader in = new BufferedReader(new InputStreamReader(
     channel.getInputStream())); 

String command = "echo \"hello\" >> welcome.txt"; 
((ChannelExec) channel).setCommand(command); 
channel.connect(); 
channel.disconnect(); 
System.out.println("done"); 

我要補充的是,在這個特殊的例子,沒有任何理由要打開EXEC通道的標準輸入的輸入流,所以你可以離開這一行了。