Example usage for org.apache.commons.net.ssh.connection Session exec

List of usage examples for org.apache.commons.net.ssh.connection Session exec

Introduction

In this page you can find the example usage for org.apache.commons.net.ssh.connection Session exec.

Prototype

Command exec(String command) throws ConnectionException, TransportException;

Source Link

Document

Execute a remote command.

Usage

From source file:examples.ssh.X11.java

public static void main(String... args) throws Exception {
    SSHClient ssh = new SSHClient();

    // Compression makes X11 more feasible over slower connections
    // ssh.useCompression();

    ssh.loadKnownHosts();//from w  w  w.j  av a  2 s. c om

    /*
     * NOTE: Forwarding incoming X connections to localhost:6000 only works if X is started without the
     * "-nolisten tcp" option (this is usually not the default for good reason)
     */
    ssh.registerX11Forwarder(new SocketForwardingConnectListener(new InetSocketAddress("localhost", 6000)));

    ssh.connect("localhost");
    try {

        ssh.authPublickey(System.getProperty("user.name"));

        Session sess = ssh.startSession();

        /*
         * It is recommendable to send a fake cookie, and in your ConnectListener when a connection comes in replace
         * it with the real one. But here simply one from `xauth list` is being used.
         */
        sess.reqX11Forwarding("MIT-MAGIC-COOKIE-1", "26e8700422fd3efb99a918ce02324e9e", 0);

        Command cmd = sess.exec("firefox");

        new Pipe("stdout", cmd.getInputStream(), System.out).start();
        new Pipe("stderr", cmd.getErrorStream(), System.err).start();

        // Wait for session & X11 channel to get closed
        ssh.getConnection().join();

    } finally {
        ssh.disconnect();
    }
}