Java Code Examples for com.trilead.ssh2.Connection#connect()

The following examples show how to use com.trilead.ssh2.Connection#connect() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HostAndPortChecker.java    From yet-another-docker-plugin with MIT License 6 votes vote down vote up
/**
 * Connects to sshd on host:port
 * Retries while attempts reached with delay
 * First with tcp port wait, then with ssh connection wait
 *
 * @throws IOException if no retries left
 */
public void bySshWithEveryRetryWaitFor(int time, TimeUnit units) throws IOException {
    checkState(withEveryRetryWaitFor(time, units), "Port %s is not opened to connect to", hostAndPort.getPort());

    for (int i = 1; i <= retries; i++) {
        Connection connection = new Connection(hostAndPort.getHostText(), hostAndPort.getPort());
        try {
            connection.connect(null, 0, sshTimeoutMillis, sshTimeoutMillis);
            LOG.info("SSH port is open on {}:{}", hostAndPort.getHostText(), hostAndPort.getPort());
            return;
        } catch (IOException e) {
            LOG.error("Failed to connect to {}:{} (try {}/{}) - {}",
                    hostAndPort.getHostText(), hostAndPort.getPort(), i, retries, e.getMessage());
            if (i == retries) {
                throw e;
            }
        } finally {
            connection.close();
        }
        sleepFor(time, units);
    }
}
 
Example 2
Source File: PortUtils.java    From docker-plugin with MIT License 5 votes vote down vote up
private boolean executeOnce(final int thisTryNumber, final int totalTriesIntended) {
    final Connection sshConnection = new Connection(parent.host, parent.port);
    try {
        sshConnection.connect(null, sshTimeoutMillis, sshTimeoutMillis, sshTimeoutMillis);
        LOGGER.info("SSH port is open on {}:{}", parent.host, parent.port);
        return true;
    } catch (IOException e) {
        LOGGER.error("Failed to connect to {}:{} (try {}/{}) - {}", parent.host, parent.port, thisTryNumber, totalTriesIntended, e.getMessage());
        return false;
    } finally {
        sshConnection.close();
    }
}
 
Example 3
Source File: TrileadSessionFactory.java    From git-client-plugin with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public RemoteSession getSession(URIish uri, CredentialsProvider credentialsProvider, FS fs, int tms) throws TransportException {
    try {
        int p = uri.getPort();
        if (p<0)    p = 22;
        Connection con = new Connection(uri.getHost(), p);
        con.setTCPNoDelay(true);
        con.connect();  // TODO: host key check

        boolean authenticated;
        if (credentialsProvider instanceof SmartCredentialsProvider) {
            final SmartCredentialsProvider smart = (SmartCredentialsProvider) credentialsProvider;
            StandardUsernameCredentialsCredentialItem
                    item = new StandardUsernameCredentialsCredentialItem("Credentials for " + uri, false);
            authenticated = smart.supports(item)
                    && smart.get(uri, item)
                    && SSHAuthenticator.newInstance(con, item.getValue(), uri.getUser())
                    .authenticate(smart.listener);
        } else if (credentialsProvider instanceof CredentialsProviderImpl) {
            CredentialsProviderImpl sshcp = (CredentialsProviderImpl) credentialsProvider;

            authenticated = SSHAuthenticator.newInstance(con, sshcp.cred).authenticate(sshcp.listener);
        } else {
            authenticated = false;
        }
        if (!authenticated && con.isAuthenticationComplete())
            throw new TransportException("Authentication failure");

        return wrap(con);
    } catch (UnsupportedCredentialItem | IOException | InterruptedException e) {
        throw new TransportException(uri,"Failed to connect",e);
    }
}
 
