Sending commands to server via JSch shell channel

后端 未结 9 964
渐次进展
渐次进展 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: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")

提交回复
热议问题