【问题标题】:How to write on a file inside a server using Jsch exec如何使用 Jsch exec 在服务器内的文件上写入
【发布时间】:2015-06-12 10:17:18
【问题描述】:

我尝试了一些命令,例如

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

但它没有工作。

如何使用此 exec 代码或仅使用我将放入 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);
    }
  }

}

【问题讨论】:

  • 定义“它不起作用”。您是否尝试将驻留在客户端上的数据放入服务器上的文件中?

标签: java shell unix ssh jsch


【解决方案1】:

尝试如下命令:

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

【讨论】:

    【解决方案2】:

    你可以写入一个文件

    echo "your text here" > file
    

    您不需要ssh,因为 Jsch 取代了它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-01
      • 2014-11-29
      • 2012-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多