/**
   * 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;
  }
 private void executeShellScripts(Session session) throws IOException, JSchException {
   Channel channel = session.openChannel("shell");
   File shellScript = new File("scripts/ubuntu-scripts.txt");
   FileInputStream fin = new FileInputStream(shellScript);
   byte fileContent[] = new byte[(int) shellScript.length()];
   fin.read(fileContent);
   InputStream in = new ByteArrayInputStream(fileContent);
   channel.setInputStream(in);
   channel.setOutputStream(System.out);
   channel.connect();
 }
  public static void main(String[] arg) {

    String xhost = "127.0.0.1";
    int xport = 0;

    try {
      JSch jsch = new JSch();

      String host = null;
      if (arg.length > 0) {
        host = arg[0];
      } else {
        host =
            JOptionPane.showInputDialog(
                "Enter username@hostname", System.getProperty("user.name") + "@localhost");
      }
      String user = host.substring(0, host.indexOf('@'));
      host = host.substring(host.indexOf('@') + 1);

      Session session = jsch.getSession(user, host, 22);

      String display =
          JOptionPane.showInputDialog("Please enter display name", xhost + ":" + xport);
      xhost = display.substring(0, display.indexOf(':'));
      xport = Integer.parseInt(display.substring(display.indexOf(':') + 1));

      session.setX11Host(xhost);
      session.setX11Port(xport + 6000);

      // username and password will be given via UserInfo interface.
      UserInfo ui = new MyUserInfo();
      session.setUserInfo(ui);
      session.connect();

      Channel channel = session.openChannel("shell");

      channel.setXForwarding(true);

      channel.setInputStream(System.in);
      channel.setOutputStream(System.out);

      channel.connect();
    } catch (Exception e) {
      System.out.println(e);
    }
  }
Esempio n. 4
0
  public static void main(String[] arg) throws JSchException, InterruptedException {
    JSch jsch = new JSch();

    String[] proxyInfo = queryUserAndHost("proxy server", arg.length > 0 ? arg[0] : null);

    Session gateway = jsch.getSession(proxyInfo[0], proxyInfo[1]);

    UserInfo ui = new SwingDialogUserInfo();
    gateway.setUserInfo(ui);
    gateway.connect();

    String[] targetInfo = queryUserAndHost("target server", arg.length > 1 ? arg[1] : null);

    Session session = jsch.getSession(targetInfo[0], targetInfo[1]);

    session.setProxy(new ProxySSH(gateway));

    session.setUserInfo(ui);

    System.err.println("connecting session ...");
    session.connect();

    System.err.println("session connected.");
    System.err.println("opening shell channel ...");

    Channel channel = session.openChannel("shell");

    channel.setOutputStream(System.out, true);
    channel.setExtOutputStream(System.err, true);

    channel.setInputStream(System.in, true);

    channel.connect();

    System.err.println("shell channel connected.");

    do {
      Thread.sleep(100);
    } while (!channel.isEOF());
    System.err.println("exitcode: " + channel.getExitStatus());
    session.disconnect();
    Thread.sleep(50);

    gateway.disconnect();
  }
  private static void runCommandOnHost(String host, String user, String password, String command) {
    try {
      JSch jsch = new JSch();

      Session session = jsch.getSession(user, host, 22);
      java.util.Properties config = new java.util.Properties();
      config.put("StrictHostKeyChecking", "no");
      session.setConfig(config);
      session.setPassword(password);
      session.connect();
      Channel channel = session.openChannel("exec");
      ((ChannelExec) channel).setCommand(command);

      channel.setInputStream(null);

      ((ChannelExec) channel).setErrStream(System.err);

      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;
        }
        if (channel.isClosed()) {
          if (in.available() > 0) continue;
          // System.out.println("exit-status: "+channel.getExitStatus());
          break;
        }
        try {
          Thread.sleep(1000);
        } catch (Exception ee) {
        }
      }
      channel.disconnect();
      session.disconnect();
    } catch (Exception e) {
      System.out.println(e);
    }
  }
 /**
  * This method execute the given command over SSH
  *
  * @param session
  * @param command Command to be executed
  * @throws JSchException
  * @throws IOException
  * @throws InterruptedException
  */
 @SuppressWarnings("unused")
 private static void executeCommand(Session session, String command)
     throws JSchException, IOException, InterruptedException {
   InputStream in = null;
   Channel channel = null;
   try {
     channel = session.openChannel("exec");
     ((ChannelExec) channel).setCommand(command);
     channel.setInputStream(null);
     ((ChannelExec) channel).setErrStream(System.err);
     in = channel.getInputStream();
     channel.connect();
     String msg = validateCommandExecution(channel, in);
   } finally {
     if (in != null) {
       in.close();
     }
     if (channel != null) {
       channel.disconnect();
     }
   }
 }
  public String runCommand(String params) {
    try {
      StringBuilder sb = new StringBuilder();
      Channel channel = ConnectionManager.getSession().openChannel("exec");
      channel.setInputStream(null);
      channel.setOutputStream(System.out);
      ((ChannelExec) channel).setCommand(params);
      ((ChannelExec) channel).setPty(false);
      channel.connect();
      InputStream in = channel.getInputStream();
      //			byte[] tmp = new byte[1024];
      while (true) {
        InputStreamReader is = new InputStreamReader(in);

        BufferedReader br = new BufferedReader(is);
        String read = br.readLine();
        while (read != null) {
          System.out.println(read);
          sb.append(read);
          read = br.readLine();
        }
        if (channel.isClosed()) {
          System.out.println(sb.toString());
          System.out.println("exit-status:" + channel.getExitStatus());
          break;
        }
        try {
          Thread.sleep(1000);
        } catch (Exception ee) {
        }
      }
      channel.disconnect();
      return sb.toString();
    } catch (Exception e) {
      e.printStackTrace();
      return "empty";
    }
  }
