Exemplo n.º 1
0
  private void authenticate() {

    try {
      if (connection.authenticateWithNone(profile.getUser())) {
        Log.d(TAG, "Authenticate with none");
        return;
      }
    } catch (Exception e) {
      Log.d(TAG, "Host does not support 'none' authentication.");
    }

    try {
      if (connection.isAuthMethodAvailable(profile.getUser(), AUTH_PUBLICKEY)) {
        File f = new File(profile.getKeyPath());
        if (f.exists()) if (profile.getPassword().equals("")) profile.setPassword(null);
        if (connection.authenticateWithPublicKey(profile.getUser(), f, profile.getPassword())) {
          Log.d(TAG, "Authenticate with public key");
          return;
        }
      }
    } catch (Exception e) {
      Log.d(TAG, "Host does not support 'Public key' authentication.");
    }

    try {
      if (connection.isAuthMethodAvailable(profile.getUser(), AUTH_PASSWORD)) {
        if (connection.authenticateWithPassword(profile.getUser(), profile.getPassword())) {
          Log.d(TAG, "Authenticate with password");
          return;
        }
      }
    } catch (IllegalStateException e) {
      Log.e(TAG, "Connection went away while we were trying to authenticate", e);
    } catch (Exception e) {
      Log.e(TAG, "Problem during handleAuthentication()", e);
    }

    // TODO: Need verification

    try {
      if (connection.isAuthMethodAvailable(profile.getUser(), AUTH_KEYBOARDINTERACTIVE)) {
        if (connection.authenticateWithKeyboardInteractive(profile.getUser(), this)) return;
      }
    } catch (Exception e) {
      Log.d(TAG, "Host does not support 'Keyboard-Interactive' authentication.");
    }
  }
