Search in sources :

Example 86 with Connection

use of org.geotoolkit.sml.xml.v100.Connection in project cosmic by MissionCriticalCloud.

the class SshHelper method sshExecute.

public static Pair<Boolean, String> sshExecute(final String host, final int port, final String user, final File pemKeyFile, final String password, final String command, final int connectTimeoutInMs, final int kexTimeoutInMs, final int waitResultTimeoutInMs) throws Exception {
    com.trilead.ssh2.Connection conn = null;
    com.trilead.ssh2.Session sess = null;
    try {
        conn = new com.trilead.ssh2.Connection(host, port);
        conn.connect(null, connectTimeoutInMs, kexTimeoutInMs);
        if (pemKeyFile == null) {
            if (!conn.authenticateWithPassword(user, password)) {
                final String msg = "Failed to authentication SSH user " + user + " on host " + host;
                s_logger.error(msg);
                throw new Exception(msg);
            }
        } else {
            if (!conn.authenticateWithPublicKey(user, pemKeyFile, password)) {
                final String msg = "Failed to authentication SSH user " + user + " on host " + host;
                s_logger.error(msg);
                throw new Exception(msg);
            }
        }
        sess = openConnectionSession(conn);
        sess.execCommand(command);
        final InputStream stdout = sess.getStdout();
        final InputStream stderr = sess.getStderr();
        final byte[] buffer = new byte[8192];
        final StringBuffer sbResult = new StringBuffer();
        int currentReadBytes = 0;
        while (true) {
            throwSshExceptionIfStdoutOrStdeerIsNull(stdout, stderr);
            if ((stdout.available() == 0) && (stderr.available() == 0)) {
                final int conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA | ChannelCondition.EOF | ChannelCondition.EXIT_STATUS, waitResultTimeoutInMs);
                throwSshExceptionIfConditionsTimeout(conditions);
                if ((conditions & ChannelCondition.EXIT_STATUS) != 0) {
                    break;
                }
                if (canEndTheSshConnection(waitResultTimeoutInMs, sess, conditions)) {
                    break;
                }
            }
            while (stdout.available() > 0) {
                currentReadBytes = stdout.read(buffer);
                sbResult.append(new String(buffer, 0, currentReadBytes));
            }
            while (stderr.available() > 0) {
                currentReadBytes = stderr.read(buffer);
                sbResult.append(new String(buffer, 0, currentReadBytes));
            }
        }
        final String result = sbResult.toString();
        if (sess.getExitStatus() == null) {
            // Exit status is NOT available. Returning failure result.
            s_logger.error(String.format("SSH execution of command %s has no exit status set. Result output: %s", command, result));
            return new Pair<>(false, result);
        }
        if (sess.getExitStatus() != null && sess.getExitStatus().intValue() != 0) {
            s_logger.error(String.format("SSH execution of command %s has an error status code in return. Result output: %s", command, result));
            return new Pair<>(false, result);
        }
        return new Pair<>(true, result);
    } finally {
        if (sess != null) {
            sess.close();
        }
        if (conn != null) {
            conn.close();
        }
    }
}
Also used : Session(com.trilead.ssh2.Session) InputStream(java.io.InputStream) Connection(com.trilead.ssh2.Connection) IOException(java.io.IOException) Pair(com.cloud.legacymodel.utils.Pair)

Example 87 with Connection

use of org.geotoolkit.sml.xml.v100.Connection in project cosmic by MissionCriticalCloud.

the class SshHelperTest method openConnectionSessionTest.

@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();
}
Also used : Connection(com.trilead.ssh2.Connection) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 88 with Connection

use of org.geotoolkit.sml.xml.v100.Connection in project new-cloud by xie-summer.

the class SSHTemplate method getConnection.

/**
 * 获取连接并校验
 * @param ip
 * @param port
 * @param username
 * @param password
 * @return Connection
 * @throws Exception
 */
private Connection getConnection(String ip, int port, String username, String password) throws Exception {
    Connection conn = new Connection(ip, port);
    conn.connect(null, CONNCET_TIMEOUT, CONNCET_TIMEOUT);
    boolean isAuthenticated = conn.authenticateWithPassword(username, password);
    if (isAuthenticated == false) {
        throw new Exception("SSH authentication failed with [ userName: " + username + ", password: " + password + "]");
    }
    return conn;
}
Also used : Connection(ch.ethz.ssh2.Connection) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) SSHException(com.sohu.cache.exception.SSHException)

Example 89 with Connection

use of org.geotoolkit.sml.xml.v100.Connection in project ovirt-engine-sdk-java by oVirt.

the class DiscoverIscsi method main.