Example 4
Source File: SSHData.java    From hop with Apache License 2.0 4 votes vote down vote up
public static Connection OpenConnection( String serveur, int port, String username, String password,
                                         boolean useKey, String keyFilename, String passPhrase, int timeOut, IVariables variables, String proxyhost,
                                         int proxyport, String proxyusername, String proxypassword ) throws HopException {
  Connection conn = null;
  char[] content = null;
  boolean isAuthenticated = false;
  try {
    // perform some checks
    if ( useKey ) {
      if ( Utils.isEmpty( keyFilename ) ) {
        throw new HopException( BaseMessages.getString( SSHMeta.PKG, "SSH.Error.PrivateKeyFileMissing" ) );
      }
      FileObject keyFileObject = HopVFS.getFileObject( keyFilename );

      if ( !keyFileObject.exists() ) {
        throw new HopException( BaseMessages.getString( SSHMeta.PKG, "SSH.Error.PrivateKeyNotExist", keyFilename ) );
      }

      FileContent keyFileContent = keyFileObject.getContent();

      CharArrayWriter charArrayWriter = new CharArrayWriter( (int) keyFileContent.getSize() );

      try ( InputStream in = keyFileContent.getInputStream() ) {
        IOUtils.copy( in, charArrayWriter );
      }

      content = charArrayWriter.toCharArray();
    }
    // Create a new connection
    conn = createConnection( serveur, port );

    /* We want to connect through a HTTP proxy */
    if ( !Utils.isEmpty( proxyhost ) ) {
      /* Now connect */
      // if the proxy requires basic authentication:
      if ( !Utils.isEmpty( proxyusername ) ) {
        conn.setProxyData( new HTTPProxyData( proxyhost, proxyport, proxyusername, proxypassword ) );
      } else {
        conn.setProxyData( new HTTPProxyData( proxyhost, proxyport ) );
      }
    }

    // and connect
    if ( timeOut == 0 ) {
      conn.connect();
    } else {
      conn.connect( null, 0, timeOut * 1000 );
    }
    // authenticate
    if ( useKey ) {
      isAuthenticated =
        conn.authenticateWithPublicKey( username, content, variables.environmentSubstitute( passPhrase ) );
    } else {
      isAuthenticated = conn.authenticateWithPassword( username, password );
    }
    if ( isAuthenticated == false ) {
      throw new HopException( BaseMessages.getString( SSHMeta.PKG, "SSH.Error.AuthenticationFailed", username ) );
    }
  } catch ( Exception e ) {
    // Something wrong happened
    // do not forget to disconnect if connected
    if ( conn != null ) {
      conn.close();
    }
    throw new HopException( BaseMessages.getString( SSHMeta.PKG, "SSH.Error.ErrorConnecting", serveur, username ), e );
  }
  return conn;
}
 
Example 5
Source File: ActionFtpDelete.java    From hop with Apache License 2.0 4 votes vote down vote up
private void SSHConnect( String realservername, String realserverpassword, int realserverport,
                         String realUsername, String realPassword, String realproxyhost, String realproxyusername,
                         String realproxypassword, int realproxyport, String realkeyFilename, String realkeyPass ) throws Exception {

  /* Create a connection instance */

  Connection conn = new Connection( realservername, realserverport );

  /* We want to connect through a HTTP proxy */
  if ( useproxy ) {
    conn.setProxyData( new HTTPProxyData( realproxyhost, realproxyport ) );

    /* Now connect */
    // if the proxy requires basic authentication:
    if ( !Utils.isEmpty( realproxyusername ) || !Utils.isEmpty( realproxypassword ) ) {
      conn
        .setProxyData( new HTTPProxyData( realproxyhost, realproxyport, realproxyusername, realproxypassword ) );
    }
  }

  if ( timeout > 0 ) {
    // Use timeout
    conn.connect( null, 0, timeout * 1000 );

  } else {
    // Cache Host Key
    conn.connect();
  }

  // Authenticate

  boolean isAuthenticated = false;
  if ( publicpublickey ) {
    isAuthenticated = conn.authenticateWithPublicKey( realUsername, new File( realkeyFilename ), realkeyPass );
  } else {
    isAuthenticated = conn.authenticateWithPassword( realUsername, realserverpassword );
  }

  if ( !isAuthenticated ) {
    throw new Exception( "Can not connect to " );
  }

  sshclient = new SFTPv3Client( conn );

}
 
