net.schmizz.sshj.connection.channel.direct.Session Java Examples

The following examples show how to use net.schmizz.sshj.connection.channel.direct.Session. 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: RaspiQuery.java    From rpicheck with MIT License 6 votes vote down vote up
@Override
public final List<ProcessBean> queryProcesses(boolean showRootProcesses)
        throws RaspiQueryException {
    LOGGER.info("Querying running processes...");
    if (client != null) {
        if (client.isConnected() && client.isAuthenticated()) {
            Session session;
            try {
                session = client.startSession();
                final Command cmd = session.exec(showRootProcesses ? PROCESS_ALL : PROCESS_NO_ROOT_CMD);
                cmd.join(30, TimeUnit.SECONDS);
                return this.parseProcesses(IOUtils.readFully(cmd.getInputStream()).toString().trim());
            } catch (IOException e) {
                throw RaspiQueryException.createTransportFailure(hostname,
                        e);
            }
        } else {
            throw new IllegalStateException(
                    "You must establish a connection first.");
        }
    } else {
        throw new IllegalStateException(
                "You must establish a connection first.");
    }
}
 
Example #2
Source File: RaspiQuery.java    From rpicheck with MIT License 6 votes vote down vote up
@Override
public final String queryDistributionName() throws RaspiQueryException {
    LOGGER.info("Querying distribution name...");
    if (client != null) {
        if (client.isConnected() && client.isAuthenticated()) {
            Session session;
            try {
                session = client.startSession();
                final Command cmd = session.exec(DISTRIBUTION_CMD);
                cmd.join(30, TimeUnit.SECONDS);
                return this.parseDistribution(IOUtils.readFully(cmd.getInputStream()).toString().trim());
            } catch (IOException e) {
                throw RaspiQueryException.createTransportFailure(hostname,
                        e);
            }
        } else {
            throw new IllegalStateException(
                    "You must establish a connection first.");
        }
    } else {
        throw new IllegalStateException(
                "You must establish a connection first.");
    }
}
 
Example #3
Source File: RaspiQuery.java    From rpicheck with MIT License 6 votes vote down vote up
@Override
public final List<DiskUsageBean> queryDiskUsage()
        throws RaspiQueryException {
    LOGGER.info("Querying disk usage...");
    if (client != null) {
        if (client.isConnected() && client.isAuthenticated()) {
            Session session;
            try {
                session = client.startSession();
                final Command cmd = session.exec(DISK_USAGE_CMD);
                cmd.join(30, TimeUnit.SECONDS);
                return this.parseDiskUsage(IOUtils
                        .readFully(cmd.getInputStream()).toString().trim());
            } catch (IOException e) {
                throw RaspiQueryException.createTransportFailure(hostname,
                        e);
            }
        } else {
            throw new IllegalStateException("You must establish a connection first.");
        }
    } else {
        throw new IllegalStateException("You must establish a connection first.");
    }
}
 
Example #4
Source File: SystemtimeQuery.java    From rpicheck with MIT License 6 votes vote down vote up
@Override
public String run() throws RaspiQueryException {
    LOGGER.debug("Querying system time via 'date --rfc-2822'.");
    try {
        Session session = getSSHClient().startSession();
        String cmdString = "date --rfc-2822";
        final Session.Command cmd = session.exec(cmdString);
        cmd.join(30, TimeUnit.SECONDS);
        String output = IOUtils.readFully(cmd.getInputStream())
                .toString();
        final String result = output.trim();
        LOGGER.debug("System time: {}", result);
        return result;
    } catch (IOException e) {
        throw RaspiQueryException.createTransportFailure(e);
    }
}
 
