无法使用jsch执行sftp子命令

时间:2018-10-08 15:33:31

标签: java linux sftp jsch

这是我的代码,该代码登录到sftp服务器并执行命令“ dzdo su-ibmusr”命令,并更改and文件夹的路径并执行ls命令。这是代码

public class Sudo{
  public static void main(String[] arg) throws Exception{

      int port=22;
      String name ="john";
      String ip ="xxxx";
      String password ="root";

      JSch jsch = new JSch();
      Session session = jsch.getSession(name, ip, 22);
      session.setPassword(password);
      session.setConfig("StrictHostKeyChecking", "no");
      System.out.println("Establishing Connection...");
      session.connect();
      System.out.println("Connection established.");

      ChannelExec channelExec = (ChannelExec)session.openChannel("exec");

      InputStream in = channelExec.getInputStream();


      channelExec.setCommand("dzdo su - john");
      OutputStream out = channelExec.getOutputStream();
      out.write(("cd /xx.yy/zz \n").getBytes());

      out.write(("ls \n").getBytes());
      out.flush();
      channelExec.connect();

      BufferedReader reader = new BufferedReader(new InputStreamReader(in));
      String line;
      int index = 0;
      StringBuilder sb = new StringBuilder();
      while ((line = reader.readLine()) != null)
      {
          System.out.println(line);
      }
      session.disconnect();
  }
}

我正处于例外之下

Exception in thread "main" java.io.IOException: failed to initialize the channel.
    at com.jcraft.jsch.Channel$1.init(Channel.java:242)
    at com.jcraft.jsch.Channel$1.write(Channel.java:253)
    at java.io.OutputStream.write(OutputStream.java:75)
    at com.consol.citrus.samples.todolist.Sudo.main(Sudo.java:43)

1 个答案:

答案 0 :(得分:1)

移动线

channelExec.connect();

在此块上方:

 OutputStream out = channelExec.getOutputStream();
 out.write(("cd /xx.yy/zz \n").getBytes());
 out.write(("ls \n").getBytes());
 out.flush();

因此,您首先建立连接,然后获取输出流。