public static void main(String[] args) throws Exception {
    // Create the connection to the server:
    Connection connection = connection().url("https://engine40.example.com/ovirt-engine/api").user("admin@internal").password("redhat123").trustStoreFile("truststore.jks").build();
    // Get the reference to the hosts service:
    HostsService hostsService = connection.systemService().hostsService();
    // Find the host:
    Host host = hostsService.list().search("name=myhost").send().hosts().get(0);
    // Locate the service that manages the host, as that is where the action methods are defined:
    HostService hostService = hostsService.hostService(host.id());
    // Call the "iscsiDiscover" method of the service to start it:
    HostService.DiscoverIscsiResponse response = hostService.discoverIscsi().iscsi(iscsiDetails().address("myaddress")).send();
    // Print only address corresponding to target:
    for (IscsiDetails detail : response.discoveredTargets()) {
        System.out.println(detail.address() + ":" + detail.target());
    }
    // Close the connection to the server:
    connection.close();
}
Also used : HostService(org.ovirt.engine.sdk4.services.HostService) IscsiDetails(org.ovirt.engine.sdk4.types.IscsiDetails) Connection(org.ovirt.engine.sdk4.Connection) HostsService(org.ovirt.engine.sdk4.services.HostsService) Host(org.ovirt.engine.sdk4.types.Host)

Example 90 with Connection

use of org.geotoolkit.sml.xml.v100.Connection in project ovirt-engine-sdk-java by oVirt.

the class GetDisplayTicket method main.

public static void main(String[] args) throws Exception {
    // Create the connection to the server:
    Connection connection = connection().url("https://engine40.example.com/ovirt-engine/api").user("admin@internal").password("redhat123").trustStoreFile("truststore.jks").build();
    // Get the reference to the root of the tree of services:
    SystemService systemService = connection.systemService();
    // Find the virtual machine:
    VmsService vmsService = systemService.vmsService();
    Vm vm = vmsService.list().search("name=myvm").send().vms().get(0);
    // Find the service that manages the graphics consoles of the virtual machine:
    VmService vmService = vmsService.vmService(vm.id());
    VmGraphicsConsolesService consolesService = vmService.graphicsConsolesService();
    // The method that lists the graphics consoles doesn't support search, so in order to find the console
    // corresponding to the access protocol that we are interested on (SPICE in this example) we need to get all of
    // them and filter explicitly. In addition the `current` parameter must be `true`, as otherwise you will *not*
    // get important values like the `address` and `port` where the console is available.
    List<GraphicsConsole> consoles = consolesService.list().current(true).send().consoles();
    GraphicsConsole console = null;
    for (GraphicsConsole c : consoles) {
        if (c.protocol() == GraphicsType.SPICE) {
            console = c;
            break;
        }
    }
    // Find the service that manages the graphics console that was selected in the previous step:
    VmGraphicsConsoleService consoleService = consolesService.consoleService(console.id());
    // Request the ticket. The virtual machine must be up and running, as it doesn't make sense to get a console
    // ticket for a virtual machine that is down. If you try that, the request will fail.
    Ticket ticket = consoleService.ticket().send().ticket();
    // Print the details needed to connect to the console (the ticket value is the password):
    System.out.printf("address: %s\n", console.address());
    System.out.printf("port: %d\n", console.port());
    System.out.printf("tls_port: %d\n", console.tlsPort());
    System.out.printf("password: %s\n", ticket.value());
    // Close the connection to the server:
    connection.close();
}
Also used : Ticket(org.ovirt.engine.sdk4.types.Ticket) SystemService(org.ovirt.engine.sdk4.services.SystemService) VmGraphicsConsolesService(org.ovirt.engine.sdk4.services.VmGraphicsConsolesService) VmGraphicsConsoleService(org.ovirt.engine.sdk4.services.VmGraphicsConsoleService) Vm(org.ovirt.engine.sdk4.types.Vm) VmService(org.ovirt.engine.sdk4.services.VmService) Connection(org.ovirt.engine.sdk4.Connection) VmsService(org.ovirt.engine.sdk4.services.VmsService) GraphicsConsole(org.ovirt.engine.sdk4.types.GraphicsConsole)

Aggregations

IOException (java.io.IOException)68 Connection (org.ovirt.engine.sdk4.Connection)64 Connection (com.trilead.ssh2.Connection)61 Connection (org.osate.aadl2.Connection)57 Session (com.trilead.ssh2.Session)33 Connection (org.jboss.remoting3.Connection)33 Connection (com.google.cloud.bigquery.connection.v1.Connection)31 Test (org.junit.Test)30 VmsService (org.ovirt.engine.sdk4.services.VmsService)30 Vm (org.ovirt.engine.sdk4.types.Vm)30 InputStream (java.io.InputStream)29 Connection (okhttp3.Connection)28 Connection (ch.ethz.ssh2.Connection)24 Request (okhttp3.Request)20 Subcomponent (org.osate.aadl2.Subcomponent)19 FeatureGroupConnection (org.osate.aadl2.FeatureGroupConnection)18 PortConnection (org.osate.aadl2.PortConnection)18 VmService (org.ovirt.engine.sdk4.services.VmService)18 ArrayList (java.util.ArrayList)17 Response (okhttp3.Response)17