Example #5
Source File: SshjToolIntegrationTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups = {"Integration"})
public void testGivesUpAfterMaxRetries() throws Exception {
    final AtomicInteger callCount = new AtomicInteger();
    
    final SshTool localtool = new SshjTool(ImmutableMap.of("sshTries", 3, "host", "localhost", "privateKeyFile", "~/.ssh/id_rsa")) {
        @Override
        protected SshAction<Session> newSessionAction() {
            callCount.incrementAndGet();
            throw new RuntimeException("Simulating ssh execution failure");
        }
    };
    
    tools.add(localtool);
    try {
        localtool.execScript(ImmutableMap.<String,Object>of(), ImmutableList.of("true"));
        fail();
    } catch (SshException e) {
        if (!e.toString().contains("out of retries")) throw e;
        assertEquals(callCount.get(), 3);
    }
}
 
Example #6
Source File: SshjToolIntegrationTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test(groups = {"Integration"})
public void testReturnsOnSuccessWhenRetrying() throws Exception {
    final AtomicInteger callCount = new AtomicInteger();
    final int successOnAttempt = 2;
    final SshTool localtool = new SshjTool(ImmutableMap.of("sshTries", 3, "host", "localhost", "privateKeyFile", "~/.ssh/id_rsa")) {
        @Override
        protected SshAction<Session> newSessionAction() {
            callCount.incrementAndGet();
            if (callCount.incrementAndGet() >= successOnAttempt) {
                return super.newSessionAction();
            } else {
                throw new RuntimeException("Simulating ssh execution failure");
            }
        }
    };
    
    tools.add(localtool);
    localtool.execScript(ImmutableMap.<String,Object>of(), ImmutableList.of("true"));
    assertEquals(callCount.get(), successOnAttempt);
}
 
Example #7
Source File: NetworkInformationQuery.java    From rpicheck with MIT License 6 votes vote down vote up
/**
 * Queries the link level and signal quality of the wireless interfaces via
 * "cat /proc/net/wireless".
 *
 * @param interfaceName name of the wireless interface
 * @throws RaspiQueryException if something goes wrong
 */
private WlanBean queryWirelessInterfaceWithProcNetWireless(String interfaceName)
        throws RaspiQueryException {
    LOGGER.info("Querying wireless interface {} from /proc/net/wireless ...", interfaceName);
    Session session;
    try {
        session = getSSHClient().startSession();
        final String cmdString = "cat /proc/net/wireless";
        final Session.Command cmd = session.exec(cmdString);
        cmd.join(30, TimeUnit.SECONDS);
        String output = IOUtils.readFully(cmd.getInputStream()).toString();
        LOGGER.debug("Real output of /proc/net/wireless: \n{}",
                output);
        return this.parseProcNetWireless(output, interfaceName);
    } catch (IOException e) {
        throw RaspiQueryException.createTransportFailure(e);
    }
}
 
Example #8
Source File: NetworkInformationQuery.java    From rpicheck with MIT License 6 votes vote down vote up
private WlanBean queryWirelessInterfaceWithIwconfig(String interfaceName, String iwconfigPath) throws RaspiQueryException {
    LOGGER.info("Executing {} to query wireless interface '{}'...", iwconfigPath, interfaceName);
    Session session;
    try {
        session = getSSHClient().startSession();
        session.allocateDefaultPTY();
        final String cmdString = "LC_ALL=C " + iwconfigPath + " " + interfaceName;
        final Session.Command cmd = session.exec(cmdString);
        cmd.join(30, TimeUnit.SECONDS);
        String output = IOUtils.readFully(cmd.getInputStream())
                .toString();
        LOGGER.debug("Output of '{}': \n{}", cmdString, output);
        return this.parseIwconfigOutput(output);
    } catch (IOException e) {
        throw RaspiQueryException.createTransportFailure(e);
    }
}
 
Example #9
Source File: RaspiQuery.java    From rpicheck with MIT License 6 votes vote down vote up
/**
 * Queries the current CPU temperature.
 *
 * @param vcgencmdPath the path to vcgencmd
 * @return the temperature in Celsius
 * @throws RaspiQueryException if something goes wrong
 */
