Search code examples
javashellunixsshjsch

How to write on a file inside a server using Jsch exec


I tried some commands such as

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

but it didnt work.

How can I write in a file inside the server using this exec code or just the ssh command that I will put to String command.

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);
    }
  }

}

Solution

  • You can write to a file with

    echo "your text here" > file
    

    You don't need ssh because Jsch takes its place.