Search in sources :

Example 31 with Session

use of ch.ethz.ssh2.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 32 with Session

use of ch.ethz.ssh2.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 33 with Session

use of ch.ethz.ssh2.Session in project google-cloud-java by GoogleCloudPlatform.

the class SessionImplTest method setUp.

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    SpannerImpl spanner = new SpannerImpl(rpc, 1, null);
    String dbName = "projects/p1/instances/i1/databases/d1";
    String sessionName = dbName + "/sessions/s1";
    DatabaseId db = DatabaseId.of(dbName);
    Session sessionProto = Session.newBuilder().setName(sessionName).build();
    Mockito.when(rpc.createSession(Mockito.eq(dbName), optionsCaptor.capture())).thenReturn(sessionProto);
    session = spanner.createSession(db);
    // We expect the same options, "options", on all calls on "session".
    options = optionsCaptor.getValue();
    Mockito.reset(rpc);
}
Also used : ByteString(com.google.protobuf.ByteString) Session(com.google.spanner.v1.Session) Before(org.junit.Before)

Example 34 with Session

use of ch.ethz.ssh2.Session in project neo4j by neo4j.

the class BoltFailuresIT method throwsWhenRunMessageFails.

private void throwsWhenRunMessageFails(Consumer<ThrowingSessionMonitor> monitorSetup) {
    ThrowingSessionMonitor sessionMonitor = new ThrowingSessionMonitor();
    Monitors monitors = newMonitorsSpy(sessionMonitor);
    db = startTestDb(monitors);
    driver = createDriver();
    Session session = driver.session();
    // setup monitor to throw before running the query to make processing of the RUN message fail
    monitorSetup.accept(sessionMonitor);
    session.run("CREATE ()");
    try {
        session.close();
        fail("Exception expected");
    } catch (Exception e) {
        assertThat(e, instanceOf(ConnectionFailureException.class));
    }
}
Also used : Monitors(org.neo4j.kernel.monitoring.Monitors) ConnectionFailureException(org.neo4j.driver.v1.exceptions.ConnectionFailureException) Session(org.neo4j.driver.v1.Session)

Example 35 with Session

use of ch.ethz.ssh2.Session in project neo4j by neo4j.

the class BoltFailuresIT method throwsWhenInitMessageFails.

private void throwsWhenInitMessageFails(Consumer<ThrowingSessionMonitor> monitorSetup, boolean shouldBeAbleToGetSession) {
    ThrowingSessionMonitor sessionMonitor = new ThrowingSessionMonitor();
    monitorSetup.accept(sessionMonitor);
    Monitors monitors = newMonitorsSpy(sessionMonitor);
    db = startTestDb(monitors);
    driver = createDriver();
    try (Session session = driver.session()) {
        if (shouldBeAbleToGetSession) {
            session.run("CREATE ()").consume();
        } else {
            fail("Exception expected");
        }
    } catch (Exception e) {
        assertThat(e, instanceOf(ConnectionFailureException.class));
    }
}
Also used : Monitors(org.neo4j.kernel.monitoring.Monitors) ConnectionFailureException(org.neo4j.driver.v1.exceptions.ConnectionFailureException) Session(org.neo4j.driver.v1.Session)

Aggregations

Session (com.trilead.ssh2.Session)35 Connection (com.trilead.ssh2.Connection)31 IOException (java.io.IOException)25 InputStream (java.io.InputStream)24 Session (org.neo4j.driver.v1.Session)16 Test (org.junit.Test)15 Driver (org.neo4j.driver.v1.Driver)14 CoreClusterMember (org.neo4j.causalclustering.discovery.CoreClusterMember)9 RoutingNetworkSession (org.neo4j.driver.internal.RoutingNetworkSession)9 CloudRuntimeException (com.cloud.utils.exception.CloudRuntimeException)8 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 HttpException (org.apache.commons.httpclient.HttpException)8 SCPClient (com.trilead.ssh2.SCPClient)6 Session (ch.ethz.ssh2.Session)5 StreamGobbler (com.trilead.ssh2.StreamGobbler)5 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)5 Transaction (org.neo4j.driver.v1.Transaction)5 Record (org.neo4j.driver.v1.Record)4 SessionExpiredException (org.neo4j.driver.v1.exceptions.SessionExpiredException)4 BufferedReader (java.io.BufferedReader)3