private Double queryCpuTemp(String vcgencmdPath)
        throws RaspiQueryException {
    if (client != null) {
        if (client.isConnected() && client.isAuthenticated()) {
            Session session;
            try {
                session = client.startSession();
                final String cmdString = vcgencmdPath + " measure_temp";
                final Command cmd = session.exec(cmdString);
                cmd.join(30, TimeUnit.SECONDS);
                String output = IOUtils.readFully(cmd.getInputStream()).toString();
                return this.parseTemperature(output);
            } catch (IOException e) {
                throw RaspiQueryException.createTransportFailure(hostname,
                        e);
            }
        } else {
            throw new IllegalStateException("You must establish a connection first.");
        }
    } else {
        throw new IllegalStateException("You must establish a connection first.");
    }
}
 
Example #10
Source File: NetworkInformationQuery.java    From rpicheck with MIT License 6 votes vote down vote up
/**
 * Queries which interfaces are available via "/sys/class/net". Loopback
 * interfaces are excluded.
 *
 * @return a List with all interface names (eth0, wlan0,...).
 * @throws RaspiQueryException if something goes wrong
 */
private List<String> queryInterfaceList() throws RaspiQueryException {
    LOGGER.info("Querying network interfaces...");
    Session session;
    try {
        session = getSSHClient().startSession();
        final String cmdString = "ls -1 /sys/class/net";
        final Session.Command cmd = session.exec(cmdString);
        cmd.join(30, TimeUnit.SECONDS);
        final String output = IOUtils.readFully(
                cmd.getInputStream()).toString();
        final String[] lines = output.split("\n");
        final List<String> interfaces = new ArrayList<String>();
        for (String interfaceLine : lines) {
            if (!interfaceLine.startsWith("lo")) {
                LOGGER.debug("Found interface {}.", interfaceLine);
                interfaces.add(interfaceLine);
            }
        }
        return interfaces;
    } catch (IOException e) {
        throw RaspiQueryException.createTransportFailure(e);
    }
}
 
Example #11
Source File: NetworkInformationQuery.java    From rpicheck with MIT License 6 votes vote down vote up
/**
 * Checks if the specified interface has a carrier up and running via
 * "cat /sys/class/net/[interface]/carrier".
 *
 * @param interfaceName the interface to check
 * @return true, when the interface has a carrier up and running
 * @throws RaspiQueryException if something goes wrong
 */
private boolean checkCarrier(String interfaceName)
        throws RaspiQueryException {
    LOGGER.info("Checking carrier of {}...", interfaceName);
    Session session;
    try {
        session = getSSHClient().startSession();
        final String cmdString = "cat /sys/class/net/" + interfaceName + "/carrier";
        final Session.Command cmd = session.exec(cmdString);
        cmd.join(30, TimeUnit.SECONDS);
        final String output = IOUtils.readFully(cmd.getInputStream()).toString();
        if (output.contains("1")) {
            LOGGER.debug("{} has a carrier up and running.",
                    interfaceName);
            return true;
        } else {
            LOGGER.debug("{} has no carrier.", interfaceName);
            return false;
        }
    } catch (IOException e) {
        throw RaspiQueryException.createTransportFailure(e);
    }
}
 
Example #12
Source File: FirmwareQuery.java    From rpicheck with MIT License 6 votes vote down vote up
@Override
public String run() throws RaspiQueryException {
    LOGGER.debug("Querying firmware version, vcgencmd path={}", this.vcgencmdPath);
    try {
        Session session = getSSHClient().startSession();
        String cmdString = vcgencmdPath + " version";
        final Session.Command cmd = session.exec(cmdString);
        cmd.join(30, TimeUnit.SECONDS);
        String output = IOUtils.readFully(cmd.getInputStream())
                .toString();
        final String result = this.parseFirmwareVersion(output);
        LOGGER.debug("Firmware version: {}", result);
        return result;
    } catch (IOException e) {
        throw RaspiQueryException.createTransportFailure(e);
    }
}
 
