Search in sources :

Example 16 with Session

use of iaik.pkcs.pkcs11.Session in project intellij-community by JetBrains.

the class BasicWithHTTPProxy method main.

public static void main(String[] args) {
    String hostname = "my-ssh-server";
    String username = "joe";
    String password = "joespass";
    String proxyHost = "192.168.1.1";
    // default port used by squid
    int proxyPort = 3128;
    try {
        /* Create a connection instance */
        Connection conn = new Connection(hostname);
        /* We want to connect through a HTTP proxy */
        conn.setProxyData(new HTTPProxyData(proxyHost, proxyPort));
        // if the proxy requires basic authentication:
        // conn.setProxyData(new HTTPProxyData(proxyHost, proxyPort, "username", "secret"));
        /* Now connect (through the proxy) */
        conn.connect();
        /* Authenticate.
			 * If you get an IOException saying something like
			 * "Authentication method password not supported by the server at this stage."
			 * then please check the FAQ.
			 */
        boolean isAuthenticated = conn.authenticateWithPassword(username, password);
        if (isAuthenticated == false)
            throw new IOException("Authentication failed.");
        /* Create a session */
        Session sess = conn.openSession();
        sess.execCommand("uname -a && date && uptime && who");
        System.out.println("Here is some information about the remote host:");
        /* 
			 * This basic example does not handle stderr, which is sometimes dangerous
			 * (please read the FAQ).
			 */
        InputStream stdout = new StreamGobbler(sess.getStdout());
        BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
        while (true) {
            String line = br.readLine();
            if (line == null)
                break;
            System.out.println(line);
        }
        /* Show exit status, if available (otherwise "null") */
        System.out.println("ExitCode: " + sess.getExitStatus());
        /* Close this session */
        sess.close();
        /* Close the connection */
        conn.close();
    } catch (IOException e) {
        e.printStackTrace(System.err);
        System.exit(2);
    }
}
Also used : StreamGobbler(com.trilead.ssh2.StreamGobbler) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Connection(com.trilead.ssh2.Connection) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) HTTPProxyData(com.trilead.ssh2.HTTPProxyData) Session(com.trilead.ssh2.Session)

Example 17 with Session

use of iaik.pkcs.pkcs11.Session in project intellij-community by JetBrains.

the class SingleThreadStdoutStderr method main.

public static void main(String[] args) {
    String hostname = "127.0.0.1";
    String username = "joe";
    String password = "joespass";
    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 \"Huge amounts of text on STDOUT\"; echo \"Huge amounts of text on STDERR\" >&2");
        /*
			 * Advanced:
			 * The following is a demo on how one can read from stdout and
			 * stderr without having to use two parallel worker threads (i.e.,
			 * we don't use the Streamgobblers here) and at the same time not
			 * risking a deadlock (due to a filled SSH2 channel window, caused
			 * by the stream which you are currently NOT reading from =).
			 */
        /* Don't wrap these streams and don't let other threads work on
			 * these streams while you work with Session.waitForCondition()!!!
			 */
        InputStream stdout = sess.getStdout();
        InputStream stderr = sess.getStderr();
        byte[] buffer = new byte[8192];
        while (true) {
            if ((stdout.available() == 0) && (stderr.available() == 0)) {
                /* Even though currently there is no data available, it may be that new data arrives
					 * and the session's underlying channel is closed before we call waitForCondition().
					 * This means that EOF and STDOUT_DATA (or STDERR_DATA, or both) may
					 * be set together.
					 */
                int conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF, 2000);
                if ((conditions & ChannelCondition.TIMEOUT) != 0) {
                    /* A timeout occured. */
                    throw new IOException("Timeout while waiting for data from peer.");
                }
                if ((conditions & ChannelCondition.EOF) != 0) {
                    if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) {
                        /* ... and we have consumed all data in the local arrival window. */
                        break;
                    }
                }
            /* OK, either STDOUT_DATA or STDERR_DATA (or both) is set. */
            // You can be paranoid and check that the library is not going nuts:
            // if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0)
            //	throw new IllegalStateException("Unexpected condition result (" + conditions + ")");
            }
            while (stdout.available() > 0) {
                int len = stdout.read(buffer);
                if (// this check is somewhat paranoid
                len > 0)
                    System.out.write(buffer, 0, len);
            }
            while (stderr.available() > 0) {
                int len = stderr.read(buffer);
                if (// this check is somewhat paranoid
                len > 0)
                    System.err.write(buffer, 0, len);
            }
        }
        /* Close this session */
        sess.close();
        /* Close the connection */
        conn.close();
    } catch (IOException e) {
        e.printStackTrace(System.err);
        System.exit(2);
    }
}
Also used : InputStream(java.io.InputStream) Connection(com.trilead.ssh2.Connection) IOException(java.io.IOException) Session(com.trilead.ssh2.Session)

Example 18 with Session

use of iaik.pkcs.pkcs11.Session in project intellij-community by JetBrains.

the class StdoutAndStderr method main.

public static void main(String[] args) {
    String hostname = "127.0.0.1";
    String username = "joe";
    String password = "joespass";
    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);
    }
}
Also used : StreamGobbler(com.trilead.ssh2.StreamGobbler) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Connection(com.trilead.ssh2.Connection) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) Session(com.trilead.ssh2.Session)

