Java Examples for com.sshtools.j2ssh.SshClient

The following java examples will help you to understand the usage of com.sshtools.j2ssh.SshClient. These source code samples are taken from different open source projects.

Example 1
Project: ApprovalTests.Java-master  File: NetUtils.java View source code
/************************************************************************/
private static SftpClient sshLogin(FTPConfig config, SshClient ssh) throws IOException {
    ssh.setSocketTimeout(60000);
    ssh.connect(config.host, new IgnoreHostKeyVerification());
    PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
    pwd.setUsername(config.userName);
    pwd.setPassword(config.password);
    ssh.authenticate(pwd);
    SftpClient sftp = ssh.openSftpClient();
    return sftp;
}
Example 2
Project: RIT-CustomFunctions-master  File: SSHConnection.java View source code
/**
	 * @see com.ghc.ghTester.function#evaluate(java.lang.Object)
	 */
public Object evaluate(Object data) {
    String hostname = m_fHost.evaluateAsString(data);
    String username = m_fUsername.evaluateAsString(data);
    String password = m_fPassword.evaluateAsString(data);
    String command = m_fCommand.evaluateAsString(data);
    String stdoutTag = "";
    String stderrTag = "";
    try {
        stdoutTag = m_fStdOut.evaluateAsString(data);
        stderrTag = m_fStdErr.evaluateAsString(data);
    } catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println("Tags:" + stdoutTag + ":" + stderrTag);
    // System.out.println("stdoutTag:"+stdoutTag);
    // System.out.println("stderrTag:"+stderrTag);
    String stdout = "";
    String stderr = "";
    if (command.charAt(0) == '"') {
        command = command.substring(1, command.length() - 1);
    }
    try {
        if (EvalUtils.isString(stderrTag))
            stderrTag = EvalUtils.getString(stderrTag);
        if (EvalUtils.isString(stdoutTag))
            stdoutTag = EvalUtils.getString(stdoutTag);
        ConfigurationLoader.initialize(false);
        // Make a client connection
        SshClient ssh = new SshClient();
        ssh.setSocketTimeout(TIMEOUT);
        SshConnectionProperties properties = new SshConnectionProperties();
        properties.setHost(hostname);
        properties.setPrefPublicKey("ssh-dss");
        // Connect to the host
        ssh.connect(properties, new IgnoreHostKeyVerification());
        // Create a password authentication instance
        PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
        pwd.setUsername(username);
        pwd.setPassword(password);
        // Try the authentication
        int result = ssh.authenticate(pwd);
        // Evaluate the result
        if (result == AuthenticationProtocolState.COMPLETE) {
            // The connection is authenticated we can now do some real work!
            SessionChannelClient session = ssh.openSessionChannel();
            if (!session.requestPseudoTerminal("vt100", 80, 24, 0, 0, ""))
                System.out.println("Failed to allocate a pseudo terminal");
            // if (session.startShell()) {
            BufferedReader is = new BufferedReader(new InputStreamReader(session.getInputStream()));
            BufferedReader es = new BufferedReader(new InputStreamReader(session.getStderrInputStream()));
            OutputStream os = session.getOutputStream();
            session.executeCommand(command);
            String line = null;
            boolean readAll = false;
            while (!readAll) {
                line = null;
                line = is.readLine();
                if (line == null) {
                    readAll = true;
                    break;
                }
                stdout = stdout.concat(line) + "\n";
            }
            if (!((TagStorer) data).setTagValue(stdoutTag, stdout)) {
            // writeToConsole(data, 1, "Unable to set tag stdout");
            }
            line = null;
            readAll = false;
            while (!readAll) {
                line = null;
                line = es.readLine();
                if (line == null) {
                    readAll = true;
                    break;
                }
                stderr = stderr.concat(line) + "\n";
            }
            if (EvalUtils.isString(stderrTag))
                stderrTag = EvalUtils.getString(stderrTag);
            if (!((TagStorer) data).setTagValue(stderrTag, stderr)) {
            // writeToConsole(data, 1, "Unable to set tag stderr");
            }
            is.close();
            os.close();
            session.close();
            // } else {
            // System.out.println("Failed to start the users shell");
            // }
            ssh.disconnect();
            ssh = null;
        } else {
            stdout = "Connection to host: " + hostname + " failed \nPlease check the hostname, userid & password are correct.";
            stderr = "Connection to host: " + hostname + " failed \nPlease check the hostname, userid & password are correct.";
            if (!((TagStorer) data).setTagValue(stdoutTag, stdout)) {
            // writeToConsole(data, 1, "Unable to set tag stdout");
            }
            if (!((TagStorer) data).setTagValue(stderrTag, stderr)) {
            // writeToConsole(data, 1, "Unable to set tag stderr");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return stdout;
}
Example 3
Project: DavidResearch-master  File: SshCommand.java View source code
public boolean connect() throws IOException {
    _sshClient = new SshClient();
    ConfigurationLoader.initialize(false);
    _sshClient.setSocketTimeout(_socketTimeOut);
    SshConnectionProperties properties = new SshConnectionProperties();
    properties.setHost(_hostIp);
    properties.setPort(22);
    // properties.setPrefPublicKey("ssh-dss");
    _sshClient.connect(properties, new AlwaysAllowingConsoleKnownHostsKeyVerification());
    PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
    pwd.setUsername(_id);
    pwd.setPassword(_password);
    int result = _sshClient.authenticate(pwd);
    if (result == AuthenticationProtocolState.COMPLETE) {
        _session = _sshClient.openSessionChannel();
        _session.requestPseudoTerminal("gogrid", 200, 100, 0, 0, "");
        return true;
    } else {
        return false;
    }
}
Example 4
Project: remitt-master  File: SftpEligibility.java View source code
protected void transmit(String userName, String payload) throws Exception {
    SshClient ssh = new SshClient();
    String tempPathName = getOutputFileName(payload.getBytes());
    String host = getSftpHost(userName);
    Integer port = getSftpPort(userName);
    String sftpUser = getSftpUser(userName);
    String sftpPassword = getSftpPassword(userName);
    String sftpPath = getSftpPath(userName);
    // Perform initial connection
    ssh.connect(host, port, new IgnoreHostKeyVerification());
    // Authenticate
    PasswordAuthenticationClient passwordAuthenticationClient = new PasswordAuthenticationClient();
    passwordAuthenticationClient.setUsername(sftpUser);
    passwordAuthenticationClient.setPassword(sftpPassword);
    int result = ssh.authenticate(passwordAuthenticationClient);
    if (result != AuthenticationProtocolState.COMPLETE) {
        throw new Exception("Login to " + host + ":" + port + " " + sftpUser + "/" + sftpPassword + " failed");
    }
    // Open the SFTP channel
    SftpClient client = ssh.openSftpClient();
    if (sftpPath != null && sftpPath != "") {
        client.cd(sftpPath);
    }
    // Convert string to input stream for transfer
    ByteArrayInputStream bs = new ByteArrayInputStream(payload.getBytes());
    // Send the file
    client.put(bs, tempPathName);
    // Disconnect
    client.quit();
    ssh.disconnect();
}
Example 5
Project: iaf-master  File: FtpSession.java View source code
private void openSftpClient(String remoteDirectory) throws FtpConnectException {
    try {
        // Set the connection properties and if necessary the proxy properties
        SshConnectionProperties sshProp = new SshConnectionProperties();
        sshProp.setHost(host);
        sshProp.setPort(port);
        if (StringUtils.isNotEmpty(prefCSEncryption))
            sshProp.setPrefCSEncryption(prefCSEncryption);
        if (StringUtils.isNotEmpty(prefSCEncryption))
            sshProp.setPrefCSEncryption(prefSCEncryption);
        if (!StringUtils.isEmpty(proxyHost)) {
            sshProp.setTransportProvider(proxyTransportType);
            sshProp.setProxyHost(proxyHost);
            sshProp.setProxyPort(proxyPort);
            CredentialFactory pcf = new CredentialFactory(getProxyAuthAlias(), proxyUsername, proxyPassword);
            if (!StringUtils.isEmpty(pcf.getUsername())) {
                sshProp.setProxyUsername(pcf.getUsername());
                sshProp.setProxyPassword(pcf.getPassword());
            }
        }
        // make a secure connection with the remote host 
        sshClient = new SshClient();
        if (StringUtils.isNotEmpty(knownHostsPath)) {
            AbstractKnownHostsKeyVerification hv = null;
            if (consoleKnownHostsVerifier) {
                hv = new ConsoleKnownHostsKeyVerification(knownHostsPath);
            } else {
                hv = new SftpHostVerification(knownHostsPath);
            }
            sshClient.connect(sshProp, hv);
        } else {
            sshClient.connect(sshProp, new IgnoreHostKeyVerification());
        }
        SshAuthenticationClient sac;
        if (!isKeyboardInteractive()) {
            // pass the authentication information
            sac = getSshAuthentication();
        } else {
            // TODO: detecteren dat sshClient.getAvailableAuthMethods("ftpmsg")
            // wel keyboard-interactive terug geeft, maar geen password en dan deze methode
            // gebruiken
            final CredentialFactory credentialFactory = new CredentialFactory(getAuthAlias(), getUsername(), getPassword());
            KBIAuthenticationClient kbiAuthenticationClient = new KBIAuthenticationClient();
            kbiAuthenticationClient.setUsername(credentialFactory.getUsername());
            kbiAuthenticationClient.setKBIRequestHandler(new KBIRequestHandler() {

                public void showPrompts(String name, String instruction, KBIPrompt[] prompts) {
                    //deze 3 regels in x.zip naar Zenz gemaild, hielp ook niet
                    if (prompts == null) {
                        return;
                    }
                    for (int i = 0; i < prompts.length; i++) {
                        prompts[i].setResponse(credentialFactory.getPassword());
                    }
                }
            });
            sac = kbiAuthenticationClient;
        }
        int result = sshClient.authenticate(sac);
        if (result != AuthenticationProtocolState.COMPLETE) {
            closeSftpClient();
            throw new IOException("Could not authenticate to sftp server " + result);
        }
        // use the connection for sftp
        sftpClient = sshClient.openSftpClient();
        if (!StringUtils.isEmpty(remoteDirectory)) {
            sftpClient.cd(remoteDirectory);
        }
    } catch (Exception e) {
        closeSftpClient();
        throw new FtpConnectException(e);
    }
}