Example #13
Source File: LoadAverageQuery.java    From rpicheck with MIT License 6 votes vote down vote up
@Override
public Double run() throws RaspiQueryException {
    LOGGER.info("Querying load average for time period {}", this.period);
    Session session;
    try {
        session = getSSHClient().startSession();
        session.allocateDefaultPTY();
        final Command cmd = session.exec(LOAD_AVG_CMD);
        cmd.join(30, TimeUnit.SECONDS);
        cmd.close();
        final String output = IOUtils.readFully(cmd.getInputStream())
                .toString();
        return this.parseLoadAverage(output, this.period);
    } catch (IOException e) {
        throw RaspiQueryException.createTransportFailure(e);
    }
}
 
Example #14
Source File: RaspiQuery.java    From rpicheck with MIT License 5 votes vote down vote up
/**
 * Queries the current cpu frequency.
 *
 * @param unit         cpu or arm
 * @param vcgencmdPath the path of the vcgendcmd tool
 * @return the frequency in hz
 * @throws RaspiQueryException if something goes wrong
 */
private long queryFreq(final int unit, final String vcgencmdPath)
        throws RaspiQueryException {
    if (client != null) {
        if (client.isConnected() && client.isAuthenticated()) {
            Session session;
            try {
                session = client.startSession();
                String cmdString = vcgencmdPath + " measure_clock";
                if (unit == FREQ_ARM) {
                    cmdString += " arm";
                } else if (unit == FREQ_CORE) {
                    cmdString += " core";
                } else {
                    return 0;
                }
                final Command cmd = session.exec(cmdString);
                cmd.join(30, TimeUnit.SECONDS);
                String output = IOUtils.readFully(cmd.getInputStream()).toString();
                return this.parseFrequency(output);
            } catch (IOException e) {
                throw RaspiQueryException.createTransportFailure(hostname,
                        e);
            }
        } else {
            throw new IllegalStateException("You must establish a connection first.");
        }
    } else {
        throw new IllegalStateException("You must establish a connection first.");
    }
}
 
Example #15
Source File: NetworkInformationQuery.java    From rpicheck with MIT License 5 votes vote down vote up
/**
 * Uses "whereis" to find path to the specified executable.
 *
 * @param executableBinary
 * @return the first path
 */
private Optional<String> findPathToExecutable(String executableBinary) throws RaspiQueryException {
    try {
        Session session = getSSHClient().startSession();
        session.allocateDefaultPTY();
        final String cmdString = "LC_ALL=C /usr/bin/whereis " + executableBinary;
        final Session.Command cmd = session.exec(cmdString);
        cmd.join(30, TimeUnit.SECONDS);
        final Integer exitStatus = cmd.getExitStatus();
        String output = IOUtils.readFully(cmd.getInputStream())
                .toString();
        if (exitStatus == 0) {
            LOGGER.debug("Output of '{}': \n{}", cmdString, output);
            final String[] splitted = output.split("\\s");
            if (splitted.length >= 2) {
                String path = splitted[1].trim();
                LOGGER.debug("Path for '{}': {}", executableBinary, path);
                return Optional.of(path);
            } else {
                LOGGER.warn("Could not get path to executable '{}'. Output of '{}' was: {}", executableBinary, cmdString, output);
                return Optional.absent();
            }
        } else {
            LOGGER.warn("Can't find path to executable '{}', execution of '{}' failed with exit code {}, output: {}", executableBinary, cmdString, exitStatus, output);
            return Optional.absent();
        }
    } catch (IOException e) {
        throw RaspiQueryException.createTransportFailure(e);
    }
}
 