Exemplo n.º 2
0
  @Override
  public Map<? extends ServerResource, Map<String, String>> find(
      long dcId,
      Long podId,
      Long clusterId,
      URI uri,
      String username,
      String password,
      List<String> hostTags)
      throws DiscoveryException {

    ClusterVO cluster = _clusterDao.findById(clusterId);
    if (cluster == null || cluster.getHypervisorType() != HypervisorType.KVM) {
      if (s_logger.isInfoEnabled())
        s_logger.info("invalid cluster id or cluster is not for KVM hypervisors");
      return null;
    }

    Map<KvmDummyResourceBase, Map<String, String>> resources =
        new HashMap<KvmDummyResourceBase, Map<String, String>>();
    Map<String, String> details = new HashMap<String, String>();
    if (!uri.getScheme().equals("http")) {
      String msg =
          "urlString is not http so we're not taking care of the discovery for this: " + uri;
      s_logger.debug(msg);
      return null;
    }
    com.trilead.ssh2.Connection sshConnection = null;
    String agentIp = null;
    try {

      String hostname = uri.getHost();
      InetAddress ia = InetAddress.getByName(hostname);
      agentIp = ia.getHostAddress();
      String guid = UUID.nameUUIDFromBytes(agentIp.getBytes()).toString();
      String guidWithTail = guid + "-LibvirtComputingResource"; /*tail added by agent.java*/
      if (_resourceMgr.findHostByGuid(guidWithTail) != null) {
        s_logger.debug(
            "Skipping " + agentIp + " because " + guidWithTail + " is already in the database.");
        return null;
      }

      sshConnection = new com.trilead.ssh2.Connection(agentIp, 22);

      sshConnection.connect(null, 60000, 60000);
      if (!sshConnection.authenticateWithPassword(username, password)) {
        s_logger.debug("Failed to authenticate");
        throw new DiscoveredWithErrorException("Authentication error");
      }

      if (!SSHCmdHelper.sshExecuteCmd(sshConnection, "lsmod|grep kvm", 3)) {
        s_logger.debug("It's not a KVM enabled machine");
        return null;
      }

      List<PhysicalNetworkSetupInfo> netInfos =
          _networkMgr.getPhysicalNetworkInfo(dcId, HypervisorType.KVM);
      String kvmPrivateNic = _kvmPrivateNic;
      String kvmPublicNic = _kvmPublicNic;
      String kvmGuestNic = _kvmGuestNic;

      for (PhysicalNetworkSetupInfo info : netInfos) {
        if (info.getPrivateNetworkName() != null) {
          kvmPrivateNic = info.getPrivateNetworkName();
        }
        if (info.getPublicNetworkName() != null) {
          kvmPublicNic = info.getPublicNetworkName();
        }
        if (info.getGuestNetworkName() != null) {
          kvmGuestNic = info.getGuestNetworkName();
        }
      }

      String parameters =
          " -m " + _hostIp + " -z " + dcId + " -p " + podId + " -c " + clusterId + " -g " + guid
              + " -a";

      if (kvmPublicNic != null) {
        parameters += " --pubNic=" + kvmPublicNic;
      }

      if (kvmPrivateNic != null) {
        parameters += " --prvNic=" + kvmPrivateNic;
      }

      if (kvmGuestNic != null) {
        parameters += " --guestNic=" + kvmGuestNic;
      }

      SSHCmdHelper.sshExecuteCmd(sshConnection, "cloud-setup-agent " + parameters, 3);

      KvmDummyResourceBase kvmResource = new KvmDummyResourceBase();
      Map<String, Object> params = new HashMap<String, Object>();

      params.put("zone", Long.toString(dcId));
      params.put("pod", Long.toString(podId));
      params.put("cluster", Long.toString(clusterId));
      params.put("guid", guid);
      params.put("agentIp", agentIp);
      kvmResource.configure("kvm agent", params);
      resources.put(kvmResource, details);

      HostVO connectedHost = waitForHostConnect(dcId, podId, clusterId, guidWithTail);
      if (connectedHost == null) return null;

      details.put("guid", guidWithTail);

      // place a place holder guid derived from cluster ID
      if (cluster.getGuid() == null) {
        cluster.setGuid(UUID.nameUUIDFromBytes(String.valueOf(clusterId).getBytes()).toString());
        _clusterDao.update(clusterId, cluster);
      }

      // save user name and password
      _hostDao.loadDetails(connectedHost);
      Map<String, String> hostDetails = connectedHost.getDetails();
      hostDetails.put("password", password);
      hostDetails.put("username", username);
      _hostDao.saveDetails(connectedHost);
      return resources;
    } catch (DiscoveredWithErrorException e) {
      throw e;
    } catch (Exception e) {
      String msg = " can't setup agent, due to " + e.toString() + " - " + e.getMessage();
      s_logger.warn(msg);
    } finally {
      if (sshConnection != null) sshConnection.close();
    }

    return null;
  }
