@Override
  public void afterPropertiesSet() {
    jsch = new JSch();
    if (!isConnected) {
      if (null == session || !session.isConnected()) {
        try {
          session = jsch.getSession(sshUsername, host, port);
          session.setPassword(sshPassword);

          java.util.Properties config = new java.util.Properties();
          config.put("StrictHostKeyChecking", "no");
          session.setConfig(config);

          log.info("Открытие ssh соединения");
          session.connect();
          log.info("Tunnel status: " + session.isConnected());
          log.info("Устанавливаем туннель");
          session.setPortForwardingL(tunnelLocalPort, tunnelRemoteHost, tunnelRemotePort);
        } catch (Exception e) {
          log.error("Ошибка при построении соединения", e);
          System.exit(1);
        }
      }
      isConnected = true;
    }
  }
Ejemplo n.º 2
0
 @Override
 public void clear() {
   if (session != null && session.isConnected()) {
     session.disconnect();
     session = null;
   }
 }
 @Test
 public void testCreateClientFailsIfPwdReturnsRelativePath() throws Exception {
   final String remoteRoot = "some/directory/in/my/home/dir";
   hostConfig = createWithOverrideUsernameAndPassword(mockJSch);
   getHostConfig().setRemoteRootDir(remoteRoot);
   final BapSshCommonConfiguration commonConfiguration =
       new BapSshCommonConfiguration("Ignore me", null, null, false);
   getHostConfig().setCommonConfig(commonConfiguration);
   expect(
           mockJSch.getSession(
               getHostConfig().getUsername(),
               getHostConfig().getHostname(),
               getHostConfig().getPort()))
       .andReturn(mockSession);
   mockSession.setPassword(TEST_PASSPHRASE);
   mockSession.setConfig((Properties) anyObject());
   mockSession.connect(getHostConfig().getTimeout());
   expect(mockSession.openChannel("sftp")).andReturn(mockSftp);
   mockSftp.connect(getHostConfig().getTimeout());
   testHelper.expectDirectoryCheck(getHostConfig().getRemoteRootDir(), true);
   mockSftp.cd(getHostConfig().getRemoteRootDir());
   expect(mockSftp.pwd()).andReturn("home/bap/" + remoteRoot);
   expect(mockSftp.isConnected()).andReturn(false);
   expect(mockSession.isConnected()).andReturn(false);
   assertCreateClientThrowsException("home/bap/" + remoteRoot);
 }
Ejemplo n.º 4
0
  protected void connectSession() throws JSchException {
    if (session != null) {
      if (session.isConnected()) {
        session.disconnect();
      }
      session = null;
    }

    AutomationLogger.getInstance().info("Connectting...");

    if (StringUtil.notEmpty(user)) {
      session = jsch.getSession(user, host, 22);
      session.setPassword(password);
    } else if (auth != null) {
      session = auth.getSession(host);
    } else {
      throw new ItemNotFoundException("Authentication is missing!");
    }

    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.connect();
    AutomationLogger.getInstance().info("Connected");
  }
Ejemplo n.º 5
0
 @PreDestroy
 public void disconnect() {
   if (session != null && session.isConnected()) {
     session.disconnect();
     session = null;
   }
 }
Ejemplo n.º 6
0
  /**
   * This will execute the given command with given session and session is not closed at the end.
   *
   * @param commandInfo
   * @param session
   * @param commandOutput
   * @throws SSHApiException
   */
  public static Session executeCommand(
      CommandInfo commandInfo, Session session, CommandOutput commandOutput)
      throws SSHApiException {

    String command = commandInfo.getCommand();

    Channel channel = null;
    try {
      if (!session.isConnected()) {
        session.connect();
      }
      channel = session.openChannel("exec");
      ((ChannelExec) channel).setCommand(command);
    } catch (JSchException e) {
      session.disconnect();

      throw new SSHApiException("Unable to execute command - ", e);
    }

    channel.setInputStream(null);
    ((ChannelExec) channel).setErrStream(commandOutput.getStandardError());
    try {
      channel.connect();
    } catch (JSchException e) {

      channel.disconnect();
      session.disconnect();
      throw new SSHApiException("Unable to retrieve command output. Command - " + command, e);
    }

    commandOutput.onOutput(channel);
    // Only disconnecting the channel, session can be reused
    channel.disconnect();
    return session;
  }
Ejemplo n.º 7
0
 public boolean isLoggedIn() {
   return isConnected()
       && session != null
       && session.isConnected()
       && channel != null
       && channel.isConnected();
 }