Example #16
Source File: SshjHolderTests.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
public static void sshjConnectTest() throws IOException, InterruptedException {
	SSHClient ssh = new SSHClient();
	ssh.addHostKeyVerifier(new PromiscuousVerifier());
	ssh.connect("10.0.0.160");
	KeyProvider keyProvider = ssh.loadKeys(new String(PRIVATE_KEY), null, null);
	ssh.authPublickey("root", keyProvider);
	Session session = ssh.startSession();
	// TODO
	// session.allocateDefaultPTY();
	Session.Shell shell = session.startShell();
	String command = "mvn -version\n";

	OutputStream outputStream = shell.getOutputStream();
	outputStream.write(command.getBytes());
	outputStream.flush();
	outputStream.close();

	InputStream inputStream = shell.getInputStream();
	InputStream errorStream = shell.getErrorStream();

	Thread.sleep(1000);
	shell.close();
	if (nonNull(inputStream)) {
		String message = readFullyToString(inputStream);
		System.out.println(message);
	}
	if (nonNull(errorStream)) {
		String errmsg = readFullyToString(errorStream);
		System.out.println(errmsg);
	}

	session.close();
	ssh.close();

}
 
Example #17
Source File: RaspiQuery.java    From rpicheck with MIT License 5 votes vote down vote up
/**
 * Checks if the path is a correct path to vcgencmd.
 *
 * @param path   the path to check
 * @param client authenticated and open client
 * @return true, if correct, false if not
 * @throws IOException if something ssh related goes wrong
 */
private boolean isValidVcgencmdPath(String path, SSHClient client) throws IOException {
    final Session session = client.startSession();
    session.allocateDefaultPTY();
    LOGGER.debug("Checking vcgencmd location: {}", path);
    final Command cmd = session.exec(path);
    cmd.join(30, TimeUnit.SECONDS);
    session.close();
    final Integer exitStatus = cmd.getExitStatus();
    final String output = IOUtils.readFully(cmd.getInputStream()).toString().toLowerCase();
    LOGGER.debug("Path check output: {}", output);
    return exitStatus != null && exitStatus.equals(0)
            && !output.contains("not found") && !output.contains("no such file or directory");
}
 
Example #18
Source File: RaspiQuery.java    From rpicheck with MIT License 5 votes vote down vote up
@Override
public final Double queryVolts(String vcgencmdPath)
        throws RaspiQueryException {
    LOGGER.info("Querying core volts...");
    if (client != null) {
        if (client.isConnected() && client.isAuthenticated()) {
            Session session;
            try {
                session = client.startSession();
                final String cmdString = vcgencmdPath
                        + " measure_volts core";
                final Command cmd = session.exec(cmdString);
                cmd.join(30, TimeUnit.SECONDS);
                final String output = IOUtils.readFully(
                        cmd.getInputStream()).toString();
                return this.formatVolts(output);
            } catch (IOException e) {
                throw RaspiQueryException.createTransportFailure(hostname,
                        e);
            }
        } else {
            throw new IllegalStateException("You must establish a connection first.");
        }
    } else {
        throw new IllegalStateException("You must establish a connection first.");
    }
}
 
Example #19
Source File: RaspiQuery.java    From rpicheck with MIT License 5 votes vote down vote up
@Override
public String run(String command, int timeout) throws RaspiQueryException {
    LOGGER.info("Running custom command: {}", command);
    if (client != null) {
        if (client.isConnected() && client.isAuthenticated()) {
            Session session;
            try {
                session = client.startSession();
                session.allocateDefaultPTY();
                final Command cmd = session.exec(command);
                cmd.join(timeout, TimeUnit.SECONDS);
                cmd.close();
                final String output = IOUtils.readFully(cmd.getInputStream()).toString();
                final String error = IOUtils.readFully(cmd.getErrorStream()).toString();
                final StringBuilder sb = new StringBuilder();
                final String out = sb.append(output).append(error).toString();
                LOGGER.debug("Output of '{}': {}", command, out);
                session.close();
                return out;
            } catch (IOException e) {
                throw RaspiQueryException.createTransportFailure(hostname,
                        e);
            }
        } else {
            throw new IllegalStateException("You must establish a connection first.");
        }
    } else {
        throw new IllegalStateException("You must establish a connection first.");
    }

}
 