Example 6
Source File: SshTest.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {

        // Parameters
        List<String> argsList = Arrays.asList(args);
        Iterator<String> iter = argsList.iterator();
        while (iter.hasNext()) {
            String arg = iter.next();
            if (arg.equals("-h")) {
                host = iter.next();
            }
            if (arg.equals("-p")) {
                password = iter.next();
            }

            if (arg.equals("-u")) {
                url = iter.next();
            }
        }

        if (host == null || host.equals("")) {
            s_logger.info("Did not receive a host back from test, ignoring ssh test");
            System.exit(2);
        }

        if (password == null) {
            s_logger.info("Did not receive a password back from test, ignoring ssh test");
            System.exit(2);
        }

        try {
            s_logger.info("Attempting to SSH into host " + host);
            Connection conn = new Connection(host);
            conn.connect(null, 60000, 60000);

            s_logger.info("User + ssHed successfully into host " + host);

            boolean isAuthenticated = conn.authenticateWithPassword("root", password);

            if (isAuthenticated == false) {
                s_logger.info("Authentication failed for root with password" + password);
                System.exit(2);
            }

            String linuxCommand = "wget " + url;
            Session sess = conn.openSession();
            sess.execCommand(linuxCommand);
            sess.close();
            conn.close();

        } catch (Exception e) {
            s_logger.error("SSH test fail with error", e);
            System.exit(2);
        }
    }
 
Example 7
Source File: StressTestDirectAttach.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
private static String sshWinTest(String host) {
    if (host == null) {
        s_logger.info("Did not receive a host back from test, ignoring win ssh test");
        return null;
    }

    // We will retry 5 times before quitting
    int retry = 1;

    while (true) {
        try {
            if (retry > 0) {
                s_logger.info("Retry attempt : " + retry + " ...sleeping 300 seconds before next attempt. Account is " + s_account.get());
                Thread.sleep(300000);
            }

            s_logger.info("Attempting to SSH into windows host " + host + " with retry attempt: " + retry + " for account " + s_account.get());

            Connection conn = new Connection(host);
            conn.connect(null, 60000, 60000);

            s_logger.info("User " + s_account.get() + " ssHed successfully into windows host " + host);
            boolean success = false;
            boolean isAuthenticated = conn.authenticateWithPassword("Administrator", "password");
            if (isAuthenticated == false) {
                return "Authentication failed";
            } else {
                s_logger.info("Authentication is successfull");
            }

            try {
                SCPClient scp = new SCPClient(conn);
                scp.put("wget.exe", "wget.exe", "C:\\Users\\Administrator", "0777");
                s_logger.info("Successfully put wget.exe file");
            } catch (Exception ex) {
                s_logger.error("Unable to put wget.exe " + ex);
            }

            if (conn == null) {
                s_logger.error("Connection is null");
            }
            Session sess = conn.openSession();

            s_logger.info("User + " + s_account.get() + " executing : wget http://192.168.1.250/dump.bin");
            sess.execCommand("wget http://192.168.1.250/dump.bin && dir dump.bin");

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

            byte[] buffer = new byte[8192];
            while (true) {
                if ((stdout.available() == 0) && (stderr.available() == 0)) {
                    int conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF, 120000);

                    if ((conditions & ChannelCondition.TIMEOUT) != 0) {
                        s_logger.info("Timeout while waiting for data from peer.");
                        return null;
                    }

                    if ((conditions & ChannelCondition.EOF) != 0) {
                        if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
                            break;
                        }
                    }
                }

                while (stdout.available() > 0) {
                    success = true;
                    int len = stdout.read(buffer);
                    if (len > 0) // this check is somewhat paranoid
                        s_logger.info(new String(buffer, 0, len));
                }

                while (stderr.available() > 0) {
                    /* int len = */stderr.read(buffer);
                }
            }
            sess.close();
            conn.close();

            if (success) {
                Thread.sleep(120000);
                return null;
            } else {
                retry++;
                if (retry == MAX_RETRY_WIN) {
                    return "SSH Windows Network test fail for account " + s_account.get();
                }
            }
        } catch (Exception e) {
            s_logger.error(e);
            retry++;
            if (retry == MAX_RETRY_WIN) {
                return "SSH Windows Network test fail with error " + e.getMessage();
            }
        }
    }
}
 