Ejemplo n.º 8
0
  /**
   * Execute the command on the remote host.
   *
   * @param command - what to execute on the remote host.
   * @return return code of the process.
   * @throws BuildException bad parameter.
   * @throws JSchException if there's an underlying problem exposed in SSH
   * @throws IOException if there's a problem attaching streams.
   * @throws TimeoutException if we exceeded our timeout
   */
  public int execute(String command)
      throws BuildException, JSchException, IOException, TimeoutException {
    if (command == null) {
      throw new BuildException("Command is required.");
    }
    if (host == null) {
      throw new BuildException("Host is required.");
    }
    if (userInfo.getName() == null) {
      throw new BuildException("Username is required.");
    }
    if (userInfo.getKeyfile() == null && userInfo.getPassword() == null) {
      throw new BuildException("Password or Keyfile is required.");
    }

    Session session = null;
    try {
      session = openSession();
      return executeCommand(session, command);
    } finally {
      if (session != null && session.isConnected()) {
        session.disconnect();
      }
    }
  }
  /**
   * Determines whether a vaild session exists for the contact of remote machine.
   *
   * @param sshContact ID of SSH Contact
   * @return <tt>true</tt> if the session is connected <tt>false</tt> otherwise
   */
  public boolean isSessionValid(ContactSSH sshContact) {
    Session sshSession = sshContact.getSSHSession();
    if (sshSession != null) if (sshSession.isConnected()) return true;

    // remove reference to an unconnected SSH Session, if any
    sshContact.setSSHSession(null);
    return false;
  }
Ejemplo n.º 10
0
 public void disconnect() throws GenericFileOperationFailedException {
   if (session != null && session.isConnected()) {
     session.disconnect();
   }
   if (channel != null && channel.isConnected()) {
     channel.disconnect();
   }
 }
Ejemplo n.º 11
0
  @Override
  protected Integer doInBackground(String... arg0) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    Thread.currentThread().setName("SSHConnectionThread");
    try {

      JSch jsch = new JSch();
      session = jsch.getSession(arg0[1], arg0[0], 22);
      session.setPassword(arg0[2].getBytes());
      session.setConfig("StrictHostKeyChecking", "no");
      session.connect(timeout);
      System.out.println("connesso? " + session.isConnected());
      int assinged_port = session.setPortForwardingL(lhost, lport, rhost, rport);
      session.setPortForwardingL(lhost, 9001, rhost, 502);
      System.out.println("localhost:" + assinged_port + " -> " + rhost + ":" + rport);
      ConnectionManager.setSession(session);

    } catch (Exception e) {
      //			System.out.println(e.getLocalizedMessage());
      //			String errore = "";
      //			if(e instanceof JSchException) errore = "Errore SSH ";
      //			else if(e instanceof UnknownHostException) errore = "Ricontrolla il dominio o la
      // connessione internet, cè qualcosa di errato, attento agli spazi e maiscole";
      //			else if(e instanceof ConnectException) errore = "Ricontrolla i campi o la connessione cè
      // qualcosa che non va, attento agli spazi e maiscole";
      //			else errore = "Ricontrolla user, password e dominio, cè qualcosa di errato, attento agli
      // spazi e maiscole";
      //			if(isDialogActivated()){
      //				AlertMessageTask errorConnection = new AlertMessageTask();
      //				errorConnection.setActivity(getActivity());
      //				errorConnection.execute(errore);
      //			}
      if (fireEvent && !e.getLocalizedMessage().contains("PortForwardingL:")) {
        System.out.println("non è portforwarding ma " + e.getLocalizedMessage());
        if (MainActivity.handle == null) return null;
        Message msgObj = MainActivity.handle.obtainMessage();
        Bundle ba = new Bundle();
        ba.putInt("status", 0);
        msgObj.setData(ba);
        MainActivity.handle.sendMessage(msgObj);
        fireEvent = false;
      }
      return null;
    }
    if (fireEvent) {
      if (MainActivity.handle == null) return null;
      Message msgObj = MainActivity.handle.obtainMessage();
      Bundle ba = new Bundle();
      ba.putInt("status", 1);
      msgObj.setData(ba);
      MainActivity.handle.sendMessage(msgObj);
      fireEvent = false;
    }
    return null;
  };
Ejemplo n.º 12
0
 public static Session getSession() {
   if (session != null && session.isConnected()) return session;
   else {
     sshConnection = new SSHConnection();
     if (context != null) sshConnection.setSessionContext(session, context);
     else sshConnection.setSession(session);
     sshConnection.execute(host, user, passw);
     return session;
   }
 }
