com.trilead.ssh2.Connection Java Examples

The following examples show how to use com.trilead.ssh2.Connection. 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: JobEntrySSH2PUT.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
private Connection getConnection( String servername, int serverport, String proxyhost, int proxyport,
  String proxyusername, String proxypassword ) {
  /* Create a connection instance */

  Connection connect = new Connection( servername, serverport );

  /* We want to connect through a HTTP proxy */
  if ( usehttpproxy ) {
    connect.setProxyData( new HTTPProxyData( proxyhost, proxyport ) );

    /* Now connect */
    // if the proxy requires basic authentication:
    if ( useBasicAuthentication ) {
      connect.setProxyData( new HTTPProxyData( proxyhost, proxyport, proxyusername, proxypassword ) );
    }
  }

  return connect;
}
 
Example #2
Source File: JobEntrySSH2GET.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
private Connection getConnection( String servername, int serverport, String proxyhost, int proxyport,
  String proxyusername, String proxypassword ) {
  /* Create a connection instance */

  Connection conn = new Connection( servername, serverport );

  /* We want to connect through a HTTP proxy */
  if ( usehttpproxy ) {
    conn.setProxyData( new HTTPProxyData( proxyhost, proxyport ) );

    /* Now connect */
    // if the proxy requires basic authentication:
    if ( useBasicAuthentication ) {
      conn.setProxyData( new HTTPProxyData( proxyhost, proxyport, proxyusername, proxypassword ) );
    }
  }

  return conn;
}
 
Example #3
Source File: SshHelper.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public static void scpFrom(String host, int port, String user, File permKeyFile, String localTargetDirectory, String remoteTargetFile) throws Exception {
    com.trilead.ssh2.Connection conn = null;
    com.trilead.ssh2.SCPClient scpClient = null;

    try {
        conn = new com.trilead.ssh2.Connection(host, port);
        conn.connect(null, DEFAULT_CONNECT_TIMEOUT, DEFAULT_KEX_TIMEOUT);

        if (!conn.authenticateWithPublicKey(user, permKeyFile, null)) {
            String msg = "Failed to authentication SSH user " + user + " on host " + host;
            s_logger.error(msg);
            throw new Exception(msg);
        }
        scpClient = conn.createSCPClient();

        scpClient.get(remoteTargetFile, localTargetDirectory);

    } finally {
        if (conn != null) {
            conn.close();
        }
    }
}
 
Example #4
Source File: DockerComputerSSHConnector.java    From docker-plugin with MIT License 6 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item context, @QueryParameter String credentialsId) {
    if ( !hasPermission(context)) {
        return new StandardUsernameListBoxModel()
                .includeCurrentValue(credentialsId);
    }
    // Functionally the same as SSHLauncher's descriptor method, but without
    // filtering by host/port as we don't/can't know those yet.
    return new StandardUsernameListBoxModel()
            .includeMatchingAs(
                    ACL.SYSTEM,
                    context,
                    StandardUsernameCredentials.class,
                    Collections.emptyList(),
                    SSHAuthenticator.matcher(Connection.class))
            .includeCurrentValue(credentialsId);
}
 
Example #5
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 #6
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 #7
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 #8
Source File: SshHelperTest.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
@Test
public void openConnectionSessionTest() throws IOException, InterruptedException {
    Connection conn = Mockito.mock(Connection.class);
    PowerMockito.mockStatic(Thread.class);
    SshHelper.openConnectionSession(conn);

    Mockito.verify(conn).openSession();
}
 
Example #9
Source File: DockerSSHConnector.java    From yet-another-docker-plugin with MIT License 5 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context) {
    if (context instanceof AccessControlled) {
        if (!((AccessControlled) context).hasPermission(Computer.CONFIGURE)) {
            return new ListBoxModel();
        }
    } else {
        if (!Jenkins.getInstance().hasPermission(Computer.CONFIGURE)) {
            return new ListBoxModel();
        }
    }
    return new StandardUsernameListBoxModel().withMatching(SSHAuthenticator.matcher(Connection.class),
            CredentialsProvider.lookupCredentials(StandardUsernameCredentials.class, context,
                    ACL.SYSTEM, SSH_SCHEME));
}
 