Esempio n. 8
0
  public void execCmd(String command) {
    //        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    //        String command = "";
    BufferedReader reader = null;
    Channel channel = null;

    try {
      //            while ((command = br.readLine()) != null) {
      channel = session.openChannel("exec");
      ((ChannelExec) channel).setCommand(command);
      channel.setInputStream(null);
      ((ChannelExec) channel).setErrStream(System.err);

      channel.connect();
      InputStream in = channel.getInputStream();
      reader = new BufferedReader(new InputStreamReader(in, Charset.forName(charset)));
      String buf = null;
      while ((buf = reader.readLine()) != null) {
        System.out.println(buf);
      }
      //            }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (JSchException e) {
      e.printStackTrace();
    } finally {
      try {
        reader.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
      channel.disconnect();
      session.disconnect();
    }
  }
  /**
   * 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();
  }
  public String send(String command) throws IOException {
    if (isClosed()) {
      connect(this.host, this.port, this.username, this.password);
    }
    // System.out.println("begin to send cmd = " + command);
    Channel channel = null;
    try {
      channel = session.openChannel("shell");
    } catch (JSchException e) {
      e.printStackTrace();
    }

    if (channel == null) {
      System.out.println("can not open channel shell");
      return null;
    }
    StringBuilder sb = new StringBuilder();
    String result = "";
    String request = new String("echo " + identity + "\n" + command + "\n" + "\nexit\n");
    ChannelShell shell = (ChannelShell) channel;
    shell.setPtyType("vt320", 512, 100, 1024, 768);
    try {
      InputStream input = new ByteArrayInputStream(request.getBytes());
      channel.setInputStream(input);

      input = new ByteArrayInputStream(request.getBytes());
      channel.setInputStream(input);

      InputStream in = channel.getInputStream();

      // channel.setOutputStream(out);
      // channel.setExtOutputStream(System.err);
      channel.connect();

      byte[] tmp = new byte[1024];
      while (true) {
        // System.out.println("waiting for input ...");
        // avai = in.available();
        // System.out.println("available = "+avai );
        while ((in.available()) > 0) {
          // System.out.println("begin to read");
          int i = in.read(tmp, 0, 1024);
          // System.out.println("i" + " = "+ i);
          if (i < 0) break;
          sb.append(new String(tmp, 0, i));
          // System.out.println("sb = " + sb.toString());
          // avai = 0;
        }
        if (channel.isClosed()) {
          // System.out.println("exit-status: " +
          // channel.getExitStatus());
          break;
        }
        try {
          Thread.sleep(200);
        } catch (Exception ee) {
        }
      }

      String executeResult = sb.toString();
      executeResult = executeResult.replaceAll("\r\n", "\n");
      if (executeResult.length() > 0) {
        // if(command.indexOf("entstat")>=0)
        // SysLogger.info(executeResult);

        String[] results = executeResult.split("\n");

        sb.setLength(0);

        boolean needAppend = false;

        // if(command.indexOf("entstat")>=0){
        // for(int i = 0 ; i < results.length - 1 ; i++)
        // {
        // String line = results[i];
        // SysLogger.info(line);
        // }
        // }

        for (int i = 0; i < results.length - 1; i++) {
          String line = results[i];
          // if(command.indexOf("entstat")>=0)
          // SysLogger.info(line);
          if (needAppend) {
            // if(command.indexOf("entstat")>=0)
            // SysLogger.info("&&&&&&&&&& "+i+" ====
            // "+(results.length - 2));
            if (line.contains(" exit") && i >= results.length - 2) {
              // SysLogger.info(line);
              needAppend = false;
              break;
            }
            // if(command.indexOf("entstat")>=0)
            // SysLogger.info(line);
            sb.append(line);
            sb.append("\n");
          } else {
            // if(command.indexOf("entstat")>=0)
            // SysLogger.info(line);
            if (line.equals(identity)
                || line.equals("$" + identity)
                || line.equals("#" + identity)) {
              // if(command.indexOf("entstat")>=0)
              // SysLogger.info(results[i+1]);
              if (results[i + 1].indexOf("Hardware Address:") >= 0
                  || results[i + 1].indexOf("load average:") >= 0
                  || results[i + 1].indexOf("$hdisk") >= 0
                  || results[i + 1].indexOf("BEIST") >= 0
                  || command.equalsIgnoreCase("lsuser ALL")
                  || results[i + 1].indexOf("$AIX") >= 0
                  || command.equalsIgnoreCase("cat /etc/group")) {

                needAppend = true;
              } else {
                i++;
                needAppend = true;
              }
            }
          }
        }

        if (sb.length() > 1) {
          sb.setLength(sb.length() - 1);
        }

        result = sb.toString();

        // SysLogger.info("cmd = " + command + " , result = " + result);
        return result;
      }

    } catch (JSchException e) {
      e.printStackTrace();
    } finally {
      channel.disconnect();
    }

    // System.out.println("cmd = " + command + " result = " + result);
    // log("cmd = " + command + " , result = " + result);
    return "";
  }
  @Override
  public void run() {
    String monitoredMachineAddress = null;
    String user = null;
    String password = null;
    String host = null;

    for (String metric : getProvidedMetrics()) {
      try {
        if (dcAgent.shouldMonitor(
            new VM(Config.getInstance().getVmType(), Config.getInstance().getVmId()), metric)) {
          Map<String, String> parameters = dcAgent.getParameters(metric);

          monitoredMachineAddress = parameters.get("monitoredMachineAddress");
          user = parameters.get("user");
          password = parameters.get("password");
          host = parameters.get("host");
        }
      } catch (ConfigurationException e) {
        e.printStackTrace();
      }
    }

    JSch jsch = new JSch();

    try {
      session = jsch.getSession(user, host, 22);

      session.setPassword(password);

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

      session.connect(10 * 1000);

      long startTime = 0;

      while (!fmt.isInterrupted()) {
        if (System.currentTimeMillis() - startTime > 60000) {

          for (String metric : getProvidedMetrics()) {
            if (dcAgent.shouldMonitor(
                new VM(Config.getInstance().getVmType(), Config.getInstance().getVmId()), metric)) {
              Map<String, String> parameters = dcAgent.getParameters(metric);

              period = Integer.valueOf(parameters.get("samplingTime"));
              samplingProb = Double.valueOf(parameters.get("samplingProbability"));
            }
          }

          startTime = System.currentTimeMillis();
        }

        boolean isSent = false;
        if (Math.random() < samplingProb) {
          isSent = true;
        }
        channel = session.openChannel("exec");

        String command =
            "snmpwalk -c public -v 1 " + monitoredMachineAddress + " .1.3.6.1.4.1.2021.51";
        // command = "ls -l";
        ((ChannelExec) channel).setCommand(command);
        channel.setInputStream(null);
        ((ChannelExec) channel).setErrStream(System.err);
        channel.setOutputStream(System.out);
        InputStream in = channel.getInputStream();

        channel.connect();

        BufferedReader buf = new BufferedReader(new InputStreamReader(in));
        String line = "";

        int count = 0;
        boolean isFirst = true;
        String metricName = null;

        while ((line = buf.readLine()) != null) {
          Pattern p = Pattern.compile("\"([^\"]*)\"");
          Matcher m = p.matcher(line);

          while (m.find()) {
            if (isFirst) {
              if (m.group(1).equals("NodeID")) {
                count++;
                metricName = "NodeID";
                System.out.println("NodeID");
                isFirst = false;
              }
              continue;
            } else {
              if (count % 2 == 1) {
                try {
                  if (isSent) {
                    logger.info("Sending datum: {} {} {}", m.group(1), metricName, monitoredTarget);
                    dcAgent.send(
                        new VM(Config.getInstance().getVmType(), Config.getInstance().getVmId()),
                        metricName,
                        m.group(1));
                  }
                } catch (Exception e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                }
                // sendMonitoringDatum(Double.valueOf(m.group(1)),
                // ResourceFactory.createResource(MC.getURI() + metricName), monitoredResourceURL,
                // monitoredResource);
                // System.out.println(metricName+"   "+m.group(1));
                count++;
              } else {
                metricName = m.group(1);
                count++;
              }
            }
          }
        }

        Thread.sleep(period);
      }

    } catch (JSchException e1) {
      e1.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    } catch (NumberFormatException e) {
      e.printStackTrace();
    } catch (ConfigurationException e) {
      e.printStackTrace();
    }
  }
Esempio n. 12
-1
  public static void main(String[] arg) {
    try {
      JSch jsch = new JSch();

      String user = "******";
      String host = "hddev-c01-edge-01";
      int port = 22;
      String privateKey = "src/main/resources/id_rsa";

      jsch.addIdentity(privateKey);

      System.out.println("identity added ");

      Session session = jsch.getSession(user, host, port);
      System.out.println("session created.");

      // disabling StrictHostKeyChecking may help to make connection but makes it insecure
      // see
      // http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
      //
      java.util.Properties config = new java.util.Properties();
      config.put("StrictHostKeyChecking", "no");
      session.setConfig(config);

      session.connect();
      System.out.println("session connected.....");

      Channel channel = session.openChannel("sftp");
      channel.setInputStream(System.in);
      channel.setOutputStream(System.out);
      channel.connect();
      System.out.println("shell channel connected....");

      ChannelSftp c = (ChannelSftp) channel;

      String fileName = "src/main/resources/test.txt";
      c.put(fileName, "./in/");
      c.exit();
      System.out.println("done");

    } catch (Exception e) {
      System.err.println(e);
    }
  }