Ejemplo n.º 13
0
 @Override
 public void start() throws MachineException {
   try {
     session = jsch.getSession(username, host, port);
     session.setUserInfo(user);
     // todo remember parent pid of shell to be able to kill all processes on client stop
     if (!session.isConnected()) {
       session.connect(connectionTimeout);
     }
   } catch (JSchException e) {
     throw new MachineException(
         "Ssh machine creation failed because ssh of machine is inaccessible. Error: "
             + e.getLocalizedMessage());
   }
 }
 @Test
 public void testFailToConnect() throws Exception {
   hostConfig = createWithOverrideUsernameAndPassword(mockJSch);
   getHostConfig().setCommonConfig(new BapSshCommonConfiguration("", "", "", false));
   expect(
           mockJSch.getSession(
               getHostConfig().getUsername(),
               getHostConfig().getHostname(),
               getHostConfig().getPort()))
       .andReturn(mockSession);
   mockSession.setPassword(TEST_PASSPHRASE);
   mockSession.setConfig((Properties) anyObject());
   final JSchException exception = new JSchException("meh");
   mockSession.connect(getHostConfig().getTimeout());
   expectLastCall().andThrow(exception);
   expect(mockSession.isConnected()).andReturn(false);
   assertCreateClientThrowsException(exception);
 }
Ejemplo n.º 15
0
  public String Conecta(String host, String command)
      throws JSchException, IOException, InterruptedException {

    ConstantesUsers constantes = new ConstantesUsers();

    JSch jsch = new JSch();
    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    Session session = jsch.getSession(constantes.getUser(), host, constantes.getPort());
    session.setPassword(constantes.getPassword());
    session.setConfig(config);
    String saida = null;
    if (!session.isConnected()) {
      session.connect();
      //			System.out.println("Conectado");
      Channel channel = session.openChannel("exec");
      ((ChannelExec) channel).setCommand(command);
      InputStream in = channel.getInputStream();
      channel.connect();
      byte[] tmp = new byte[1024];
      while (true) {
        while (in.available() > 0) {
          int i = in.read(tmp, 0, 1024);
          if (i < 0) break;
          //		          System.out.print(new String(tmp, 0, i));
          saida = new String(tmp, 0, i);
        }
        if (channel.isClosed()) {
          channel.disconnect();
          break;
        }
      }

      channel.disconnect();
      session.disconnect();
    } else {
      System.out.println("Conexao já estabelecida");
    }
    return saida;
  }
Ejemplo n.º 16
0
 public boolean isConnected() {
   if (session == null) {
     return false;
   }
   return session.isConnected();
 }
 private void expectDisconnect() throws Exception {
   expect(mockSftp.isConnected()).andReturn(false);
   expect(mockSession.isConnected()).andReturn(false);
 }
Ejemplo n.º 18
0
 private boolean isClosed() {
   if (session != null) {
     return !session.isConnected();
   }
   return true;
 }
  /**
   * Creates a SSH Session with a remote machine and tries to login according to the details
   * specified by Contact An appropriate message is shown to the end user in case the login fails
   *
   * @param sshContact ID of SSH Contact
   * @throws JSchException if a JSch is unable to create a SSH Session with the remote machine
   * @throws InterruptedException if the thread is interrupted before session connected or is timed
   *     out
   * @throws OperationFailedException if not of above reasons :-)
   */
  public void createSSHSessionAndLogin(ContactSSH sshContact)
      throws JSchException, OperationFailedException, InterruptedException {
    logger.info("Creating a new SSH Session to " + sshContact.getHostName());

    // creating a new JSch Stack identifier for contact
    JSch jsch = new JSch();

    String knownHosts = (String) accountID.getAccountProperties().get("KNOWN_HOSTS_FILE");

    if (!knownHosts.equals("Optional")) jsch.setKnownHosts(knownHosts);

    String identitiyKey = (String) accountID.getAccountProperties().get("IDENTITY_FILE");

    String userName = sshContact.getUserName();

    // use the name of system user if the contact has not supplied SSH
    // details
    if (userName.equals("")) userName = System.getProperty("user.name");

    if (!identitiyKey.equals("Optional")) jsch.addIdentity(identitiyKey);

    // creating a new session for the contact
    Session session =
        jsch.getSession(
            userName, sshContact.getHostName(), sshContact.getSSHConfigurationForm().getPort());

    /**
     * Creating and associating User Info with the session User Info passes authentication from
     * sshContact to SSH Stack
     */
    SSHUserInfo sshUserInfo = new SSHUserInfo(sshContact);

    session.setUserInfo(sshUserInfo);

    /** initializing the session */
    session.connect(connectionTimeout);

    int count = 0;

    // wait for session to get connected
    while (!session.isConnected() && count <= 30000) {
      Thread.sleep(1000);
      count += 1000;
      logger.trace("SSH:" + sshContact.getHostName() + ": Sleep zzz .. ");
    }

    // if timeout have exceeded
    if (count > 30000) {
      sshContact.setSSHSession(null);
      JOptionPane.showMessageDialog(
          null, "SSH Connection attempt to " + sshContact.getHostName() + " timed out");

      // error codes are not defined yet
      throw new OperationFailedException(
          "SSH Connection attempt to " + sshContact.getHostName() + " timed out", 2);
    }

    sshContact.setJSch(jsch);
    sshContact.setSSHSession(session);

    logger.info("A new SSH Session to " + sshContact.getHostName() + " Created");
  }
