Sending commands to server via JSch shell channel

后端 未结 9 850
渐次进展
渐次进展 2020-11-30 03:37

I can\'t figure it out how I can send commands via JSch shell channel.

I do this, but it doesn\'t work:

JSch shell = new JSch();
String command = \"c         


        
相关标签:
9条回答
  • 2020-11-30 04:01

    try this code :

             JSch jsch=new JSch();
    
             System.out.println("Getting session");
             Session session=jsch.getSession("root","10.0.0.0",22);
    
              System.out.println("session is ::::"+session.getHost());
              // username and password will be given via UserInfo interface.
              UserInfo ui = new MyUserInfo("Lab@123", null);
              //UserInfo ui = new MyUserInfo(password, null);
              session.setUserInfo(ui);
              session.setPassword("Lab@123");
              Properties config = new java.util.Properties();
              config.put("StrictHostKeyChecking", "no");
              session.setConfig(config);
              session.connect(40000);
    
    
                  Channel channel=session.openChannel("exec"); 
                  ((ChannelExec)channel).setCommand("ls");
    
                  channel.connect();
                  channel.run();
    
                  // get I/O streams for remote scp
                  OutputStream out=channel.getOutputStream();
                  InputStream in=channel.getInputStream(); 
    
    
              String output="";
              while (channel.isClosed()!=true) {
    
                  try {
                    output+=streamToString(in);
    
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    
            }
    
                System.out.println("Output is :::"+output);
                channel.disconnect();
                session.disconnect();
        }
    
        public static String streamToString(InputStream input)throws Exception 
        { String output = ""; while(input.available()>0) { output += ((char)(input.read())); } return output; }
    
    
    
        public static OutputStream stringToStream(String charset) throws IOException{
    
            byte[] bytes = charset.getBytes();
            /*ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            InputStreamReader isr = new InputStreamReader(bais);*/
            InputStream is = null;
            OutputStream os = null;
            try {
                is = new ByteArrayInputStream(charset.getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //byte[] buf = new byte[1024];
            int numRead;
    
              while ( (numRead = is.read(bytes) ) >= 0) {
                  os.write(bytes, 0, numRead);
              }        
            return os;      
    
    0 讨论(0)
  • 2020-11-30 04:02

    With piped input and output streams seems interesting:

    JSch jsch = new JSch();
    jsch.addIdentity("/home/audrius/.ssh/blablabla", "blablablabla");
    
    String user = "audrius";
    String host = "ultrastudio.org";
    
    Session session = jsch.getSession(user, host, 439);
    session.setConfig("StrictHostKeyChecking", "no");           
    session.connect();
    
    Channel channel = session.openChannel("shell");
    
    PipedInputStream pip = new PipedInputStream(40);
    channel.setInputStream(pip);
    
    PipedOutputStream pop = new PipedOutputStream(pip);
    PrintStream print = new PrintStream(pop);           
    channel.setOutputStream(System.out);
    
    print.println("ls");
    
    0 讨论(0)
  • 2020-11-30 04:06

    I realize that this is an old thread, but I have struggled with a similar problem today. This is my solution.

    public class ChannelConsole {
    
    // ================================================
    // static fields
    // ================================================
    
    // ================================================
    // instance fields
    // ================================================
    
    private Session session;
    
    // ================================================
    // constructors
    // ================================================
    
    public ChannelConsole(Session session) {
        this.session = session;
    }
    
    // ================================================
    // getters and setters
    // ================================================
    
    // ================================================
    // public methods
    // ================================================
    
    public String execute(String command) throws JSchException {
        command = command.trim() + "\n";
    
        ChannelExec channel = (ChannelExec) this.session.openChannel("exec");
        channel.setCommand(command);
    
        ByteArrayOutputStream responseStream = new ByteArrayOutputStream();
        channel.setOutputStream(responseStream);
    
        channel.connect();
    
        try {
            awaitChannelClosure(channel);
        } catch (InterruptedException e) {
            // no one cares
        }
    
        String result = responseStream.toString();
        closeQuietly(responseStream);
        return result;
    
    }
    
    // ================================================
    // private methods
    // ================================================
    
    private void awaitChannelClosure(ChannelExec channel) throws InterruptedException {
        while (channel.isConnected()) {
            Thread.sleep(100);
        }
    }
    
    private static void closeQuietly(Closeable closeable) {
        if (closeable == null) {
            return;
        }
    
        try {
            closeable.close();
        } catch (IOException ignored) {
            ignored.printStackTrace();
        }
    }
    
    }
    

    Using this class you can just do something like : shell = new ChannelConsole(this.session); String result = shell.execute("quota -v; echo; echo \"Disk storage information:\"; df -hk")

    0 讨论(0)
提交回复
热议问题