Example usage for org.apache.commons.net.ssh SSHClient disconnect

List of usage examples for org.apache.commons.net.ssh SSHClient disconnect

Introduction

In this page you can find the example usage for org.apache.commons.net.ssh SSHClient disconnect.

Prototype

@Override
public void disconnect() throws IOException 

Source Link

Document

Disconnects from the connected SSH server.

Usage

From source file:examples.ssh.SFTPDownload.java

public static void main(String[] args) throws Exception {
    SSHClient ssh = new SSHClient();
    ssh.loadKnownHosts();//w  ww.  j a  va  2 s.com
    ssh.connect("localhost");
    try {
        ssh.authPublickey(System.getProperty("user.name"));
        ssh.newSFTPClient().get("well", "/tmp/");
    } finally {
        ssh.disconnect();
    }
}

From source file:examples.ssh.SFTPUpload.java

public static void main(String[] args) throws Exception {
    SSHClient ssh = new SSHClient();
    ssh.loadKnownHosts();//from  w  ww .  java2  s . com
    ssh.connect("localhost");
    try {
        ssh.authPublickey(System.getProperty("user.name"));
        ssh.newSFTPClient().put("/Users/shikhar/well", "/tmp/");
    } finally {
        ssh.disconnect();
    }
}

From source file:examples.ssh.SCPDownload.java

public static void main(String[] args) throws Exception {
    SSHClient ssh = new SSHClient();
    // ssh.useCompression(); // => significant speedup for large file transfers on fast links
    ssh.loadKnownHosts();/*from   ww w  . j av  a 2s . c  om*/
    ssh.connect("localhost");
    try {
        ssh.authPublickey(System.getProperty("user.name"));
        ssh.newSCPFileTransfer().download("well", "/tmp/");
    } finally {
        ssh.disconnect();
    }
}

From source file:examples.ssh.LocalPF.java

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

    ssh.loadKnownHosts();/*from w  w w .jav  a  2 s  . c  o  m*/

    ssh.connect("localhost");
    try {

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

        /*
         * _We_ listen on localhost:8080 and forward all connections on to server, which then forwards it to
         * google.com:80
         */

        ssh.newLocalPortForwarder(new InetSocketAddress("localhost", 8080), "google.com", 80).listen();

    } finally {
        ssh.disconnect();
    }
}

From source file:examples.ssh.SCPUpload.java

public static void main(String[] args) throws Exception {
    SSHClient ssh = new SSHClient();
    ssh.loadKnownHosts();/*  ww  w  . jav  a2 s .  c o  m*/
    ssh.connect("localhost");
    try {
        ssh.authPublickey(System.getProperty("user.name"));

        // Compression = significant speedup for large file transfers on fast links
        // present here to demo algorithm renegotiation - could have just put this before connect()
        ssh.useCompression();

        ssh.newSCPFileTransfer().upload("/Users/shikhar/well", "/tmp/");
    } finally {
        ssh.disconnect();
    }
}

From source file:examples.ssh.Exec.java

public static void main(String... args) throws Exception {
    SSHClient ssh = new SSHClient();
    ssh.loadKnownHosts();/*ww w.j a va  2  s  .  c om*/

    ssh.connect("localhost");
    try {

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

        Command cmd = ssh.startSession().exec("man sshd_config");

        // Pipe.pipe(cmd.getInputStream(), System.out, cmd.getLocalMaxPacketSize(), false);
        System.out.print(cmd.getOutputAsString());
        System.out.println("\n** exit status: " + cmd.getExitStatus());

    } finally {
        ssh.disconnect();
    }
}

From source file:examples.ssh.RemotePF.java

public static void main(String... args) throws Exception {
    SSHClient client = new SSHClient();
    client.loadKnownHosts();/*from   w  w  w  .  j av  a2  s  . c o m*/

    client.connect("localhost");
    try {

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

        /*
         * We make _server_ listen on port 8080, which forwards all connections to us as a channel, and we further
         * forward all such channels to google.com:80
         */
        client.getRemotePortForwarder().bind(new Forward(8080), //
                new SocketForwardingConnectListener(new InetSocketAddress("google.com", 80)));

        // Something to hang on to so forwarding stays
        client.getTransport().join();

    } finally {
        client.disconnect();
    }
}