Example #10
Source File: DockerCreateContainer.java    From yet-another-docker-plugin with MIT License 5 votes vote down vote up
public static ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context) {
    AccessControlled ac = (context instanceof AccessControlled ? (AccessControlled) context : Jenkins.getInstance());
    if (!ac.hasPermission(Jenkins.ADMINISTER)) {
        return new ListBoxModel();
    }

    return new SSHUserListBoxModel().withMatching(
            SSHAuthenticator.matcher(Connection.class),
            CredentialsProvider.lookupCredentials(
                    StandardUsernameCredentials.class,
                    context,
                    ACL.SYSTEM,
                    SSHLauncher.SSH_SCHEME)
    );
}
 
Example #11
Source File: SshHelperTest.java    From cosmic with Apache License 2.0 5 votes vote down vote up
@Test
public void openConnectionSessionTest() throws IOException, InterruptedException {
    final Connection conn = Mockito.mock(Connection.class);
    PowerMockito.mockStatic(Thread.class);
    SshHelper.openConnectionSession(conn);

    Mockito.verify(conn).openSession();

    PowerMockito.verifyStatic();
}
 
Example #12
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 #13
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 #14
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;
}
 
Example #15
Source File: TrileadSession.java    From git-client-plugin with MIT License 4 votes vote down vote up
public ProcessImpl(Connection con, String commandName, final int timeout) throws IOException {
    this.timeout = timeout;
    s = con.openSession();
    s.execCommand(commandName);
}
 
Example #16
Source File: SSHData.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
 static Connection createConnection( String serveur, int port ) {
  return new Connection( serveur, port );
}
 
Example #17
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 #18
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 #19
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 #20
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 #21
Source File: LibvirtServerDiscoverer.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
private void setupAgentSecurity(final Connection sshConnection, final String agentIp, final String agentHostname) {
    if (sshConnection == null) {
        throw new CloudRuntimeException("Cannot secure agent communication because ssh connection is invalid for host ip=" + agentIp);
    }

    Integer validityPeriod = CAManager.CertValidityPeriod.value();
    if (validityPeriod < 1) {
        validityPeriod = 1;
    }

    final SSHCmdHelper.SSHCmdResult keystoreSetupResult = SSHCmdHelper.sshExecuteCmdWithResult(sshConnection,
            String.format("sudo /usr/share/cloudstack-common/scripts/util/%s " +
                            "/etc/cloudstack/agent/agent.properties " +
                            "/etc/cloudstack/agent/%s " +
                            "%s %d " +
                            "/etc/cloudstack/agent/%s",
                    KeyStoreUtils.KS_SETUP_SCRIPT,
                    KeyStoreUtils.KS_FILENAME,
                    PasswordGenerator.generateRandomPassword(16),
                    validityPeriod,
                    KeyStoreUtils.CSR_FILENAME));

    if (!keystoreSetupResult.isSuccess()) {
        throw new CloudRuntimeException("Failed to setup keystore on the KVM host: " + agentIp);
    }

    final Certificate certificate = caManager.issueCertificate(keystoreSetupResult.getStdOut(), Arrays.asList(agentHostname, agentIp), Collections.singletonList(agentIp), null, null);
    if (certificate == null || certificate.getClientCertificate() == null) {
        throw new CloudRuntimeException("Failed to issue certificates for KVM host agent: " + agentIp);
    }

    final SetupCertificateCommand certificateCommand = new SetupCertificateCommand(certificate);
    final SSHCmdHelper.SSHCmdResult setupCertResult = SSHCmdHelper.sshExecuteCmdWithResult(sshConnection,
                String.format("sudo /usr/share/cloudstack-common/scripts/util/%s " +
                                "/etc/cloudstack/agent/agent.properties " +
                                "/etc/cloudstack/agent/%s %s " +
                                "/etc/cloudstack/agent/%s \"%s\" " +
                                "/etc/cloudstack/agent/%s \"%s\" " +
                                "/etc/cloudstack/agent/%s \"%s\"",
                        KeyStoreUtils.KS_IMPORT_SCRIPT,
                        KeyStoreUtils.KS_FILENAME,
                        KeyStoreUtils.SSH_MODE,
                        KeyStoreUtils.CERT_FILENAME,
                        certificateCommand.getEncodedCertificate(),
                        KeyStoreUtils.CACERT_FILENAME,
                        certificateCommand.getEncodedCaCertificates(),
                        KeyStoreUtils.PKEY_FILENAME,
                        certificateCommand.getEncodedPrivateKey()));

    if (setupCertResult != null && !setupCertResult.isSuccess()) {
        throw new CloudRuntimeException("Failed to setup certificate in the KVM agent's keystore file, please see logs and configure manually!");
    }

    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Succeeded to import certificate in the keystore for agent on the KVM host: " + agentIp + ". Agent secured and trusted.");
    }
}
 
