Package com.jcraft.jsch

Examples of com.jcraft.jsch.Session


        if (isNotNullAndNonEmpty(knownHostsFile)) {
            log.debug("Using knownHosts: " + knownHostsFile);
            jsch.setKnownHosts(knownHostsFile);
        }
     
        final Session session = jsch.getSession(getConfiguration().getUsername(), getConfiguration().getHost(), getConfiguration().getPort());
        session.setUserInfo(new UserInfo() {
            public String getPassphrase() {
                return null;
            }

            public String getPassword() {
View Full Code Here


   * @return Returns the created session object representing the SSH session.
   * @throws JSchException
   */
  public Session createSession(int timeout) throws JSchException {
    if (tunnelHostName == null) {
      Session session =
          JSchUtilities.createJSch().getSession(userName, hostName, 22);
      session.setUserInfo(new SWTUserInfo() {
        @Override
        public String getPassword() {
          return HadoopServer.this.password;
        }

        @Override
        public void setPassword(String pass) {
          HadoopServer.this.password = pass;
        }

      });
      if (!session.isConnected()) {
        try {
          session.connect();
        } catch (JSchException jse) {
          // Reset password in case the authentication failed
          if (jse.getMessage().equals("Auth fail"))
            this.password = null;
          throw jse;
        }
      }

      return session;
    } else {
      createSshTunnel();

      Session session =
          JSchUtilities.createJSch().getSession(userName, "localhost",
              tunnelPort);
      session.setUserInfo(new SWTUserInfo() {
        @Override
        public String getPassword() {
          return HadoopServer.this.password;
        }

        @Override
        public void setPassword(String pass) {
          HadoopServer.this.password = pass;
        }
      });
      if (!session.isConnected()) {
        try {
          session.connect();
        } catch (JSchException jse) {
          // Reset password in case the authentication failed
          if (jse.getMessage().equals("Auth fail"))
            this.password = null;
          throw jse;
        }
      }
      if (timeout > -1) {
        session.setTimeout(timeout);
      }
      return session;
    }
  }
View Full Code Here

      return session;
    }
  }

  private Session createTunnel(int port) throws JSchException {
    Session tunnel;

    tunnelPort = -1;
    for (int i = 0; !((i > 4) || (tunnelPort > -1)); i++) {
      try {
        Socket socket = SocketFactory.getDefault().createSocket();
        socket.bind(null);
        tunnelPort = socket.getLocalPort();
        socket.close();
      } catch (IOException e) {
        // ignore, retry
      }
    }

    if (tunnelPort == -1) {
      throw new JSchException("No free local port found to bound to");
    }

    tunnel =
        JSchUtilities.createJSch().getSession(tunnelUserName,
            tunnelHostName, 22);
    tunnel.setTimeout(0);
    tunnel.setPortForwardingL(tunnelPort, hostName, port);

    tunnel.setUserInfo(new SWTUserInfo() {
      @Override
      public String getPassword() {
        return HadoopServer.this.tunnelPassword;
      }

      @Override
      public void setPassword(String password) {
        HadoopServer.this.tunnelPassword = password;
      }
    });

    try {
      tunnel.connect();
    } catch (JSchException jse) {
      // Reset password in case the authentication failed
      if (jse.getMessage().equals("Auth fail"))
        this.tunnelPassword = null;
      throw jse;
View Full Code Here

        hostname });

    HadoopServer server = ServerRegistry.getInstance().getServer(serverid);

    try {
      Session session = server.createSession();
      // session.setTimeout(TIMEOUT);

      log.log(Level.FINER, "Connected");

      /*
       * COMMENTED(jz) removing server start/stop support for now if (!
       * attributes.containsKey("hadoop.jar")) { // start or stop server if(
       * server.getServerState() == IServer.STATE_STARTING ) { String command =
       * dir + "bin/start-all.sh"; execInConsole(session, command); } else if(
       * server.getServerState() == IServer.STATE_STOPPING ) { String command =
       * dir + "bin/stop-all.sh"; execInConsole(session, command); } }
       */

      if (false) {
      } else {
        FileInputStream fis = null;
        String jarFile, remoteFile = null;

        if (attributes.containsKey("hadoop.jar")) {
          jarFile = (String) attributes.get("hadoop.jar");
        } else {
          String memento = (String) attributes.get("hadoop.jarrable");
          JarModule fromMemento = JarModule.fromMemento(memento);
          jarFile = fromMemento.buildJar(new SubProgressMonitor(monitor, 100))
              .toString();
        }

        if (jarFile.lastIndexOf('/') > 0) {
          remoteFile = jarFile.substring(jarFile.lastIndexOf('/') + 1);
        } else if (jarFile.lastIndexOf('\\') > 0) {
          remoteFile = jarFile.substring(jarFile.lastIndexOf('\\') + 1);
        }

        // exec 'scp -t -p hadoop.jar' remotely

        String command = "scp -p -t " + remoteFile;
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);

        // get I/O streams for remote scp
        OutputStream out = channel.getOutputStream();
        final InputStream in = channel.getInputStream();

        channel.connect();

        if (checkAck(in) != 0) {
          throw new CoreException(SSH_FAILED_STATUS1);
        }

        // send "C0644 filesize filename", where filename should not
        // include '/'
        long filesize = (new File(jarFile)).length();
        command = "C0644 " + filesize + " ";
        if (jarFile.lastIndexOf('/') > 0) {
          command += jarFile.substring(jarFile.lastIndexOf('/') + 1);
        } else {
          command += jarFile;
        }

        command += "\n";
        out.write(command.getBytes());
        out.flush();
        if (checkAck(in) != 0) {
          throw new CoreException(SSH_FAILED_STATUS2);
        }

        // send a content of jarFile
        fis = new FileInputStream(jarFile);
        byte[] buf = new byte[1024];
        while (true) {
          int len = fis.read(buf, 0, buf.length);
          if (len <= 0) {
            break;
          }
          out.write(buf, 0, len); // out.flush();
        }

        fis.close();
        fis = null;
        // send '\0'
        buf[0] = 0;
        out.write(buf, 0, 1);
        out.flush();
        if (checkAck(in) != 0) {
          throw new CoreException(SSH_FAILED_STATUS3);
        }
        out.close();
        channel.disconnect();

        // move the jar file to a temp directory
        String jarDir = "/tmp/hadoopjar"
            + new VMID().toString().replace(':', '_');
        command = "mkdir " + jarDir + ";mv " + remoteFile + " " + jarDir;
        channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        channel.connect();
        channel.disconnect();

        session.disconnect();

        // we create a new session with a zero timeout to prevent the
        // console stream
        // from stalling -- eyhung
        final Session session2 = server.createSessionNoTimeout();

        // now remotely execute hadoop with the just sent-over jarfile
        command = dir + "bin/hadoop jar " + jarDir + "/" + remoteFile;
        log.fine("Running command: " + command);
        execInConsole(session2, command, jarDir + "/" + remoteFile);
View Full Code Here

          if (job.isCompleted())
            return;

          try {
            Session session = server.createSession();

            String command =
                server.getInstallPath() + "/bin/hadoop job -kill " + jobId;
            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);
            channel.connect();
            channel.disconnect();

            session.disconnect();
          } catch (JSchException e) {
            e.printStackTrace();
          }
        }
      }