From source file:examples.ssh.RudimentaryPTY.java

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

    ssh.loadKnownHosts();/*from   w  w  w.ja  v a2  s.  com*/

    ssh.connect("localhost");

    Shell shell = null;

    try {

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

        Session session = ssh.startSession();
        session.allocateDefaultPTY();

        shell = session.startShell();

        new Pipe("stdout", shell.getInputStream(), System.out) //
                .bufSize(shell.getLocalMaxPacketSize()) //
                .start();

        new Pipe("stderr", shell.getErrorStream(), System.err) //
                .bufSize(shell.getLocalMaxPacketSize()) //
                .start();

        // Now make System.in act as stdin. To exit, hit Ctrl+D (since that results in an EOF on System.in)

        // This is kinda messy because java only allows console input after you hit return
        // But this is just an example... a GUI app could implement a proper PTY

        Pipe.pipe(System.in, shell.getOutputStream(), shell.getRemoteMaxPacketSize(), false);

    } finally {

        if (shell != null)
            shell.close();

        ssh.disconnect();
    }
}

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  . jav  a2s.c  o m*/

    /*
     * 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();
    }
}

From source file:org.smallfoot.filexfer.ApacheCommonsNetSFTP.java

/**
 * Attempt an upload to the remote server.  Initially very basic, this can be extended for all the intelligence we need to get data through.
 *
 * This function, given a filename, connects to an FTP server and attempts to store the file.
 * Initially the username and password are defaulted to those usable to upload from PAK_RED, but
 * later (when i can look at URL factories) this can be extended.  The capability will be
 * preserved to give the function a list of statuses and a position so that a later threaded
 * design can try a number of uploads in parallel, ditching all but the most efficient: on
 * connection, so status-indiciates; on successful 1-k upload with a temp filename,
 * status-indicates finished 1k, and checks whether others are -- if others are ahead of it,
 * status-indicates as "losing" and deletes its temp file; others behind it will so-suicide; if
 * it's the non-losing, then this thread "continues" the upload from 1k, or deletes/restarts if
 * continuation is impossible.  In that way, the fastest connection continues, the others give
 * up, timeouts are handled implicitly./*from   ww w.ja v  a  2  s. c  o m*/
 *
 * Where possible, checksum post-upload is verified
 *
 * Where possible, a checksum file {filename}.sum is uploaded
 * Where possible, a manifest XML file is sent (my hostname, my user ID, any tasks or objectives, etc)
 *
 * @param file filename to upload
 * @param uploadNotify array of identifiers (email address or jabber contacts) to list as notify recipients in the upload checksum file
 * @return "OK, ##", "FAIL, ##", "UNKNOWN" based on results (where "##" is a line number of variable length)
 */