Ejemplo n.º 20
0
 private void checkConnected() {
   checkState(
       session != null && session.isConnected(),
       String.format("%s@%s:%d: SFTP not connected!", username, host, port));
 }
Ejemplo n.º 21
0
  public boolean connect(RemoteFileConfiguration configuration)
      throws GenericFileOperationFailedException {
    if (isConnected()) {
      // already connected
      return true;
    }

    boolean connected = false;
    int attempt = 0;

    while (!connected) {
      try {
        if (LOG.isTraceEnabled() && attempt > 0) {
          LOG.trace(
              "Reconnect attempt #{} connecting to + {}",
              attempt,
              configuration.remoteServerInformation());
        }

        if (channel == null || !channel.isConnected()) {
          if (session == null || !session.isConnected()) {
            LOG.trace("Session isn't connected, trying to recreate and connect.");
            session = createSession(configuration);
            if (endpoint.getConfiguration().getConnectTimeout() > 0) {
              LOG.trace(
                  "Connecting use connectTimeout: "
                      + endpoint.getConfiguration().getConnectTimeout()
                      + " ...");
              session.connect(endpoint.getConfiguration().getConnectTimeout());
            } else {
              LOG.trace("Connecting ...");
              session.connect();
            }
          }

          LOG.trace("Channel isn't connected, trying to recreate and connect.");
          channel = (ChannelSftp) session.openChannel("sftp");

          if (endpoint.getConfiguration().getConnectTimeout() > 0) {
            LOG.trace(
                "Connecting use connectTimeout: "
                    + endpoint.getConfiguration().getConnectTimeout()
                    + " ...");
            channel.connect(endpoint.getConfiguration().getConnectTimeout());
          } else {
            LOG.trace("Connecting ...");
            channel.connect();
          }
          LOG.info("Connected to " + configuration.remoteServerInformation());
        }

        // yes we could connect
        connected = true;
      } catch (Exception e) {
        // check if we are interrupted so we can break out
        if (Thread.currentThread().isInterrupted()) {
          throw new GenericFileOperationFailedException(
              "Interrupted during connecting",
              new InterruptedException("Interrupted during connecting"));
        }

        GenericFileOperationFailedException failed =
            new GenericFileOperationFailedException(
                "Cannot connect to " + configuration.remoteServerInformation(), e);
        LOG.trace("Cannot connect due: {}", failed.getMessage());
        attempt++;
        if (attempt > endpoint.getMaximumReconnectAttempts()) {
          throw failed;
        }
        if (endpoint.getReconnectDelay() > 0) {
          try {
            Thread.sleep(endpoint.getReconnectDelay());
          } catch (InterruptedException ie) {
            // we could potentially also be interrupted during sleep
            Thread.currentThread().interrupt();
            throw new GenericFileOperationFailedException("Interrupted during sleeping", ie);
          }
        }
      }
    }

    return true;
  }
  /** {@inheritDoc} */
  @Override
  public ClusterStartNodeResult call() {
    JSch ssh = new JSch();

    Session ses = null;

    try {
      if (spec.key() != null) ssh.addIdentity(spec.key().getAbsolutePath());

      ses = ssh.getSession(spec.username(), spec.host(), spec.port());

      if (spec.password() != null) ses.setPassword(spec.password());

      ses.setConfig("StrictHostKeyChecking", "no");

      ses.connect(timeout);

      boolean win = isWindows(ses);

      char separator = win ? '\\' : '/';

      spec.fixPaths(separator);

      String igniteHome = spec.igniteHome();

      if (igniteHome == null) igniteHome = win ? DFLT_IGNITE_HOME_WIN : DFLT_IGNITE_HOME_LINUX;

      String script = spec.script();

      if (script == null) script = DFLT_SCRIPT_LINUX;

      String cfg = spec.configuration();

      if (cfg == null) cfg = "";

      String startNodeCmd;
      String scriptOutputFileName =
          FILE_NAME_DATE_FORMAT.format(new Date())
              + '-'
              + UUID.randomUUID().toString().substring(0, 8)
              + ".log";

      if (win)
        throw new UnsupportedOperationException(
            "Apache Ignite cannot be auto-started on Windows from IgniteCluster.startNodes(…) API.");
      else { // Assume Unix.
        int spaceIdx = script.indexOf(' ');

        String scriptPath = spaceIdx > -1 ? script.substring(0, spaceIdx) : script;
        String scriptArgs = spaceIdx > -1 ? script.substring(spaceIdx + 1) : "";
        String rmtLogArgs = buildRemoteLogArguments(spec.username(), spec.host());
        String tmpDir = env(ses, "$TMPDIR", "/tmp/");
        String scriptOutputDir = tmpDir + "ignite-startNodes";

        shell(ses, "mkdir " + scriptOutputDir);

        // Mac os don't support ~ in double quotes. Trying get home path from remote system.
        if (igniteHome.startsWith("~")) {
          String homeDir = env(ses, "$HOME", "~");

          igniteHome = igniteHome.replaceFirst("~", homeDir);
        }

        startNodeCmd =
            new SB()
                .
                // Console output is consumed, started nodes must use Ignite file appenders for log.
                a("nohup ")
                .a("\"")
                .a(igniteHome)
                .a('/')
                .a(scriptPath)
                .a("\"")
                .a(" ")
                .a(scriptArgs)
                .a(!cfg.isEmpty() ? " \"" : "")
                .a(cfg)
                .a(!cfg.isEmpty() ? "\"" : "")
                .a(rmtLogArgs)
                .a(" > ")
                .a(scriptOutputDir)
                .a("/")
                .a(scriptOutputFileName)
                .a(" 2>& 1 &")
                .toString();
      }

      info("Starting remote node with SSH command: " + startNodeCmd, spec.logger(), log);

      shell(ses, startNodeCmd);

      return new ClusterStartNodeResultImpl(spec.host(), true, null);
    } catch (IgniteInterruptedCheckedException e) {
      return new ClusterStartNodeResultImpl(spec.host(), false, e.getMessage());
    } catch (Exception e) {
      return new ClusterStartNodeResultImpl(spec.host(), false, X.getFullStackTrace(e));
    } finally {
      if (ses != null && ses.isConnected()) ses.disconnect();
    }
  }