Example 8
Source File: TestClientWithAPI.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
private static String sshWinTest(String host) {
    if (host == null) {
        s_logger.info("Did not receive a host back from test, ignoring win ssh test");
        return null;
    }

    // We will retry 5 times before quitting
    int retry = 1;

    while (true) {
        try {
            if (retry > 0) {
                s_logger.info("Retry attempt : " + retry + " ...sleeping 300 seconds before next attempt. Account is " + s_account.get());
                Thread.sleep(300000);
            }

            s_logger.info("Attempting to SSH into windows host " + host + " with retry attempt: " + retry + " for account " + s_account.get());

            Connection conn = new Connection(host);
            conn.connect(null, 60000, 60000);

            s_logger.info("User " + s_account.get() + " ssHed successfully into windows host " + host);
            boolean success = false;
            boolean isAuthenticated = conn.authenticateWithPassword("Administrator", "password");
            if (isAuthenticated == false) {
                return "Authentication failed";
            } else {
                s_logger.info("Authentication is successfull");
            }

            try {
                SCPClient scp = new SCPClient(conn);
                scp.put("wget.exe", "wget.exe", "C:\\Users\\Administrator", "0777");
                s_logger.info("Successfully put wget.exe file");
            } catch (Exception ex) {
                s_logger.error("Unable to put wget.exe " + ex);
            }

            if (conn == null) {
                s_logger.error("Connection is null");
            }
            Session sess = conn.openSession();

            s_logger.info("User + " + s_account.get() + " executing : wget http://" + downloadUrl);
            String downloadCommand = "wget http://" + downloadUrl + " && dir dump.bin";
            sess.execCommand(downloadCommand);

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

            byte[] buffer = new byte[8192];
            while (true) {
                if ((stdout.available() == 0) && (stderr.available() == 0)) {
                    int conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF, 120000);

                    if ((conditions & ChannelCondition.TIMEOUT) != 0) {
                        s_logger.info("Timeout while waiting for data from peer.");
                        return null;
                    }

                    if ((conditions & ChannelCondition.EOF) != 0) {
                        if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
                            break;
                        }
                    }
                }

                while (stdout.available() > 0) {
                    success = true;
                    int len = stdout.read(buffer);
                    if (len > 0) // this check is somewhat paranoid
                        s_logger.info(new String(buffer, 0, len));
                }

                while (stderr.available() > 0) {
                    /* int len = */stderr.read(buffer);
                }
            }
            sess.close();
            conn.close();

            if (success) {
                return null;
            } else {
                retry++;
                if (retry == MAX_RETRY_WIN) {
                    return "SSH Windows Network test fail for account " + s_account.get();
                }
            }
        } catch (Exception e) {
            s_logger.error(e);
            retry++;
            if (retry == MAX_RETRY_WIN) {
                return "SSH Windows Network test fail with error " + e.getMessage();
            }
        }
    }
}
 
Example 9
Source File: GuestNetwork.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
    NDC.push("Following thread has started" + Thread.currentThread().getName());
    int retry = 0;

    //Start copying files between machines in the network
    s_logger.info("The size of the array is " + this.virtualMachines.size());
    while (true) {
        try {
            if (retry > 0) {
                s_logger.info("Retry attempt : " + retry + " ...sleeping 120 seconds before next attempt");
                Thread.sleep(120000);
            }
            for (VirtualMachine vm : this.virtualMachines) {

                s_logger.info("Attempting to SSH into linux host " + this.publicIp + " with retry attempt: " + retry);
                Connection conn = new Connection(this.publicIp);
                conn.connect(null, 600000, 600000);

                s_logger.info("SSHed successfully into linux host " + this.publicIp);

                boolean isAuthenticated = conn.authenticateWithPassword("root", "password");

                if (isAuthenticated == false) {
                    s_logger.info("Authentication failed");
                }
                //execute copy command
                Session sess = conn.openSession();
                String fileName;
                Random ran = new Random();
                fileName = Math.abs(ran.nextInt()) + "-file";
                String copyCommand = new String("./scpScript " + vm.getPrivateIp() + " " + fileName);
                s_logger.info("Executing " + copyCommand);
                sess.execCommand(copyCommand);
                Thread.sleep(120000);
                sess.close();

                //execute wget command
                sess = conn.openSession();
                String downloadCommand =
                    new String("wget http://172.16.0.220/scripts/checkDiskSpace.sh; chmod +x *sh; ./checkDiskSpace.sh; rm -rf checkDiskSpace.sh");
                s_logger.info("Executing " + downloadCommand);
                sess.execCommand(downloadCommand);
                Thread.sleep(120000);
                sess.close();

                //close the connection
                conn.close();
            }
        } catch (Exception ex) {
            s_logger.error(ex);
            retry++;
            if (retry == retryNum) {
                s_logger.info("Performance Guest Network test failed with error " + ex.getMessage());
            }
        }
    }

}
 
