예제 #1
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();
    }
  }
예제 #2
0
    @Override
    public Integer call() {
      int exitstatus = Integer.MAX_VALUE;
      Boolean useIdentityFile = null;
      String credentials = null;
      String userName = nodeCredentials.getUsername();

      if (nodeCredentials instanceof LoginCredentialsPassword) {
        useIdentityFile = false;
        credentials = ((LoginCredentialsPassword) nodeCredentials).getPassword();
      } else if (nodeCredentials instanceof LoginCredentialsPrivateKey) {
        useIdentityFile = true;
        credentials = ((LoginCredentialsPrivateKey) nodeCredentials).getKey().getKeyPath();
      }

      ChannelExec c = null;
      SshClient ssh = null;

      try {
        ssh = new SshClient();
        ssh.createSession(nodeAddress, userName, false);

        log.info("connecting with username: "******"connecting using identity file: " + credentials);
        } else {
          log.info("connecting using password: "******"executing command: " + command);
        c.connect();

        new Thread(
                new Runnable() {
                  public void run() {
                    String line;
                    BufferedReader bufferedInputReader =
                        new BufferedReader(new InputStreamReader(is));
                    try {
                      while ((line = bufferedInputReader.readLine()) != null) {
                        output.append(line);
                        synchronized (timeStamp) {
                          timeStamp = System.currentTimeMillis();
                        }
                      }
                    } catch (IOException e) {
                      e.printStackTrace();
                    }
                  }
                })
            .start();

        new Thread(
                new Runnable() {
                  public void run() {
                    String line;
                    BufferedReader bufferedErrorReader =
                        new BufferedReader(new InputStreamReader(err));
                    try {
                      while ((line = bufferedErrorReader.readLine()) != null) {
                        error.append(line);
                        synchronized (timeStamp) {
                          timeStamp = System.currentTimeMillis();
                        }
                      }
                    } catch (IOException e) {
                      e.printStackTrace();
                    }
                  }
                })
            .start();

        while (!c.isClosed()) {
          synchronized (this.timeStamp) {
            if (System.currentTimeMillis() - this.timeStamp > MAXIMUM_WAITING_TIME_INACTIVITY) {
              log.warn("command execution seems inactive, canceling!");
              break;
            }
          }
          log.info("waiting for command to finish.");
          try {
            Thread.sleep(SshClient.DEFAULT_WAITING_TIME_PER_CYCLE);
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
        }
        exitstatus = c.getExitStatus();

      } catch (JSchException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        if (c != null) {
          c.disconnect();
        }

        if (ssh != null) {
          try {
            ssh.disconnectSession();
          } catch (JSchException e) {
            e.printStackTrace();
          }
        }
      }
      return exitstatus;
    }
예제 #3
0
  /**
   * copy a file from remote host to local
   *
   * @param rfile
   * @param lfile
   */
  public String scpFrom(String rfile, String lfile) {
    if (!connected) {
      throw new ActionFailedException("There is no session!");
    }
    FileOutputStream fos = null;
    // When get a rfile which with regular expression, to save the file with the same name as it get
    // from the remote server[add by phoebe]
    String completeLfile = lfile;

    try {
      // exec 'scp -f rfile' remotely
      String command = "scp -f " + rfile;
      Channel channel = session.openChannel("exec");
      ((ChannelExec) channel).setCommand(command);

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

      channel.connect();

      byte[] buf = new byte[1024];

      // send '\0'
      buf[0] = 0;
      out.write(buf, 0, 1);
      out.flush();

      while (true) {
        int c = checkAck(in);
        if (c != 'C') {
          break;
        }

        // read '0644 '
        in.read(buf, 0, 5);

        long filesize = 0L;
        while (true) {
          if (in.read(buf, 0, 1) < 0) {
            // error
            break;
          }
          if (buf[0] == ' ') break;
          filesize = filesize * 10L + (long) (buf[0] - '0');
        }

        String file = null;
        for (int i = 0; ; i++) {
          in.read(buf, i, 1);
          if (buf[i] == (byte) 0x0a) {
            file = new String(buf, 0, i);
            break;
          }
        }

        // send '\0'
        buf[0] = 0;
        out.write(buf, 0, 1);
        out.flush();

        // When get a rfile which with regular expression, to save the file with the same name as it
        // get from the remote server[add by phoebe]
        if (completeLfile.contains("*")) {
          completeLfile = completeLfile.substring(0, completeLfile.lastIndexOf("/")) + "/" + file;
        }

        // read a content of lfile
        fos = new FileOutputStream(completeLfile);
        int foo;
        while (true) {
          if (buf.length < filesize) foo = buf.length;
          else foo = (int) filesize;
          foo = in.read(buf, 0, foo);
          if (foo < 0) {
            // error
            break;
          }
          fos.write(buf, 0, foo);
          filesize -= foo;
          if (filesize == 0L) break;
        }
        fos.close();
        fos = null;

        if (checkAck(in) != 0) {
          throw new ActionFailedException("Failed to get Ack, Copy may fail!");
        }

        // send '\0'
        buf[0] = 0;
        out.write(buf, 0, 1);
        out.flush();
      }

    } catch (IOException e) {
      e.printStackTrace();
    } catch (JSchException e) {
      e.printStackTrace();
    } finally {
      if (channel != null) {
        channel.disconnect();
      }
    }
    return completeLfile;
  }
예제 #4
0
파일: Model.java 프로젝트: hoangdang89/Test
  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;
  }