Ejemplo n.º 23
0
 public boolean isConnected() throws GenericFileOperationFailedException {
   return session != null && session.isConnected() && channel != null && channel.isConnected();
 }
Ejemplo n.º 24
0
 public static void stop() {
   if (session.isConnected()) session.disconnect();
 }
Ejemplo n.º 25
0
 public static boolean isConnected() {
   if (session != null && session.isConnected()) return true;
   else return false;
 }
Ejemplo n.º 26
0
 public boolean isConnected() {
   return session.isConnected();
 }
Ejemplo n.º 27
-1
  /**
   * Retrieves the session for the specified Job.
   *
   * @param job
   * @return
   * @throws PortalServiceException
   */
  public Session getSession(CloudFileOwner job) throws PortalServiceException {
    try {
      JSch jsch = new JSch();
      String prvkey = job.getProperty(NCIDetails.PROPERTY_NCI_KEY);
      jsch.addIdentity(new IdentityString(jsch, prvkey), null);
      String userName = job.getProperty(NCIDetails.PROPERTY_NCI_USER);
      Session session = jsch.getSession(userName, endPoint, 22);
      session.setConfig("StrictHostKeyChecking", "no");
      if (!session.isConnected()) {
        session.connect();
      }

      return session;
    } catch (JSchException ex) {
      logger.error("Unable to retrieve SSH session for job " + job.getId() + ":" + ex.getMessage());
      logger.debug("Exception:", ex);
      throw new PortalServiceException("Unable to retrieve SSH session for job " + job.getId(), ex);
    }
  }