Example 10
Source File: ConfigTest.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
@Override
public boolean executeTest() {

    int error = 0;
    Element rootElement = this.getInputFile().get(0).getDocumentElement();
    NodeList commandLst = rootElement.getElementsByTagName("command");

    //Analyze each command, send request and build the array list of api commands
    for (int i = 0; i < commandLst.getLength(); i++) {
        Node fstNode = commandLst.item(i);
        Element fstElmnt = (Element)fstNode;

        //new command
        ApiCommand api = new ApiCommand(fstElmnt, this.getParam(), this.getCommands());

        if (api.getName().equals("rebootManagementServer")) {

            s_logger.info("Attempting to SSH into management server " + this.getParam().get("hostip"));
            try {
                Connection conn = new Connection(this.getParam().get("hostip"));
                conn.connect(null, 60000, 60000);

                s_logger.info("SSHed successfully into management server " + this.getParam().get("hostip"));

                boolean isAuthenticated = conn.authenticateWithPassword("root", "password");

                if (isAuthenticated == false) {
                    s_logger.info("Authentication failed for root with password");
                    return false;
                }

                String restartCommand = "service cloud-management restart; service cloud-usage restart";
                Session sess = conn.openSession();
                s_logger.info("Executing : " + restartCommand);
                sess.execCommand(restartCommand);
                Thread.sleep(120000);
                sess.close();
                conn.close();

            } catch (Exception ex) {
                s_logger.error(ex);
                return false;
            }
        } else {
            //send a command
            api.sendCommand(this.getClient(), null);

            //verify the response of the command
            if ((api.getResponseType() == ResponseType.ERROR) && (api.getResponseCode() == 200) && (api.getTestCaseInfo() != null)) {
                s_logger.error("Test case " + api.getTestCaseInfo() +
                    "failed. Command that was supposed to fail, passed. The command was sent with the following url " + api.getUrl());
                error++;
            } else if ((api.getResponseType() != ResponseType.ERROR) && (api.getResponseCode() == 200)) {
                //set parameters for the future use
                if (api.setParam(this.getParam()) == false) {
                    s_logger.error("Exiting the test...Command " + api.getName() +
                        " didn't return parameters needed for the future use. The command was sent with url " + api.getUrl());
                    return false;
                } else {
                    //verify parameters
                    if (api.verifyParam() == false) {
                        s_logger.error("Command " + api.getName() + " failed. Verification for returned parameters failed. Command was sent with url " + api.getUrl());
                        error++;
                    } else if (api.getTestCaseInfo() != null) {
                        s_logger.info("Test case " + api.getTestCaseInfo() + " passed. Command was sent with the url " + api.getUrl());
                    }
                }
            } else if ((api.getResponseType() != ResponseType.ERROR) && (api.getResponseCode() != 200)) {
                s_logger.error("Command " + api.getName() + " failed with an error code " + api.getResponseCode() + " . Command was sent with url  " + api.getUrl() +
                    " Required: " + api.getRequired());
                if (api.getRequired() == true) {
                    s_logger.info("The command is required for the future use, so exiging");
                    return false;
                }
                error++;
            } else if (api.getTestCaseInfo() != null) {
                s_logger.info("Test case " + api.getTestCaseInfo() + " passed. Command that was supposed to fail, failed - test passed. Command was sent with url " +
                    api.getUrl());
            }
        }
    }
    if (error != 0)
        return false;
    else
        return true;
}
 