Example #20
Source File: MemoryQuery.java    From rpicheck with MIT License 5 votes vote down vote up
@Override
public RaspiMemoryBean run() throws RaspiQueryException {
    LOGGER.info("Querying memory information...");
    try {
        Session session = getSSHClient().startSession();
        final Session.Command cmd = session.exec(MEMORY_INFO_CMD);
        cmd.join(30, TimeUnit.SECONDS);
        return this.formatMemoryInfo(IOUtils.readFully(cmd.getInputStream()).toString());
    } catch (IOException e) {
        throw RaspiQueryException.createTransportFailure(e);
    }
}
 
Example #21
Source File: UptimeQuery.java    From rpicheck with MIT License 5 votes vote down vote up
@Override
public Double run() throws RaspiQueryException {
    LOGGER.info("Querying uptime...");
    try {
        final Session session = getSSHClient().startSession();
        final Command cmd = session.exec(UPTIME_CMD);
        cmd.join(30, TimeUnit.SECONDS);
        final String output = IOUtils.readFully(cmd.getInputStream())
                .toString();
        return this.formatUptime(output);
    } catch (IOException e) {
        throw RaspiQueryException.createTransportFailure(e);
    }
}
 
Example #22
Source File: SerialNoQuery.java    From rpicheck with MIT License 5 votes vote down vote up
@Override
public String run() throws RaspiQueryException {
    LOGGER.info("Querying serial number...");
    try {
        Session session = getSSHClient().startSession();
        final Command cmd = session.exec(CAT_PROC_CPUINFO_GREP_SERIAL);
        cmd.join(30, TimeUnit.SECONDS);
        String output = IOUtils.readFully(cmd.getInputStream()).toString();
        return this.formatCpuSerial(output);
    } catch (IOException e) {
        throw RaspiQueryException.createTransportFailure(e);
    }
}
 
Example #23
Source File: SshJClientActions.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private static Pair<Integer, String> execute(SSHClient ssh, String command) throws IOException {
    LOGGER.info("Waiting to SSH command to be executed...");
    try (Session session = startSshSession(ssh);
        Session.Command cmd = session.exec(command);
        OutputStream os = IOUtils.readFully(cmd.getInputStream())) {
        Log.log(LOGGER, format("The following SSH command [%s] is going to be executed on host [%s]", ssh.getConnection().getTransport().getRemoteHost(),
                command));
        cmd.join(10L, TimeUnit.SECONDS);
        return Pair.of(cmd.getExitStatus(), os.toString());
    }
}
 
Example #24
Source File: SshLogAccessService.java    From lognavigator with Apache License 2.0 5 votes vote down vote up
@Override
public InputStream executeCommand(String logAccessConfigId, String shellCommand) throws LogAccessException {
	
	// Get the LogAccessConfig
	LogAccessConfig logAccessConfig = configService.getLogAccessConfig(logAccessConfigId);

	// Create ssh client and authenticate
	SSHClient sshClient = sshClientThreadLocal.get();
	boolean closeSshClient = false;
	if (sshClient == null) {
		sshClient = connectAndAuthenticate(logAccessConfig);
		closeSshClient = true;
	}
	
	// Define the precommand (if any)
	String precommand = "";
	if (StringUtils.hasText(logAccessConfig.getPreCommand())) {
		precommand = logAccessConfig.getPreCommand() + " && ";
	}

	// Execute the shell command
	Session session = null;
	Command resultCommand;
	try {
		session = sshClient.startSession();
		resultCommand = session.exec("cd \"" + logAccessConfig.getDirectory() + "\" && " + precommand + shellCommand);
	}
	catch (SSHException e) {
		IOUtils.closeQuietly(session, sshClient);
		throw new LogAccessException("Error when executing command " + shellCommand + " to " + logAccessConfig, e);
	}
	
	// Get and return the result stream
	InputStream sequenceStream = new SequenceInputStream(resultCommand.getInputStream(), resultCommand.getErrorStream());
	InputStream resultStream = new SshCloseFilterInputStream(sequenceStream, resultCommand, session, (closeSshClient ? sshClient : null));
	return resultStream;
}
 