Exemplo n.º 3
0
  public Result execute(Result previousResult, int nr) {
    Result result = previousResult;
    result.setResult(false);

    try {

      // Get real variable value
      String realServerName = environmentSubstitute(serverName);
      int realServerPort = Const.toInt(environmentSubstitute(serverPort), 22);
      String realUserName = environmentSubstitute(userName);
      String realServerPassword =
          Encr.decryptPasswordOptionallyEncrypted(environmentSubstitute(password));
      // Proxy Host
      String realProxyHost = environmentSubstitute(httpproxyhost);
      int realProxyPort = Const.toInt(environmentSubstitute(httpproxyport), 22);
      String realproxyUserName = environmentSubstitute(httpproxyusername);
      String realProxyPassword =
          Encr.decryptPasswordOptionallyEncrypted(environmentSubstitute(httpProxyPassword));
      // Key file
      String realKeyFilename = environmentSubstitute(keyFilename);
      String relKeyFilepass = environmentSubstitute(keyFilePass);
      // Source files
      String realLocalDirectory = environmentSubstitute(localDirectory);
      String realwildcard = environmentSubstitute(wildcard);
      // Remote destination
      String realftpDirectory = environmentSubstitute(ftpDirectory);
      // Destination folder (Move to)
      String realDestinationFolder = environmentSubstitute(destinationfolder);

      try {
        // Remote source
        realftpDirectory = FTPUtils.normalizePath(realftpDirectory);
        // Destination folder (Move to)
        realDestinationFolder = FTPUtils.normalizePath(realDestinationFolder);
      } catch (Exception e) {
        logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.CanNotNormalizePath", e.getMessage()));
        result.setNrErrors(1);
        return result;
      }

      // Check for mandatory fields
      boolean mandatoryok = true;
      if (Const.isEmpty(realServerName)) {
        mandatoryok = false;
        logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.ServernameMissing"));
      }
      if (usehttpproxy) {
        if (Const.isEmpty(realProxyHost)) {
          mandatoryok = false;
          logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.HttpProxyhostMissing"));
        }
      }
      if (publicpublickey) {
        if (Const.isEmpty(realKeyFilename)) {
          mandatoryok = false;
          logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.KeyFileMissing"));
        } else {
          // Let's check if folder exists...
          if (!KettleVFS.fileExists(realKeyFilename, this)) {
            mandatoryok = false;
            logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.KeyFileNotExist"));
          }
        }
      }

      if (Const.isEmpty(realLocalDirectory)) {
        mandatoryok = false;
        logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.LocalFolderMissing"));
      }
      if (afterFtpPut.equals("move_file")) {
        if (Const.isEmpty(realDestinationFolder)) {
          mandatoryok = false;
          logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.DestinatFolderMissing"));
        } else {
          FileObject folder = null;
          try {
            folder = KettleVFS.getFileObject(realDestinationFolder, this);
            // Let's check if folder exists...
            if (!folder.exists()) {
              // Do we need to create it?
              if (createDestinationFolder) {
                folder.createFolder();
              } else {
                logError(
                    BaseMessages.getString(
                        PKG, "JobSSH2PUT.Log.DestinatFolderNotExist", realDestinationFolder));
              }
            }
          } catch (Exception e) {
            throw new KettleException(e);
          } finally {
            if (folder != null) {
              try {
                folder.close();
                folder = null;
              } catch (Exception e) {
                /* Ignore */
              }
            }
          }
        }
      }

      if (mandatoryok) {
        Connection conn = null;
        SFTPv3Client client = null;
        boolean good = true;

        int nbfilestoput = 0;
        int nbput = 0;
        int nbrerror = 0;

        try {
          // Create a connection instance
          conn =
              getConnection(
                  realServerName,
                  realServerPort,
                  realProxyHost,
                  realProxyPort,
                  realproxyUserName,
                  realProxyPassword);

          if (timeout > 0) {
            // Use timeout
            // Cache Host Key
            if (cachehostkey) {
              conn.connect(new SimpleVerifier(database), 0, timeout * 1000);
            } else {
              conn.connect(null, 0, timeout * 1000);
            }

          } else {
            // Cache Host Key
            if (cachehostkey) {
              conn.connect(new SimpleVerifier(database));
            } else {
              conn.connect();
            }
          }

          // Authenticate

          boolean isAuthenticated = false;
          if (publicpublickey) {
            String keyContent =
                KettleVFS.getTextFileContent(realKeyFilename, this, Const.XML_ENCODING);
            isAuthenticated =
                conn.authenticateWithPublicKey(
                    realUserName, keyContent.toCharArray(), relKeyFilepass);
          } else {
            isAuthenticated = conn.authenticateWithPassword(realUserName, realServerPassword);
          }

          // LET'S CHECK AUTHENTICATION ...
          if (isAuthenticated == false) {
            logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.AuthenticationFailed"));
          } else {
            if (log.isBasic()) {
              logBasic(
                  BaseMessages.getString(PKG, "JobSSH2PUT.Log.Connected", serverName, userName));
            }

            client = new SFTPv3Client(conn);

            if (log.isDetailed()) {
              logDetailed(
                  BaseMessages.getString(
                      PKG, "JobSSH2PUT.Log.ProtocolVersion", "" + client.getProtocolVersion()));
            }

            // Check if remote directory exists
            if (!Const.isEmpty(realftpDirectory)) {
              if (!sshDirectoryExists(client, realftpDirectory)) {
                good = false;
                if (createRemoteFolder) {
                  good = CreateRemoteFolder(client, realftpDirectory);
                  if (good) {
                    logBasic(BaseMessages.getString(PKG, "JobSSH2PUT.Log.RemoteDirectoryCreated"));
                  }

                } else {
                  logError(
                      BaseMessages.getString(
                          PKG, "JobSSH2PUT.Log.RemoteDirectoryNotExist", realftpDirectory));
                }
              } else if (log.isDetailed()) {
                logDetailed(
                    BaseMessages.getString(
                        PKG, "JobSSH2PUT.Log.RemoteDirectoryExist", realftpDirectory));
              }
            }

            if (good) {
              // Get files list from local folder (source)
              List<FileObject> myFileList = getFiles(realLocalDirectory);

              // Prepare Pattern for wildcard
              Pattern pattern = null;
              if (!Const.isEmpty(realwildcard)) {
                pattern = Pattern.compile(realwildcard);
              }

              // Let's put files now ...
              // Get the files in the list
              for (int i = 0; i < myFileList.size() && !parentJob.isStopped(); i++) {
                FileObject myFile = myFileList.get(i);
                String localFilename = myFile.toString();
                String remoteFilename = myFile.getName().getBaseName();

                boolean getIt = true;

                // First see if the file matches the regular expression!
                if (pattern != null) {
                  Matcher matcher = pattern.matcher(remoteFilename);
                  getIt = matcher.matches();
                }

                // do we have a target directory?
                if (!Const.isEmpty(realftpDirectory)) {
                  remoteFilename = realftpDirectory + FTPUtils.FILE_SEPARATOR + remoteFilename;
                }

                if (onlyGettingNewFiles) {
                  // We get only new files
                  // ie not exist on the remote server
                  getIt = !sshFileExists(client, remoteFilename);
                }

                if (getIt) {
                  nbfilestoput++;

                  boolean putok = putFile(myFile, remoteFilename, client);
                  if (!putok) {
                    nbrerror++;
                    logError(
                        BaseMessages.getString(
                            PKG, "JobSSH2PUT.Log.Error.CanNotPutFile", localFilename));
                  } else {
                    nbput++;
                  }

                  if (putok && !afterFtpPut.equals("do_nothing")) {
                    deleteOrMoveFiles(myFile, realDestinationFolder);
                  }
                }
              }
              /** ****************************** RESULT ******************* */
              if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobSSH2PUT.Log.Result.JobEntryEnd1"));
                logDetailed(
                    BaseMessages.getString(
                        PKG, "JobSSH2PUT.Log.Result.TotalFiles", "" + nbfilestoput));
                logDetailed(
                    BaseMessages.getString(PKG, "JobSSH2PUT.Log.Result.TotalFilesPut", "" + nbput));
                logDetailed(
                    BaseMessages.getString(
                        PKG, "JobSSH2PUT.Log.Result.TotalFilesError", "" + nbrerror));
                logDetailed(BaseMessages.getString(PKG, "JobSSH2PUT.Log.Result.JobEntryEnd2"));
              }
              if (nbrerror == 0) {
                result.setResult(true);
                /** ****************************** RESULT ******************* */
              }
            }
          }

        } catch (Exception e) {
          result.setNrErrors(nbrerror);
          logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.Error.ErrorFTP", e.getMessage()));
        } finally {
          if (conn != null) {
            conn.close();
          }
          if (client != null) {
            client.close();
          }
        }
      }
    } catch (Exception e) {
      result.setResult(false);
      result.setNrErrors(1L);
      logError(BaseMessages.getString(PKG, "JobSSH2PUT.Log.Error.UnexpectedError"), e);
    }

    return result;
  }
