2015-04-07 46 views
0

服務器中的文件寫我嘗試了一些命令,如如何使用Jsch EXEC

echo "Your text here" | ssh hostname 'cat >> output.txt' 

,但它沒有工作。

我該如何使用這個執行代碼或者我將要放入String命令的ssh命令寫入服務器內的文件。

public class TestWrite{ 

    private static final String user = "username here"; 
    private static final String host = "host here"; 
    private static final String password = "pass here"; 


    public static void main(String[] arg){ 
    try{ 
     JSch jsch=new JSch(); 

     Session session=jsch.getSession(user, host, 22); 
     session.setPassword(password); 
     session.setConfig("StrictHostKeyChecking", "no"); 
     session.connect(); 

     String command = "Command here"; 

     Channel channel=session.openChannel("exec"); 
     ((ChannelExec)channel).setCommand(command); 


     channel.setInputStream(null); 
     ((ChannelExec)channel).setErrStream(System.err); 

     InputStream in=channel.getInputStream(); 

     channel.connect(); 

     byte[] tmp=new byte[1024]; 
     while(true){ 
     while(in.available()>0){ 
      int i=in.read(tmp, 0, 1024); 
      if(i<0)break; 
      System.out.print(new String(tmp, 0, i)); 
     } 
     if(channel.isClosed()){ 
      if(in.available()>0) continue; 
      System.out.println("exit-status: "+channel.getExitStatus()); 
      break; 
     } 
     try{Thread.sleep(1000);}catch(Exception ee){} 
     } 
     channel.disconnect(); 
     session.disconnect(); 
    } 
    catch(Exception e){ 
     System.out.println(e); 
    } 
    } 

} 
+0

定義'它不起作用'。您是否試圖將駐留在客戶端上的數據放入服務器上的文件中? – copeg

回答

1

你可以寫一個文件與

echo "your text here" > file 

你不需要ssh因爲Jsch取代它的位置。

0

嘗試像這樣的命令:

ssh hostname 'echo "Your text here" >> output.txt'