Example #22
Source File: SshHelper.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
protected static Session openConnectionSession(Connection conn) throws IOException, InterruptedException {
    Session sess = conn.openSession();
    return sess;
}
 
Example #23
Source File: SshHelper.java    From cosmic with Apache License 2.0 4 votes vote down vote up
protected static Session openConnectionSession(final Connection conn) throws IOException {
    return conn.openSession();
}
 
Example #24
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 #25
Source File: SSHData.java    From hop with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
static Connection createConnection( String serveur, int port ) {
  return new Connection( serveur, port );
}
 
Example #26
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 #27
Source File: SSHMeta.java    From hop with Apache License 2.0 3 votes vote down vote up
/**
 * @param serveur
 * @param port
 * @param username
 * @param password
 * @param useKey
 * @param keyFilename
 * @param passPhrase
 * @param timeOut
 * @param variables
 * @param proxyhost
 * @param proxyport
 * @param proxyusername
 * @param proxypassword
 * @return
 * @throws HopException
 * @deprecated Use {@link SSHData#OpenConnection(String, int, String, String, boolean, String, String, int, IVariables, String, int, String, String)} instead
 */
@Deprecated
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 {
  return SSHData.OpenConnection( serveur, port, username, password, useKey, keyFilename, passPhrase, timeOut,
    variables, proxyhost, proxyport, proxyusername, proxypassword );
}
 
Example #28
Source File: SSHMeta.java    From pentaho-kettle with Apache License 2.0 3 votes vote down vote up
/**
 *
 * @param serveur
 * @param port
 * @param username
 * @param password
 * @param useKey
 * @param keyFilename
 * @param passPhrase
 * @param timeOut
 * @param space
 * @param proxyhost
 * @param proxyport
 * @param proxyusername
 * @param proxypassword
 * @return
 * @throws KettleException
 * @deprecated Use {@link SSHData#OpenConnection(String, int, String, String, boolean, String, String, int, VariableSpace, String, int, String, String)} instead
 */
@Deprecated
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 {
  return SSHData.OpenConnection( serveur, port, username, password, useKey, keyFilename, passPhrase, timeOut,
    space, proxyhost, proxyport, proxyusername, proxypassword );
}
 
Example #29
Source File: TrileadSessionFactory.java    From git-client-plugin with MIT License 2 votes vote down vote up
/**
 * wrap.
 *
 * @param con a {@link com.trilead.ssh2.Connection} object.
 * @return a {@link org.jenkinsci.plugins.gitclient.trilead.TrileadSession} object.
 */
protected TrileadSession wrap(Connection con) {
    return new TrileadSession(con);
}
 
Example #30
Source File: TrileadSession.java    From git-client-plugin with MIT License 2 votes vote down vote up
/**
 * Constructor for TrileadSession.
 *
 * @param con a {@link com.trilead.ssh2.Connection} object for this session's connection.
 */
public TrileadSession(Connection con) {
    this.con = con;
}