Exemplo n.º 4
0
 /**
  * Authenticate using some supported methods. If authentication fails, the method throws {@link
  * IOException}.
  *
  * @param c the connection to use for authentication
  * @throws IOException in case of IO error or authentication failure
  */
 private void authenticate(final Connection c) throws IOException {
   for (String method : myHost.getPreferredMethods()) {
     if (c.isAuthenticationComplete()) {
       return;
     }
     if (PUBLIC_KEY_METHOD.equals(method)) {
       if (!myHost.supportsPubkeyAuthentication()) {
         continue;
       }
       if (!c.isAuthMethodAvailable(myHost.getUser(), PUBLIC_KEY_METHOD)) {
         continue;
       }
       File key = myHost.getIdentityFile();
       if (key == null) {
         for (String a : myHost.getHostKeyAlgorithms()) {
           if (SSH_RSA_ALGORITHM.equals(a)) {
             if (tryPublicKey(c, idRSAPath)) {
               return;
             }
           } else if (SSH_DSS_ALGORITHM.equals(a)) {
             if (tryPublicKey(c, idDSAPath)) {
               return;
             }
           }
         }
       } else {
         if (tryPublicKey(c, key.getPath())) {
           return;
         }
       }
     } else if (KEYBOARD_INTERACTIVE_METHOD.equals(method)) {
       if (!c.isAuthMethodAvailable(myHost.getUser(), KEYBOARD_INTERACTIVE_METHOD)) {
         continue;
       }
       InteractiveSupport interactiveSupport = new InteractiveSupport();
       for (int i = myHost.getNumberOfPasswordPrompts(); i > 0; i--) {
         if (c.isAuthenticationComplete()) {
           return;
         }
         if (c.authenticateWithKeyboardInteractive(myHost.getUser(), interactiveSupport)) {
           myLastError = "";
           return;
         } else {
           myLastError = GitBundle.getString("sshmain.keyboard.interactive.failed");
         }
         if (interactiveSupport.myPromptCount == 0 || interactiveSupport.myCancelled) {
           // the interactive callback has never been asked or it was cancelled, exit the loop
           myLastError = "";
           break;
         }
       }
     } else if (PASSWORD_METHOD.equals(method)) {
       if (!myHost.supportsPasswordAuthentication()) {
         continue;
       }
       if (!c.isAuthMethodAvailable(myHost.getUser(), PASSWORD_METHOD)) {
         continue;
       }
       for (int i = myHost.getNumberOfPasswordPrompts(); i > 0; i--) {
         String password =
             myXmlRpcClient.askPassword(myHandlerNo, getUserHostString(), myLastError);
         if (password == null) {
           break;
         } else {
           if (c.authenticateWithPassword(myHost.getUser(), password)) {
             myLastError = "";
             return;
           } else {
             myLastError = GitBundle.getString("sshmain.password.failed");
           }
         }
       }
     }
   }
   throw new IOException("Authentication failed");
 }