View Full Code Here

      try {
        dialog.run(true, false, new IRunnableWithProgress() {
          public void run(IProgressMonitor monitor)
              throws InvocationTargetException, InterruptedException {
            Session session = null;
            try {
              session = location.createSession();
              try {
                ChannelExec channel =
                    (ChannelExec) session.openChannel("exec");
                channel.setCommand(location.getInstallPath()
                    + "/bin/hadoop version");
                BufferedReader response =
                    new BufferedReader(new InputStreamReader(channel
                        .getInputStream()));
                channel.connect();
                final String versionLine = response.readLine();

                if ((versionLine != null)
                    && versionLine.startsWith("Hadoop")) {
                  Display.getDefault().syncExec(new Runnable() {
                    public void run() {
                      setMessage("Found " + versionLine,
                          IMessageProvider.INFORMATION);
                    }
                  });
                } else {
                  Display.getDefault().syncExec(new Runnable() {
                    public void run() {
                      setMessage("No Hadoop Found in this location",
                          IMessageProvider.WARNING);
                    }
                  });
                }
              } finally {
                session.disconnect();
                location.dispose();
              }
            } catch (final JSchException e) {
              Display.getDefault().syncExec(new Runnable() {
                public void run() {
                  System.err.println(e.getMessage());
                  setMessage("Problems connecting to server: "
                      + e.getLocalizedMessage(), IMessageProvider.WARNING);
                }
              });
            } catch (final IOException e) {
              Display.getDefault().syncExec(new Runnable() {
                public void run() {
                  setMessage("Problems communicating with server: "
                      + e.getLocalizedMessage(), IMessageProvider.WARNING);
                }
              });
            } catch (final Exception e) {
              Display.getDefault().syncExec(new Runnable() {
                public void run() {
                  setMessage("Errors encountered connecting to server: "
                      + e.getLocalizedMessage(), IMessageProvider.WARNING);
                }
              });
            } finally {
              if (session != null) {
                session.disconnect();
              }
            }
          }

        });
View Full Code Here

        String dir = args[3];

        Properties props = new Properties();
        props.setProperty("StrictHostKeyChecking", "false");
        JSch jsch = new JSch();
        Session session = jsch.getSession(user, host, 22);
        session.setUserInfo(new UserInfo()
        {
            public String getPassphrase()
            {
                return null;
            }

            public String getPassword()
            {
                return null;
            }

            public boolean promptPassword(String string)
            {
                return false;
            }

            public boolean promptPassphrase(String string)
            {
                return false;
            }

            public boolean promptYesNo(String string)
            {
                return true;
            }

            public void showMessage(String string)
            {
            }
        });
        session.setPassword(pass);
        session.connect();
        ChannelSftp chan = (ChannelSftp) session.openChannel("sftp");
        chan.connect();
        Vector list = chan.ls(dir);
        Iterator iterList = list.iterator();
        while (iterList.hasNext())
        {
            System.err.println(iterList.next());
        }
        System.err.println("done");
        chan.disconnect();
        session.disconnect();
    }
