Пример #1
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");
  }
Пример #2
0
 /**
  * 连接到指定的IP
  *
  * @throws JSchException
  */
 public void connect() throws JSchException {
   jsch = new JSch();
   session = jsch.getSession(user, host, 22);
   session.setPassword(passwd);
   java.util.Properties config = new java.util.Properties();
   config.put("StrictHostKeyChecking", "no");
   session.setConfig(config);
   session.connect();
 }
 public void login(String username, String password) throws JSchException {
   session = jSch.getSession(username, ip, port);
   session.setPassword(password);
   //// FIXME: 03/04/2016 Security
   session.setConfig("StrictHostKeyChecking", "no");
   session.connect();
   channel = (ChannelSftp) session.openChannel("sftp");
   channel.connect();
 }
Пример #4
0
 public Session getSession(String host, Integer port, String user, Boolean hostKeyChecking)
     throws JSchException {
   if (this.session != null) return this.session;
   this.setHost(host);
   this.setUser(user);
   this.session = jsch.getSession(user, host, port);
   java.util.Properties config = new java.util.Properties();
   if (hostKeyChecking) {
     log.info("strict host key checking enabled");
     config.put("StrictHostKeyChecking", "yes");
   } else {
     log.info("strict host key checking disabled");
     config.put("StrictHostKeyChecking", "no");
   }
   session.setConfig(config);
   return session;
 }