Exemplo n.º 5
0
  public Result execute(Result previousResult, int nr) {
    Result result = previousResult;
    result.setResult(false);

    if (log.isRowLevel()) {
      logRowlevel(BaseMessages.getString(PKG, "JobSSH2GET.Log.GettingFieldsValue"));
    }

    // Get real variable value
    String realServerName = environmentSubstitute(serverName);
    int realServerPort = Const.toInt(environmentSubstitute(serverPort), 22);
    String realUserName = environmentSubstitute(userName);
    String realServerPassword =
        Encr.decryptPasswordOptionallyEncrypted(environmentSubstitute(password));
    // Proxy Host
    String realProxyHost = environmentSubstitute(httpProxyHost);
    int realProxyPort = Const.toInt(environmentSubstitute(httpproxyport), 22);
    String realproxyUserName = environmentSubstitute(httpproxyusername);
    String realProxyPassword =
        Encr.decryptPasswordOptionallyEncrypted(environmentSubstitute(httpProxyPassword));
    // Key file
    String realKeyFilename = environmentSubstitute(keyFilename);
    String relKeyFilepass = environmentSubstitute(keyFilePass);
    // target files
    String realLocalDirectory = environmentSubstitute(localDirectory);
    String realwildcard = environmentSubstitute(wildcard);
    // Remote source
    String realftpDirectory = environmentSubstitute(ftpDirectory);
    // Destination folder (Move to)
    String realDestinationFolder = environmentSubstitute(destinationfolder);

    try {
      // Remote source
      realftpDirectory = FTPUtils.normalizePath(realftpDirectory);
      // Destination folder (Move to)
      realDestinationFolder = FTPUtils.normalizePath(realDestinationFolder);
    } catch (Exception e) {
      logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.CanNotNormalizePath", e.getMessage()));
      result.setNrErrors(1);
      return result;
    }

    // Check for mandatory fields
    if (log.isRowLevel()) {
      logRowlevel(BaseMessages.getString(PKG, "JobSSH2GET.Log.CheckingMandatoryFields"));
    }

    boolean mandatoryok = true;
    if (Const.isEmpty(realServerName)) {
      mandatoryok = false;
      logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.ServernameMissing"));
    }
    if (usehttpproxy) {
      if (Const.isEmpty(realProxyHost)) {
        mandatoryok = false;
        logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.HttpProxyhostMissing"));
      }
    }
    if (publicpublickey) {
      if (Const.isEmpty(realKeyFilename)) {
        mandatoryok = false;
        logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.KeyFileMissing"));
      } else {
        // Let's check if key file exists...
        if (!new File(realKeyFilename).exists()) {
          mandatoryok = false;
          logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.KeyFileNotExist"));
        }
      }
    }

    if (Const.isEmpty(realLocalDirectory)) {
      mandatoryok = false;
      logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.LocalFolderMissing"));
    } else {
      // Check if target folder exists...
      if (!new File(realLocalDirectory).exists()) {

        if (createtargetfolder) {
          // Create Target folder
          if (!CreateFolder(realLocalDirectory)) {
            mandatoryok = false;
          }

        } else {
          mandatoryok = false;
          logError(
              BaseMessages.getString(
                  PKG, "JobSSH2GET.Log.LocalFolderNotExists", realLocalDirectory));
        }
      } else {
        if (!new File(realLocalDirectory).isDirectory()) {
          mandatoryok = false;
          logError(
              BaseMessages.getString(
                  PKG, "JobSSH2GET.Log.LocalFolderNotFolder", realLocalDirectory));
        }
      }
    }
    if (afterFtpPut.equals("move_file")) {
      if (Const.isEmpty(realDestinationFolder)) {
        mandatoryok = false;
        logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.DestinatFolderMissing"));
      }
    }

    if (mandatoryok) {

      Connection conn = null;
      SFTPv3Client client = null;
      boolean good = true;

      try {
        // Create a connection instance
        conn =
            getConnection(
                realServerName,
                realServerPort,
                realProxyHost,
                realProxyPort,
                realproxyUserName,
                realProxyPassword);
        if (log.isDetailed()) {
          logDetailed(BaseMessages.getString(PKG, "JobSSH2GET.Log.ConnectionInstanceCreated"));
        }
        if (timeout > 0) {
          // Use timeout
          // Cache Host Key
          if (cachehostkey) {
            conn.connect(new SimpleVerifier(database), 0, timeout * 1000);
          } else {
            conn.connect(null, 0, timeout * 1000);
          }

        } else {
          // Cache Host Key
          if (cachehostkey) {
            conn.connect(new SimpleVerifier(database));
          } else {
            conn.connect();
          }
        }

        // Authenticate

        boolean isAuthenticated = false;
        if (publicpublickey) {
          isAuthenticated =
              conn.authenticateWithPublicKey(
                  realUserName, new File(realKeyFilename), relKeyFilepass);
        } else {
          isAuthenticated = conn.authenticateWithPassword(realUserName, realServerPassword);
        }

        // LET'S CHECK AUTHENTICATION ...
        if (isAuthenticated == false) {
          logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.AuthenticationFailed"));
        } else {
          if (log.isBasic()) {
            logBasic(BaseMessages.getString(PKG, "JobSSH2GET.Log.Connected", serverName, userName));
          }

          client = new SFTPv3Client(conn);

          if (log.isDetailed()) {
            logDetailed(
                BaseMessages.getString(
                    PKG, "JobSSH2GET.Log.ProtocolVersion", "" + client.getProtocolVersion()));
          }

          // Check if ftp (source) directory exists
          if (!Const.isEmpty(realftpDirectory)) {
            if (!sshDirectoryExists(client, realftpDirectory)) {
              good = false;
              logError(
                  BaseMessages.getString(
                      PKG, "JobSSH2GET.Log.RemoteDirectoryNotExist", realftpDirectory));
            } else if (log.isDetailed()) {
              logDetailed(
                  BaseMessages.getString(
                      PKG, "JobSSH2GET.Log.RemoteDirectoryExist", realftpDirectory));
            }
          }

          if (realDestinationFolder != null) {
            // Check now destination folder
            if (!sshDirectoryExists(client, realDestinationFolder)) {
              if (createdestinationfolder) {
                if (!CreateRemoteFolder(client, realDestinationFolder)) {
                  good = false;
                }
              } else {
                good = false;
                logError(
                    BaseMessages.getString(
                        PKG, "JobSSH2GET.Log.DestinatFolderNotExist", realDestinationFolder));
              }
            }
          }

          if (good) {
            Pattern pattern = null;
            if (!Const.isEmpty(realwildcard)) {
              pattern = Pattern.compile(realwildcard);
            }

            if (includeSubFolders) {
              if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobSSH2GET.Log.RecursiveModeOn"));
              }
              copyRecursive(realftpDirectory, realLocalDirectory, client, pattern, parentJob);
            } else {
              if (log.isDetailed()) {
                logDetailed(BaseMessages.getString(PKG, "JobSSH2GET.Log.RecursiveModeOff"));
              }
              GetFiles(realftpDirectory, realLocalDirectory, client, pattern, parentJob);
            }

            /** ****************************** RESULT ******************* */
            if (log.isDetailed()) {
              logDetailed(BaseMessages.getString(PKG, "JobSSH2GET.Log.Result.JobEntryEnd1"));
              logDetailed(
                  BaseMessages.getString(
                      PKG, "JobSSH2GET.Log.Result.TotalFiles", "" + nbfilestoget));
              logDetailed(
                  BaseMessages.getString(PKG, "JobSSH2GET.Log.Result.TotalFilesPut", "" + nbgot));
              logDetailed(
                  BaseMessages.getString(
                      PKG, "JobSSH2GET.Log.Result.TotalFilesError", "" + nbrerror));
              logDetailed(BaseMessages.getString(PKG, "JobSSH2GET.Log.Result.JobEntryEnd2"));
            }
            if (nbrerror == 0) {
              result.setResult(true);
              /** ****************************** RESULT ******************* */
            }
          }
        }

      } catch (Exception e) {
        result.setNrErrors(nbrerror);
        logError(BaseMessages.getString(PKG, "JobSSH2GET.Log.Error.ErrorFTP", e.getMessage()));
      } finally {
        if (conn != null) {
          conn.close();
        }
        if (client != null) {
          client.close();
        }
      }
    }

    return result;
  }
  public static void main(String[] args) {
    String hostname = "127.0.0.1";
    String username = "******";
    String password = "******";

    try {
      /* Create a connection instance */

      Connection conn = new Connection(hostname);

      /* Now connect */

      conn.connect();

      /* Authenticate */

      boolean isAuthenticated = conn.authenticateWithPassword(username, password);

      if (isAuthenticated == false) throw new IOException("Authentication failed.");

      /* Create a session */

      Session sess = conn.openSession();

      sess.execCommand("echo \"Text on STDOUT\"; echo \"Text on STDERR\" >&2");

      InputStream stdout = new StreamGobbler(sess.getStdout());
      InputStream stderr = new StreamGobbler(sess.getStderr());

      BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdout));
      BufferedReader stderrReader = new BufferedReader(new InputStreamReader(stderr));

      System.out.println("Here is the output from stdout:");

      while (true) {
        String line = stdoutReader.readLine();
        if (line == null) break;
        System.out.println(line);
      }

      System.out.println("Here is the output from stderr:");

      while (true) {
        String line = stderrReader.readLine();
        if (line == null) break;
        System.out.println(line);
      }

      /* Close this session */

      sess.close();

      /* Close the connection */

      conn.close();

    } catch (IOException e) {
      e.printStackTrace(System.err);
      System.exit(2);
    }
  }