public boolean upload(File file, Vector<String> uploadNotify) throws FileTransferWinchException {
    String checksum = null;
    SSHClient ssh = new SSHClient();

    try {
        checksum = checksum(file);
    } catch (java.security.NoSuchAlgorithmException nsae) {
        throw new FileTransferChecksumMismatchException(
                "Checksum algorithm \"MD5\" is not available on this platform");
    } catch (java.io.FileNotFoundException fnfe) {
        throw new FileTransferWinchException("Local file not readable", fnfe);
    } catch (java.io.IOException ioe) {
        throw new FileTransferWinchException("I/O Error reading local file", ioe);
    }

    String targetPath = getPath();
    if ((null == targetPath) || (0 == targetPath.length()))
        targetPath = ".";

    String checksumnote = "# MD5 checksum (see RFC-1321)\n" + "# Verify using: \n" + "#   Windows:\n"
            + "#     see http://support.microsoft.com/kb/841290\n" + "#     VICT.BAT -c " + file.getName()
            + "\n" + "#   MacOSX, BSD-based systems:\n" + "#     md5 " + file.getName() + "\n"
            + "#   Linux (ie Redhat, CentOS, Debian, Ubuntu):\n" + "#     md5sum " + file.getName() + "\n"
            + "#     md5sum -c " + file.getName() + ".sum\n" + "#   Practically every platform:\n"
            + "#     java -jar vict.jar -c " + file.getName() + "\n";
    if (null != uploadNotify)
        for (String s : uploadNotify)
            checksumnote += "# NOTIFY: " + s + "\n";

    String checksumline = checksum + "  " + file.getName();

    System.out.println("connecting to upload " + file.getName() + " (" + checksumline + ")");
    checksumline += "\n";
    try {
        ssh.loadKnownHosts();

        //System.out.println ("connecting to "+getHost() +" port "+getPort()+ " to transfer "+ file.getName());
        ssh.connect(getHost());
        //System.out.println ("authorizing to "+getHost()+" using \""+getUser()+"\", \""+getPass()+"\"");
        if ((null != getPass()) && (getPass().length() > 0)) {
            //System.out.println ("authorizing u p");
            /* lacking a java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); the following line simply generates a org.apache.commons.net.ssh.userauth.UserAuthException */
            ssh.authPassword(getUser(), getPass());
            //System.out.println ("authorized u p");
        } else {
            //System.out.println ("authorizing u k");
            ssh.authPublickey(getUser());
            //System.out.println ("authorized u k");
        }

        //System.out.println ("uploading " + file.getName());

        File temp = File.createTempFile(file.getName(), ".tmp");
        //System.out.println ("created " + temp.getAbsolutePath());
        java.io.FileOutputStream tempo = new java.io.FileOutputStream(temp);
        tempo.write(checksumnote.getBytes(), 0, checksumnote.length());
        tempo.write(checksumline.getBytes(), 0, checksumline.length());
        tempo.flush();
        ssh.newSFTPClient().put(temp.getAbsolutePath(), targetPath/* getPath()+file.getName()+".sum" */);
        tempo.close();
        if (!temp.delete())
            temp.deleteOnExit();
        ssh.newSFTPClient().put(file.getName(), targetPath /* getPath()+file.getName() */ );
        //it.sauronsoftware.ftp4j.FTPReply reply = client.sendCustomCommand("XMD5 \""+file.getName()+"\"");
        ssh.disconnect();

        //System.out.println ("MD5 (XMD5): server offers no checksum, so you're on your own...");
        return false;

    } catch (org.apache.commons.net.ssh.userauth.UserAuthException uae) {
        throw new FileTransferWinchException("Authentication failure: " + uae);
    } catch (java.io.IOException ioe) {
        ioe.printStackTrace();
        throw new FileTransferIllegalFSMReplyException(
                "Uploading " + file.getName() + ": IO Error: " + ioe.getMessage(), ioe);
    }
    /*
        catch (it.sauronsoftware.ftp4j.FTPIllegalReplyException fire)
        {
            throw new FileTransferIllegalFSMReplyException("Uploading " + file.getName() + ": (FSM) Illegal FTP response: " + fire.getMessage(), fire);
        }
        catch (it.sauronsoftware.ftp4j.FTPException fe)
        {
            throw new FileTransferDataTransferException("Uploading " + file.getName() + ": (xFTE) Illegal FTP response: " + fe.getMessage(), fe);
        }
        catch (it.sauronsoftware.ftp4j.FTPDataTransferException fdte)
        {
            throw new FileTransferDataTransferException("Uploading " + file.getName() + ": (DTE) Illegal FTP response: " + fdte.getMessage(), fdte);
        }
        catch (it.sauronsoftware.ftp4j.FTPAbortedException fae)
        {
            throw new FileTransferDataTransferException("Uploading " + file.getName() + ": FTP aborted: " + fae.getMessage(), fae);
        }
    */
    finally {
        if (ssh.isConnected())
            try {
                ssh.disconnect();
            } catch (java.io.IOException ioe) {
                throw new FileTransferWinchException("tearing down ssh connection under exception", ioe);
            }
    }
}