Пример #5
0
  /**
   * This will not reuse any session, it will create the session and close it at the end
   *
   * @param commandInfo Encapsulated information about command. E.g :- executable name parameters
   *     etc ...
   * @param serverInfo The SSHing server information.
   * @param authenticationInfo Security data needs to be communicated with remote server.
   * @param commandOutput The output of the command.
   * @param configReader configuration required for ssh/gshissh connection
   * @throws SSHApiException throw exception when error occurs
   */
  public static void executeCommand(
      CommandInfo commandInfo,
      ServerInfo serverInfo,
      AuthenticationInfo authenticationInfo,
      CommandOutput commandOutput,
      ConfigReader configReader)
      throws SSHApiException {

    if (authenticationInfo instanceof GSIAuthenticationInfo) {
      System.setProperty(
          X509_CERT_DIR,
          (String)
              ((GSIAuthenticationInfo) authenticationInfo).getProperties().get("X509_CERT_DIR"));
    }

    JSch jsch = new ExtendedJSch();

    log.debug(
        "Connecting to server - "
            + serverInfo.getHost()
            + ":"
            + serverInfo.getPort()
            + " with user name - "
            + serverInfo.getUserName());

    Session session;

    try {
      session =
          jsch.getSession(serverInfo.getUserName(), serverInfo.getHost(), serverInfo.getPort());
    } catch (JSchException e) {
      throw new SSHApiException(
          "An exception occurred while creating SSH session."
              + "Connecting server - "
              + serverInfo.getHost()
              + ":"
              + serverInfo.getPort()
              + " connecting user name - "
              + serverInfo.getUserName(),
          e);
    }

    java.util.Properties config = configReader.getProperties();
    session.setConfig(config);

    // =============================================================
    // Handling vanilla SSH pieces
    // =============================================================
    if (authenticationInfo instanceof SSHPasswordAuthentication) {
      String password =
          ((SSHPasswordAuthentication) authenticationInfo)
              .getPassword(serverInfo.getUserName(), serverInfo.getHost());

      session.setUserInfo(new SSHAPIUIKeyboardInteractive(password));

      // TODO figure out why we need to set password to session
      session.setPassword(password);

    } else if (authenticationInfo instanceof SSHPublicKeyFileAuthentication) {
      SSHPublicKeyFileAuthentication sshPublicKeyFileAuthentication =
          (SSHPublicKeyFileAuthentication) authenticationInfo;

      String privateKeyFile =
          sshPublicKeyFileAuthentication.getPrivateKeyFile(
              serverInfo.getUserName(), serverInfo.getHost());

      logDebug("The private key file for vanilla SSH " + privateKeyFile);

      String publicKeyFile =
          sshPublicKeyFileAuthentication.getPrivateKeyFile(
              serverInfo.getUserName(), serverInfo.getHost());

      logDebug("The public key file for vanilla SSH " + publicKeyFile);

      Identity identityFile;

      try {
        identityFile = GSISSHIdentityFile.newInstance(privateKeyFile, null, jsch);
      } catch (JSchException e) {
        throw new SSHApiException(
            "An exception occurred while initializing keys using files. "
                + "(private key and public key)."
                + "Connecting server - "
                + serverInfo.getHost()
                + ":"
                + serverInfo.getPort()
                + " connecting user name - "
                + serverInfo.getUserName()
                + " private key file - "
                + privateKeyFile
                + ", public key file - "
                + publicKeyFile,
            e);
      }

      // Add identity to identity repository
      GSISSHIdentityRepository identityRepository = new GSISSHIdentityRepository(jsch);
      identityRepository.add(identityFile);

      // Set repository to session
      session.setIdentityRepository(identityRepository);

      // Set the user info
      SSHKeyPasswordHandler sshKeyPasswordHandler =
          new SSHKeyPasswordHandler((SSHKeyAuthentication) authenticationInfo);

      session.setUserInfo(sshKeyPasswordHandler);

    } else if (authenticationInfo instanceof SSHPublicKeyAuthentication) {

      SSHPublicKeyAuthentication sshPublicKeyAuthentication =
          (SSHPublicKeyAuthentication) authenticationInfo;

      Identity identityFile;

      try {
        String name = serverInfo.getUserName() + "_" + serverInfo.getHost();
        identityFile =
            GSISSHIdentityFile.newInstance(
                name,
                sshPublicKeyAuthentication.getPrivateKey(
                    serverInfo.getUserName(), serverInfo.getHost()),
                sshPublicKeyAuthentication.getPublicKey(
                    serverInfo.getUserName(), serverInfo.getHost()),
                jsch);
      } catch (JSchException e) {
        throw new SSHApiException(
            "An exception occurred while initializing keys using byte arrays. "
                + "(private key and public key)."
                + "Connecting server - "
                + serverInfo.getHost()
                + ":"
                + serverInfo.getPort()
                + " connecting user name - "
                + serverInfo.getUserName(),
            e);
      }

      // Add identity to identity repository
      GSISSHIdentityRepository identityRepository = new GSISSHIdentityRepository(jsch);
      identityRepository.add(identityFile);

      // Set repository to session
      session.setIdentityRepository(identityRepository);

      // Set the user info
      SSHKeyPasswordHandler sshKeyPasswordHandler =
          new SSHKeyPasswordHandler((SSHKeyAuthentication) authenticationInfo);

      session.setUserInfo(sshKeyPasswordHandler);
    }

    // Not a good way, but we dont have any choice
    if (session instanceof ExtendedSession) {
      if (authenticationInfo instanceof GSIAuthenticationInfo) {
        ((ExtendedSession) session)
            .setAuthenticationInfo((GSIAuthenticationInfo) authenticationInfo);
      }
    }

    try {
      session.connect();
    } catch (JSchException e) {
      throw new SSHApiException(
          "An exception occurred while connecting to server."
              + "Connecting server - "
              + serverInfo.getHost()
              + ":"
              + serverInfo.getPort()
              + " connecting user name - "
              + serverInfo.getUserName(),
          e);
    }

    String command = commandInfo.getCommand();

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

      throw new SSHApiException(
          "Unable to execute command - "
              + command
              + " on server - "
              + serverInfo.getHost()
              + ":"
              + serverInfo.getPort()
              + " connecting user name - "
              + serverInfo.getUserName(),
          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
              + " on server - "
              + serverInfo.getHost()
              + ":"
              + serverInfo.getPort()
              + " connecting user name - "
              + serverInfo.getUserName(),
          e);
    }

    commandOutput.onOutput(channel);

    channel.disconnect();
    session.disconnect();
  }
  /** {@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();
    }
  }
Пример #7
0
  private Connection getMySQLSSHConnection() {
    Connection connection = null;

    //
    int assigned_port;
    final int local_port = 3309;

    // Remote host and port
    final int remote_port = 3306;
    final String remote_host = "remote.host.com";

    try {
      JSch jsch = new JSch();

      // Create SSH session.  Port 22 is your SSH port which
      // is open in your firewall setup.
      System.out.println("DEBUG: get session");
      Session session = jsch.getSession("user", remote_host, 22);
      System.out.println("DEBUG: set password");
      session.setPassword("password");

      // Additional SSH options.  See your ssh_config manual for
      // more options.  Set options according to your requirements.
      java.util.Properties config = new java.util.Properties();
      config.put("StrictHostKeyChecking", "no");
      config.put("Compression", "yes");
      config.put("ConnectionAttempts", "2");

      System.out.println("DEBUG: set configuration");
      session.setConfig(config);

      // Connect
      System.out.println("DEBUG: SSH connect");
      session.connect();

      // Create the tunnel through port forwarding.
      // This is basically instructing jsch session to send
      // data received from local_port in the local machine to
      // remote_port of the remote_host
      // assigned_port is the port assigned by jsch for use,
      // it may not always be the same as
      // local_port.

      System.out.println("DEBUG: get assigned port");
      assigned_port = session.setPortForwardingL(local_port, remote_host, remote_port);

    } catch (JSchException e) {
      System.out.println("DEBUG: SSH exception: fail");
      e.printStackTrace();
      return null;
    }

    if (assigned_port == 0) {
      System.out.println("Port forwarding failed !");
      return null;
    }

    // Database access credintials.  Make sure this user has
    // "connect" access to this database;

    // these may be initialized somewhere else in your code.
    final String database_user = "******";
    final String database_password = "******";
    final String database = "db_name";

    // Build the  database connection URL.
    StringBuilder url = new StringBuilder("jdbc:mysql://localhost:");

    // use assigned_port to establish database connection
    url.append(assigned_port)
        .append("/")
        .append(database)
        .append("?user="******"&password="******"DEBUG: load mysql driver");
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      System.out.println("DEBUG: get connection");
      connection = DriverManager.getConnection(url.toString());
    } catch (Exception e) {
      System.out.println("DEBUG get connection failed");
      e.printStackTrace();
    }

    return connection;
  }