Example 19 with Session

use of iaik.pkcs.pkcs11.Session in project zm-mailbox by Zimbra.

the class RemoteManager method execute.

public synchronized RemoteResult execute(String command) throws ServiceException {
    Session s = null;
    try {
        s = getSession();
        if (ZimbraLog.rmgmt.isDebugEnabled())
            ZimbraLog.rmgmt.debug("executing shim command  '" + mShimCommand + "' on " + this);
        s.execCommand(mShimCommand);
        OutputStream os = s.getStdin();
        String send = "HOST:" + mHost + " " + command;
        if (ZimbraLog.rmgmt.isDebugEnabled()) {
            ZimbraLog.rmgmt.debug("sending mgmt command '%s' on %s", send, this);
        }
        os.write(send.getBytes());
        os.close();
        RemoteResult result = new RemoteResult();
        InputStream stdout = new StreamGobbler(s.getStdout());
        InputStream stderr = new StreamGobbler(s.getStderr());
        result.mStdout = ByteUtil.getContent(stdout, -1);
        result.mStderr = ByteUtil.getContent(stderr, -1);
        if (ZimbraLog.rmgmt.isTraceEnabled()) {
            try {
                ZimbraLog.rmgmt.trace("stdout content for cmd:\n%s", new String(result.mStdout, "UTF-8"));
                ZimbraLog.rmgmt.trace("stderr content for cmd:\n%s", new String(result.mStderr, "UTF-8"));
            } catch (Exception ex) {
                ZimbraLog.rmgmt.trace("Problem logging stdout or stderr for cmd - probably not UTF-8");
            }
        }
        try {
            result.mExitStatus = s.getExitStatus();
        } catch (NullPointerException npe) {
        // wow this is strange - on hold command we hit NPE here.  TODO file a bug against ganymed
        }
        if (result.mExitStatus != 0) {
            throw new IOException("command failed: exit status=" + result.mExitStatus + ", stdout=" + new String(result.mStdout) + ", stderr=" + new String(result.mStderr));
        }
        result.mExitSignal = s.getExitSignal();
        return result;
    } catch (IOException ioe) {
        throw ServiceException.FAILURE("exception executing command: " + command + " with " + this, ioe);
    } finally {
        if (s != null) {
            releaseSession(s);
        }
    }
}
Also used : StreamGobbler(ch.ethz.ssh2.StreamGobbler) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) IOException(java.io.IOException) ServiceException(com.zimbra.common.service.ServiceException) Session(ch.ethz.ssh2.Session)

Example 20 with Session

use of iaik.pkcs.pkcs11.Session in project zm-mailbox by Zimbra.

the class RemoteManager method executeBackground0.

private synchronized void executeBackground0(String command, RemoteBackgroundHandler handler) {
    Session s = null;
    try {
        s = getSession();
        if (ZimbraLog.rmgmt.isDebugEnabled())
            ZimbraLog.rmgmt.debug("(bg) executing shim command  '" + mShimCommand + "' on " + this);
        s.execCommand(mShimCommand);
        OutputStream os = s.getStdin();
        String send = "HOST:" + mHost + " " + command;
        if (ZimbraLog.rmgmt.isDebugEnabled())
            ZimbraLog.rmgmt.debug("(bg) sending mgmt command '" + send + "' on " + this);
        os.write(send.getBytes());
        os.close();
        InputStream stdout = new StreamGobbler(s.getStdout());
        InputStream stderr = new StreamGobbler(s.getStderr());
        handler.read(stdout, stderr);
    } catch (OutOfMemoryError e) {
        Zimbra.halt("out of memory", e);
    } catch (Throwable t) {
        handler.error(t);
    } finally {
        if (s != null) {
            releaseSession(s);
        }
    }
}
Also used : StreamGobbler(ch.ethz.ssh2.StreamGobbler) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) Session(ch.ethz.ssh2.Session)

Aggregations

Session (com.trilead.ssh2.Session)42 Session (org.neo4j.driver.v1.Session)38 Connection (com.trilead.ssh2.Connection)32 IOException (java.io.IOException)29 Test (org.junit.Test)29 InputStream (java.io.InputStream)27 Driver (org.neo4j.driver.v1.Driver)27 StatementResult (org.neo4j.driver.v1.StatementResult)20 TokenException (iaik.pkcs.pkcs11.TokenException)15 P11TokenException (org.xipki.security.exception.P11TokenException)15 Record (org.neo4j.driver.v1.Record)12 Session (iaik.pkcs.pkcs11.Session)10 SecretKey (iaik.pkcs.pkcs11.objects.SecretKey)10 ValuedSecretKey (iaik.pkcs.pkcs11.objects.ValuedSecretKey)10 DSAPrivateKey (iaik.pkcs.pkcs11.objects.DSAPrivateKey)9 ECPrivateKey (iaik.pkcs.pkcs11.objects.ECPrivateKey)9 PrivateKey (iaik.pkcs.pkcs11.objects.PrivateKey)9 RSAPrivateKey (iaik.pkcs.pkcs11.objects.RSAPrivateKey)9 SM2PrivateKey (iaik.pkcs.pkcs11.objects.SM2PrivateKey)9 CoreClusterMember (org.neo4j.causalclustering.discovery.CoreClusterMember)9