Example 11
Source File: JobEntryFTPDelete.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
private void SSHConnect( String realservername, String realserverpassword, int realserverport,
  String realUsername, String realPassword, String realproxyhost, String realproxyusername,
  String realproxypassword, int realproxyport, String realkeyFilename, String realkeyPass ) throws Exception {

  /* Create a connection instance */

  Connection conn = new Connection( realservername, realserverport );

  /* We want to connect through a HTTP proxy */
  if ( useproxy ) {
    conn.setProxyData( new HTTPProxyData( realproxyhost, realproxyport ) );

    /* Now connect */
    // if the proxy requires basic authentication:
    if ( !Utils.isEmpty( realproxyusername ) || !Utils.isEmpty( realproxypassword ) ) {
      conn
        .setProxyData( new HTTPProxyData( realproxyhost, realproxyport, realproxyusername, realproxypassword ) );
    }
  }

  if ( timeout > 0 ) {
    // Use timeout
    conn.connect( null, 0, timeout * 1000 );

  } else {
    // Cache Host Key
    conn.connect();
  }

  // Authenticate

  boolean isAuthenticated = false;
  if ( publicpublickey ) {
    isAuthenticated = conn.authenticateWithPublicKey( realUsername, new File( realkeyFilename ), realkeyPass );
  } else {
    isAuthenticated = conn.authenticateWithPassword( realUsername, realserverpassword );
  }

  if ( !isAuthenticated ) {
    throw new Exception( "Can not connect to " );
  }

  sshclient = new SFTPv3Client( conn );

}
 
Example 12
Source File: SSHData.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
public static Connection OpenConnection( String serveur, int port, String username, String password,
    boolean useKey, String keyFilename, String passPhrase, int timeOut, VariableSpace space, String proxyhost,
    int proxyport, String proxyusername, String proxypassword ) throws KettleException {
  Connection conn = null;
  char[] content = null;
  boolean isAuthenticated = false;
  try {
    // perform some checks
    if ( useKey ) {
      if ( Utils.isEmpty( keyFilename ) ) {
        throw new KettleException( BaseMessages.getString( SSHMeta.PKG, "SSH.Error.PrivateKeyFileMissing" ) );
      }
      FileObject keyFileObject = KettleVFS.getFileObject( keyFilename );

      if ( !keyFileObject.exists() ) {
        throw new KettleException( BaseMessages.getString( SSHMeta.PKG, "SSH.Error.PrivateKeyNotExist", keyFilename ) );
      }

      FileContent keyFileContent = keyFileObject.getContent();

      CharArrayWriter charArrayWriter = new CharArrayWriter( (int) keyFileContent.getSize() );

      try ( InputStream in = keyFileContent.getInputStream() ) {
        IOUtils.copy( in, charArrayWriter );
      }

      content = charArrayWriter.toCharArray();
    }
    // Create a new connection
    conn = createConnection( serveur, port );

    /* We want to connect through a HTTP proxy */
    if ( !Utils.isEmpty( proxyhost ) ) {
      /* Now connect */
      // if the proxy requires basic authentication:
      if ( !Utils.isEmpty( proxyusername ) ) {
        conn.setProxyData( new HTTPProxyData( proxyhost, proxyport, proxyusername, proxypassword ) );
      } else {
        conn.setProxyData( new HTTPProxyData( proxyhost, proxyport ) );
      }
    }

    // and connect
    if ( timeOut == 0 ) {
      conn.connect();
    } else {
      conn.connect( null, 0, timeOut * 1000 );
    }
    // authenticate
    if ( useKey ) {
      isAuthenticated =
        conn.authenticateWithPublicKey( username, content, space.environmentSubstitute( passPhrase ) );
    } else {
      isAuthenticated = conn.authenticateWithPassword( username, password );
    }
    if ( isAuthenticated == false ) {
      throw new KettleException( BaseMessages.getString( SSHMeta.PKG, "SSH.Error.AuthenticationFailed", username ) );
    }
  } catch ( Exception e ) {
    // Something wrong happened
    // do not forget to disconnect if connected
    if ( conn != null ) {
      conn.close();
    }
    throw new KettleException( BaseMessages.getString( SSHMeta.PKG, "SSH.Error.ErrorConnecting", serveur, username ), e );
  }
  return conn;
}