Examples Of hz.ssh2.SCPClient

Home Package Class Method Package ch.ethz.ssh2

Examples of ch.ethz.ssh2.SCPClient

  • ch.ethz.ssh2.SCPClient A very basic SCPClient that can be used to copy files from/to the SSH-2 server. On the server side, the "scp" program must be in the PATH.

    This scp client is thread safe - you can download (and upload) different sets of files concurrently without any troubles. The SCPClient is actually mapping every request to a distinct {@link Session}. @author Christian Plattner, [email protected] @version $Id: SCPClient.java,v 1.11 2006/08/02 11:57:12 cplattne Exp $

21222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990        try     {       /* Create a connection instance */       Connection conn = new Connection(hostname);       /* We want to connect through a HTTP proxy */             conn.setProxyData(new HTTPProxyData(proxyHost, proxyPort));             // if the proxy requires basic authentication:       // conn.setProxyData(new HTTPProxyData(proxyHost, proxyPort, "username", "secret"));             /* Now connect (through the proxy) */       conn.connect();       /* Authenticate.        * If you get an IOException saying something like        * "Authentication method password not supported by the server at this stage."        * then please check the FAQ.        */       boolean isAuthenticated = conn.authenticateWithPassword(username, password);       if (isAuthenticated == false)         throw new IOException("Authentication failed.");       /* Create a session */       Session sess = conn.openSession();       sess.execCommand("uname -a && date && uptime && who");       System.out.println("Here is some information about the remote host:");       /*        * This basic example does not handle stderr, which is sometimes dangerous        * (please read the FAQ).        */       InputStream stdout = new StreamGobbler(sess.getStdout());       BufferedReader br = new BufferedReader(new InputStreamReader(stdout));       while (true)       {         String line = br.readLine();         if (line == null)           break;         System.out.println(line);       }       /* Show exit status, if available (otherwise "null") */       System.out.println("ExitCode: " + sess.getExitStatus());       /* Close this session */       sess.close();       /* Close the connection */       conn.close();     }     catch (IOException e)     {       e.printStackTrace(System.err);
View Full Code Here
15161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130     try     {       /* Create a connection instance */       Connection conn = new Connection(hostname);       /* Now connect */       conn.connect();       /* Authenticate */       boolean isAuthenticated = conn.authenticateWithPassword(username, password);       if (isAuthenticated == false)         throw new IOException("Authentication failed.");       /* Create a session */       Session sess = conn.openSession();       sess.execCommand("echo \"Huge amounts of text on STDOUT\"; echo \"Huge amounts of text on STDERR\" >&2");       /*        * Advanced:        * The following is a demo on how one can read from stdout and        * stderr without having to use two parallel worker threads (i.e.,        * we don't use the Streamgobblers here) and at the same time not        * risking a deadlock (due to a filled SSH2 channel window, caused        * by the stream which you are currently NOT reading from =).        */       /* Don't wrap these streams and don't let other threads work on        * these streams while you work with Session.waitForCondition()!!!        */       InputStream stdout = sess.getStdout();       InputStream stderr = sess.getStderr();       byte[] buffer = new byte[8192];       while (true)       {         if ((stdout.available() == 0) && (stderr.available() == 0))         {           /* Even though currently there is no data available, it may be that new data arrives            * and the session's underlying channel is closed before we call waitForCondition().            * This means that EOF and STDOUT_DATA (or STDERR_DATA, or both) may            * be set together.            */           int conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA               | ChannelCondition.EOF, 2000);           /* Wait no longer than 2 seconds (= 2000 milliseconds) */           if ((conditions & ChannelCondition.TIMEOUT) != 0)           {             /* A timeout occured. */             throw new IOException("Timeout while waiting for data from peer.");           }           /* Here we do not need to check separately for CLOSED, since CLOSED implies EOF */           if ((conditions & ChannelCondition.EOF) != 0)           {             /* The remote side won't send us further data... */             if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0)             {               /* ... and we have consumed all data in the local arrival window. */               break;             }           }           /* OK, either STDOUT_DATA or STDERR_DATA (or both) is set. */           // You can be paranoid and check that the library is not going nuts:           // if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0)           //  throw new IllegalStateException("Unexpected condition result (" + conditions + ")");         }         /* If you below replace "while" with "if", then the way the output appears on the local          * stdout and stder streams is more "balanced". Addtionally reducing the buffer size          * will also improve the interleaving, but performance will slightly suffer.          * OKOK, that all matters only if you get HUGE amounts of stdout and stderr data =)          */         while (stdout.available() > 0)         {           int len = stdout.read(buffer);           if (len > 0) // this check is somewhat paranoid             System.out.write(buffer, 0, len);         }         while (stderr.available() > 0)         {           int len = stderr.read(buffer);           if (len > 0) // this check is somewhat paranoid             System.err.write(buffer, 0, len);         }       }       /* Close this session */       sess.close();       /* Close the connection */       conn.close();     }     catch (IOException e)     {       e.printStackTrace(System.err);
View Full Code Here
518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689      this.username = username;     }     public void run()     {       Connection conn = new Connection(hostname);       try       {         /*          *          * CONNECT AND VERIFY SERVER HOST KEY (with callback)          *          */         String[] hostkeyAlgos = database.getPreferredServerHostkeyAlgorithmOrder(hostname);         if (hostkeyAlgos != null)           conn.setServerHostKeyAlgorithms(hostkeyAlgos);         conn.connect(new AdvancedVerifier());         /*          *          * AUTHENTICATION PHASE          *          */         boolean enableKeyboardInteractive = true;         boolean enableDSA = true;         boolean enableRSA = true;         String lastError = null;         while (true)         {           if ((enableDSA || enableRSA) && conn.isAuthMethodAvailable(username, "publickey"))           {             if (enableDSA)             {               File key = new File(idDSAPath);               if (key.exists())               {                 EnterSomethingDialog esd = new EnterSomethingDialog(loginFrame, "DSA Authentication",                     new String[] { lastError, "Enter DSA private key password:" }, true);                 esd.setVisible(true);                 boolean res = conn.authenticateWithPublicKey(username, key, esd.answer);                 if (res == true)                   break;                 lastError = "DSA authentication failed.";               }               enableDSA = false; // do not try again             }             if (enableRSA)             {               File key = new File(idRSAPath);               if (key.exists())               {                 EnterSomethingDialog esd = new EnterSomethingDialog(loginFrame, "RSA Authentication",                     new String[] { lastError, "Enter RSA private key password:" }, true);                 esd.setVisible(true);                 boolean res = conn.authenticateWithPublicKey(username, key, esd.answer);                 if (res == true)                   break;                 lastError = "RSA authentication failed.";               }               enableRSA = false; // do not try again             }             continue;           }           if (enableKeyboardInteractive && conn.isAuthMethodAvailable(username, "keyboard-interactive"))           {             InteractiveLogic il = new InteractiveLogic(lastError);             boolean res = conn.authenticateWithKeyboardInteractive(username, il);             if (res == true)               break;             if (il.getPromptCount() == 0)             {               // aha. the server announced that it supports "keyboard-interactive", but when               // we asked for it, it just denied the request without sending us any prompt.               // That happens with some server versions/configurations.               // We just disable the "keyboard-interactive" method and notify the user.               lastError = "Keyboard-interactive does not work.";               enableKeyboardInteractive = false; // do not try this again             }             else             {               lastError = "Keyboard-interactive auth failed."; // try again, if possible             }             continue;           }           if (conn.isAuthMethodAvailable(username, "password"))           {             final EnterSomethingDialog esd = new EnterSomethingDialog(loginFrame,                 "Password Authentication",                 new String[] { lastError, "Enter password for " + username }, true);             esd.setVisible(true);             if (esd.answer == null)               throw new IOException("Login aborted by user");             boolean res = conn.authenticateWithPassword(username, esd.answer);             if (res == true)               break;             lastError = "Password authentication failed."; // try again, if possible             continue;           }           throw new IOException("No supported authentication methods available.");         }         /*          *          * AUTHENTICATION OK. DO SOMETHING.          *          */         Session sess = conn.openSession();         int x_width = 90;         int y_width = 30;         sess.requestPTY("dumb", x_width, y_width, 0, 0, null);         sess.startShell();         TerminalDialog td = new TerminalDialog(loginFrame, username + "@" + hostname, sess, x_width, y_width);         /* The following call blocks until the dialog has been closed */         td.setVisible(true);       }       catch (IOException e)       {         //e.printStackTrace();         JOptionPane.showMessageDialog(loginFrame, "Exception: " + e.getMessage());       }       /*        *        * CLOSE THE CONNECTION.        *        */       conn.close();       /*        *        * CLOSE THE LOGIN FRAME - APPLICATION WILL BE EXITED (no more frames)        *  
View Full Code Here
27282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106     try     {       /* Create a connection instance */       Connection conn = new Connection(hostname);       /* Now connect */       conn.connect();       /* Authenticate */       boolean isAuthenticated = conn.authenticateWithPublicKey(username, keyfile, keyfilePass);       if (isAuthenticated == false)         throw new IOException("Authentication failed.");       /* ===== OK, now let's establish some local port forwardings ===== */             /* Example Port Forwarding: -L 8080:www.ethz.ch:80 (OpenSSH notation)        *        * This works by allocating a socket to listen on 8080 on the local interface (127.0.0.1).        * Whenever a connection is made to this port (127.0.0.1:8080), the connection is forwarded        * over the secure channel, and a connection is made to www.ethz.ch:80 from the remote        * machine (i.e., the ssh server).        *        * (the above text is based partially on the OpenSSH man page)        */       /* You can create as many of them as you want */             LocalPortForwarder lpf1 = conn.createLocalPortForwarder(8080, "www.ethz.ch", 80);             /* Now simply point your webbrowser to 127.0.0.1:8080 */       /* (on the host where you execute this program)                         */       /* ===== OK, now let's establish some remote port forwardings ===== */             /* Example Port Forwarding: -R 127.0.0.1:8080:www.ganymed.ethz.ch:80 (OpenSSH notation)        *        * Specifies that the port 127.0.0.1:8080 on the remote server is to be forwarded to the        * given host and port on the local side.  This works by allocating a socket to listen to port        * 8080 on the remote side (the ssh server), and whenever a connection is made to this port, the        * connection is forwarded over the secure channel, and a connection is made to        * www.ganymed.ethz.ch:80 by the Ganymed SSH-2 library.        *        * (the above text is based partially on the OpenSSH man page)        */       /* You can create as many of them as you want */             conn.requestRemotePortForwarding("127.0.0.1", 8080, "www.ganymed.ethz.ch", 80);       /* Now, on the ssh server, if you connect to 127.0.0.1:8080, then the connection is forwarded        * through the secure tunnel to the library, which in turn will forward the connection        * to www.ganymed.ethz.ch:80. */       /* Sleep a bit... (30 seconds) */       sleepSomeTime(30000);       /* Stop accepting remote connections that are being forwarded to www.ganymed.ethz.ch:80 */       conn.cancelRemotePortForwarding(8080);       /* Sleep a bit... (20 seconds) */       sleepSomeTime(20000);       /* Stop accepting connections on 127.0.0.1:8080 that are being forwarded to www.ethz.ch:80 */       lpf1.close();             /* Close the connection */       conn.close();     }     catch (IOException e)     {       e.printStackTrace(System.err);
View Full Code Here
171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879     try     {       /* Create a connection instance */       Connection conn = new Connection(hostname);       /* Now connect */       conn.connect();       /* Authenticate.        * If you get an IOException saying something like        * "Authentication method password not supported by the server at this stage."        * then please check the FAQ.        */       boolean isAuthenticated = conn.authenticateWithPassword(username, password);       if (isAuthenticated == false)         throw new IOException("Authentication failed.");       /* Create a session */       Session sess = conn.openSession();       sess.execCommand("uname -a && date && uptime && who");       System.out.println("Here is some information about the remote host:");       /*        * This basic example does not handle stderr, which is sometimes dangerous        * (please read the FAQ).        */       InputStream stdout = new StreamGobbler(sess.getStdout());       BufferedReader br = new BufferedReader(new InputStreamReader(stdout));       while (true)       {         String line = br.readLine();         if (line == null)           break;         System.out.println(line);       }       /* Show exit status, if available (otherwise "null") */       System.out.println("ExitCode: " + sess.getExitStatus());       /* Close this session */       sess.close();       /* Close the connection */       conn.close();     }     catch (IOException e)     {       e.printStackTrace(System.err);
View Full Code Here
1718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778     try     {       /* Create a connection instance */       Connection conn = new Connection(hostname);       /* Now connect */       conn.connect();       /* Authenticate */       boolean isAuthenticated = conn.authenticateWithPassword(username, password);       if (isAuthenticated == false)         throw new IOException("Authentication failed.");       /* Create a session */       Session sess = conn.openSession();       sess.execCommand("echo \"Text on STDOUT\"; echo \"Text on STDERR\" >&2");       InputStream stdout = new StreamGobbler(sess.getStdout());       InputStream stderr = new StreamGobbler(sess.getStderr());         BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdout));       BufferedReader stderrReader = new BufferedReader(new InputStreamReader(stderr));             System.out.println("Here is the output from stdout:");         while (true)       {         String line = stdoutReader.readLine();         if (line == null)           break;         System.out.println(line);       }             System.out.println("Here is the output from stderr:");             while (true)       {         String line = stderrReader.readLine();         if (line == null)           break;         System.out.println(line);       }             /* Close this session */             sess.close();       /* Close the connection */       conn.close();     }     catch (IOException e)     {       e.printStackTrace(System.err);
View Full Code Here
28293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576      if (knownHosts.exists())         database.addHostkeys(knownHosts);       /* Create a connection instance */       Connection conn = new Connection(hostname);       /* Now connect and use the SimpleVerifier */       conn.connect(new SimpleVerifier(database));       /* Authenticate */       boolean isAuthenticated = conn.authenticateWithPassword(username, password);       if (isAuthenticated == false)         throw new IOException("Authentication failed.");       /* Create a session */       Session sess = conn.openSession();       sess.execCommand("uname -a && date && uptime && who");       InputStream stdout = new StreamGobbler(sess.getStdout());       BufferedReader br = new BufferedReader(new InputStreamReader(stdout));       System.out.println("Here is some information about the remote host:");       while (true)       {         String line = br.readLine();         if (line == null)           break;         System.out.println(line);       }       /* Close this session */       sess.close();       /* Close the connection */       conn.close();     }     catch (IOException e)     {       e.printStackTrace(System.err);
View Full Code Here
2526272829303132333435       Connection conn = new Connection(hostname);       /* We want to connect through a HTTP proxy */             conn.setProxyData(new HTTPProxyData(proxyHost, proxyPort));             // if the proxy requires basic authentication:       // conn.setProxyData(new HTTPProxyData(proxyHost, proxyPort, "username", "secret"));             /* Now connect (through the proxy) */  
View Full Code Here
54555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102       * (the above text is based partially on the OpenSSH man page)        */       /* You can create as many of them as you want */             LocalPortForwarder lpf1 = conn.createLocalPortForwarder(8080, "www.ethz.ch", 80);             /* Now simply point your webbrowser to 127.0.0.1:8080 */       /* (on the host where you execute this program)                         */       /* ===== OK, now let's establish some remote port forwardings ===== */             /* Example Port Forwarding: -R 127.0.0.1:8080:www.ganymed.ethz.ch:80 (OpenSSH notation)        *        * Specifies that the port 127.0.0.1:8080 on the remote server is to be forwarded to the        * given host and port on the local side.  This works by allocating a socket to listen to port        * 8080 on the remote side (the ssh server), and whenever a connection is made to this port, the        * connection is forwarded over the secure channel, and a connection is made to        * www.ganymed.ethz.ch:80 by the Ganymed SSH-2 library.        *        * (the above text is based partially on the OpenSSH man page)        */       /* You can create as many of them as you want */             conn.requestRemotePortForwarding("127.0.0.1", 8080, "www.ganymed.ethz.ch", 80);       /* Now, on the ssh server, if you connect to 127.0.0.1:8080, then the connection is forwarded        * through the secure tunnel to the library, which in turn will forward the connection        * to www.ganymed.ethz.ch:80. */       /* Sleep a bit... (30 seconds) */       sleepSomeTime(30000);       /* Stop accepting remote connections that are being forwarded to www.ganymed.ethz.ch:80 */       conn.cancelRemotePortForwarding(8080);       /* Sleep a bit... (20 seconds) */       sleepSomeTime(20000);       /* Stop accepting connections on 127.0.0.1:8080 that are being forwarded to www.ethz.ch:80 */       lpf1.close();             /* Close the connection */       conn.close();  
View Full Code Here
432433434435436437438439440441442443444445446447448449450451452453454455456    public void testWithGanymede() throws Exception {         // begin client config         final Connection conn = new Connection("localhost", port);         conn.connect(null, 5000, 0);         conn.authenticateWithPassword("sshd", "sshd");         final SCPClient scp_client = new SCPClient(conn);         final Properties props = new Properties();         props.setProperty("test", "test-passed");         File f = new File("target/scp/gan");         Utils.deleteRecursive(f);         f.mkdirs();         assertTrue(f.exists());         String name = "test.properties";         scp_client.put(toBytes(props, ""), name, "target/scp/gan");         assertTrue(new File(f, name).exists());         assertTrue(new File(f, name).delete());         name = "test2.properties";         scp_client.put(toBytes(props, ""), name, "target/scp/gan");         assertTrue(new File(f, name).exists());         assertTrue(new File(f, name).delete());         assertTrue(f.delete());         conn.close();
View Full Code Here 0 1 2 3 4 5 6 7 8 9 TOP

Related Classes of ch.ethz.ssh2.SCPClient

  • Basic
  • BasicWithHTTPProxy
  • ch.ethz.ssh2.auth.AuthenticationManager
  • ch.ethz.ssh2.auth.ServerAuthenticationManager
  • ch.ethz.ssh2.channel.ChannelManager
  • ch.ethz.ssh2.channel.LocalAcceptThread
  • ch.ethz.ssh2.Connection
  • ch.ethz.ssh2.ConnectionInfo
  • ch.ethz.ssh2.crypto.cipher.BlockCipher
  • ch.ethz.ssh2.crypto.dh.DhExchange
  • Copyright © 2018 www.massapicom. All rights reserved. All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.

    Từ khóa » Ch.ethz.ssh2