Example #25
Source File: SshjTool.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected SshAction<Session> newSessionAction() {

        return new SshAction<Session>() {

            private Session session = null;

            @Override
            public void clear() throws TransportException, ConnectionException {
                closeWhispering(session, this);
                session = null;
            }

            @Override
            public Session create() throws Exception {
                checkConnected();
                session = sshClientConnection.ssh.startSession();
                if (allocatePTY) {
                    session.allocatePTY(TERM, 80, 24, 0, 0, Collections.<PTYMode, Integer> emptyMap());
                }
                return session;
            }

            @Override
            public String toString() {
                return "Session()";
            }
        };

    }
 
Example #26
Source File: Main.java    From aedict with GNU General Public License v3.0 5 votes vote down vote up
private static void exec(SSHClient ssh, String cmd) throws ConnectionException, TransportException, IOException {
    final Session s = ssh.startSession();
    try {
        final Command c = s.exec(cmd);
        if (c.getExitErrorMessage() != null) {
            throw new RuntimeException("Command " + cmd + " failed to execute with status " + c.getExitStatus() + ": " + c.getExitErrorMessage() + ", " + c.getErrorAsString());
        }
    } finally {
        MiscUtils.closeQuietly(s);
    }
}
 
Example #27
Source File: SshjHolder.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T execWaitForComplete(String host, String user, char[] pemPrivateKey, String password, String command,
		ProcessFunction<Session.Command, T> processor, long timeoutMs) throws Exception {
	return doExecCommand(host, user, pemPrivateKey,password, command, cmd -> {
		// Wait for completed by condition.
		cmd.join(timeoutMs, TimeUnit.MILLISECONDS);
		return processor.process(cmd);
	});
}
 
Example #28
Source File: SshJClientActions.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
private static Session startSshSession(SSHClient ssh) throws ConnectionException, TransportException {
    Session sshSession = ssh.startSession();
    sshSession.allocateDefaultPTY();
    return sshSession;
}
 
Example #29
Source File: SshJExample.java    From ExpectIt with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws IOException {
    SSHClient ssh = new SSHClient();
    ssh.addHostKeyVerifier(
            new HostKeyVerifier() {
                @Override
                public boolean verify(String s, int i, PublicKey publicKey) {
                    return true;
                }
            });
    ssh.connect("sdf.org");
    ssh.authPassword("new", "");
    Session session = ssh.startSession();
    session.allocateDefaultPTY();
    Shell shell = session.startShell();
    Expect expect = new ExpectBuilder()
            .withOutput(shell.getOutputStream())
            .withInputs(shell.getInputStream(), shell.getErrorStream())
            .withEchoInput(System.out)
            .withEchoOutput(System.err)
            .withInputFilters(removeColors(), removeNonPrintable())
            .withExceptionOnFailure()
            .build();
    try {
        expect.expect(contains("[RETURN]"));
        expect.sendLine();
        String ipAddress = expect.expect(regexp("Trying (.*)\\.\\.\\.")).group(1);
        System.out.println("Captured IP: " + ipAddress);
        expect.expect(contains("login:"));
        expect.sendLine("new");
        expect.expect(contains("(Y/N)"));
        expect.send("N");
        expect.expect(regexp(": $"));
        expect.send("\b");
        expect.expect(regexp("\\(y\\/n\\)"));
        expect.sendLine("y");
        expect.expect(contains("Would you like to sign the guestbook?"));
        expect.send("n");
        expect.expect(contains("[RETURN]"));
        expect.sendLine();
    } finally {
        expect.close();
        session.close();
        ssh.close();
    }
}
 
Example #30
Source File: SshCloseFilterInputStream.java    From lognavigator with Apache License 2.0 4 votes vote down vote up
public SshCloseFilterInputStream(InputStream in, Command command, Session session, SSHClient sshClient) {
	super(in);
	this.command = command;
	this.session = session;
	this.sshClient = sshClient;
}