View Full Code Here

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 1000; i++) {
            sb.append(PAYLOAD_TMP);
        }
        final String PAYLOAD = sb.toString();
        Session session = createSession();
        final ServerSocket ss = new ServerSocket(0);
        int forwardedPort = ss.getLocalPort();
        int sinkPort = getFreePort();
        session.setPortForwardingL(sinkPort, "localhost", forwardedPort);
        final AtomicInteger conCount = new AtomicInteger(0);

        new Thread() {
            public void run() {
                try {
                    for (int i = 0; i < NUM_ITERATIONS; ++i) {
                        Socket s = ss.accept();
                        conCount.incrementAndGet();
                        InputStream is = s.getInputStream();
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        byte[] buf = new byte[8192];
                        int l;
                        while (baos.size() < PAYLOAD.length() && (l = is.read(buf)) > 0) {
                            baos.write(buf, 0, l);
                        }
                        if (!PAYLOAD.equals(baos.toString())) {
                            assertEquals(PAYLOAD, baos.toString());
                        }
                        is = new ByteArrayInputStream(baos.toByteArray());
                        OutputStream os = s.getOutputStream();
                        while ((l = is.read(buf)) > 0) {
                            os.write(buf, 0, l);
                        }
                        s.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
        Thread.sleep(50);

        for ( int i = 0; i < NUM_ITERATIONS; i++) {
            Socket s = null;
            try {
                LoggerFactory.getLogger(getClass()).info("Iteration {}", i);
                s = new Socket("localhost", sinkPort);
                s.getOutputStream().write(PAYLOAD.getBytes());
                s.getOutputStream().flush();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buf = new byte[8192];
                int l;
                while (baos.size() < PAYLOAD.length() && (l = s.getInputStream().read(buf)) > 0) {
                    baos.write(buf, 0, l);
                }
                assertEquals(PAYLOAD, baos.toString());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (s != null) {
                    s.close();
                }
            }
        }
        session.delPortForwardingL(sinkPort);
    }
View Full Code Here

                "longer Test Data. This is significantly longer Test Data. This is significantly "+
                "longer Test Data. This is significantly longer Test Data. This is significantly "+
                "longer Test Data. This is significantly longer Test Data. This is significantly "+
                "longer Test Data. This is significantly longer Test Data. This is significantly "+
                "longer Test Data. ";
        Session session = createSession();
        final ServerSocket ss = new ServerSocket(0);
        int forwardedPort = ss.getLocalPort();
        int sinkPort = getFreePort();
        session.setPortForwardingR(sinkPort, "localhost", forwardedPort);
        final boolean started[] = new boolean[1];
        started[0] = false;
        final AtomicInteger conCount = new AtomicInteger(0);

        new Thread() {
            public void run() {
                started[0] = true;
                try {
                    for (int i = 0; i < NUM_ITERATIONS; ++i) {
                        Socket s = ss.accept();
                        conCount.incrementAndGet();
                        s.getOutputStream().write(PAYLOAD.getBytes());
                        s.getOutputStream().flush();
                        s.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
        Thread.sleep(50);
        Assert.assertTrue("Server not started", started[0]);

        final boolean lenOK[] = new boolean[NUM_ITERATIONS];
        final boolean dataOK[] = new boolean[NUM_ITERATIONS];
        for ( int i = 0; i < NUM_ITERATIONS; i++) {
            final int ii = i;
            Socket s = null;
            try {
                s = new Socket("localhost", sinkPort);
                byte b1[] = new byte[PAYLOAD.length() / 2];
                byte b2[] = new byte[PAYLOAD.length()];
                int read1 = s.getInputStream().read(b1);
                Thread.sleep(50);
                int read2 = s.getInputStream().read(b2);
                lenOK[ii] = PAYLOAD.length() == read1 + read2;
                dataOK[ii] = PAYLOAD.equals(new String(b1, 0, read1) + new String(b2, 0, read2));
                if (!lenOK[ii] || !dataOK[ii] ) {
                    throw new Exception("Bad data");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (s != null) {
                    s.close();
                }
            }
        }
        int ok = 0;
        for (int i = 0; i < NUM_ITERATIONS; i++) {
            ok += lenOK[i] ? 1 : 0;
        }
        Thread.sleep(50);
        for (int i = 0; i < NUM_ITERATIONS; i++) {
            Assert.assertTrue(lenOK[i]);
            Assert.assertTrue(dataOK[i]);
        }
        session.delPortForwardingR(forwardedPort);
    }
View Full Code Here

        });
        acceptor.setReuseAddress(true);
        acceptor.bind(new InetSocketAddress(port));


        Session session = createSession();

        final int forwardedPort1 = getFreePort();
        final int forwardedPort2 = getFreePort();
        System.err.println("URL: http://localhost:" + forwardedPort2);

        session.setPortForwardingL(forwardedPort1, host, port);
        session.setPortForwardingR(forwardedPort2, "localhost", forwardedPort1);


        final CountDownLatch latch = new CountDownLatch(nbThread * nbDownloads * nbLoops);

        final Thread[] threads = new Thread[nbThread];
View Full Code Here

TOP

Related Classes of com.jcraft.jsch.Session

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.