Java Code Examples for net.schmizz.sshj.connection.channel.direct.Session#Command

The following examples show how to use net.schmizz.sshj.connection.channel.direct.Session#Command . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
Source File: SshMachineTest.java    From karamel with Apache License 2.0 4 votes vote down vote up
public void testReadLogfile() throws IOException {
  String privateKey = "-----BEGIN RSA PRIVATE KEY-----\n"
      + "MIIEogIBAAKCAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzI\n"
      + "w+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9HZyN1Q9qgCgzUFtdOKLv6IedplqoP\n"
      + "kcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2\n"
      + "hMNG0zQPyUecp4pzC6kivAIhyfHilFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NO\n"
      + "Td0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcW\n"
      + "yLbIbEgE98OHlnVYCzRdK8jlqm8tehUc9c9WhQIBIwKCAQEA4iqWPJXtzZA68mKd\n"
      + "ELs4jJsdyky+ewdZeNds5tjcnHU5zUYE25K+ffJED9qUWICcLZDc81TGWjHyAqD1\n"
      + "Bw7XpgUwFgeUJwUlzQurAv+/ySnxiwuaGJfhFM1CaQHzfXphgVml+fZUvnJUTvzf\n"
      + "TK2Lg6EdbUE9TarUlBf/xPfuEhMSlIE5keb/Zz3/LUlRg8yDqz5w+QWVJ4utnKnK\n"
      + "iqwZN0mwpwU7YSyJhlT4YV1F3n4YjLswM5wJs2oqm0jssQu/BT0tyEXNDYBLEF4A\n"
      + "sClaWuSJ2kjq7KhrrYXzagqhnSei9ODYFShJu8UWVec3Ihb5ZXlzO6vdNQ1J9Xsf\n"
      + "4m+2ywKBgQD6qFxx/Rv9CNN96l/4rb14HKirC2o/orApiHmHDsURs5rUKDx0f9iP\n"
      + "cXN7S1uePXuJRK/5hsubaOCx3Owd2u9gD6Oq0CsMkE4CUSiJcYrMANtx54cGH7Rk\n"
      + "EjFZxK8xAv1ldELEyxrFqkbE4BKd8QOt414qjvTGyAK+OLD3M2QdCQKBgQDtx8pN\n"
      + "CAxR7yhHbIWT1AH66+XWN8bXq7l3RO/ukeaci98JfkbkxURZhtxV/HHuvUhnPLdX\n"
      + "3TwygPBYZFNo4pzVEhzWoTtnEtrFueKxyc3+LjZpuo+mBlQ6ORtfgkr9gBVphXZG\n"
      + "YEzkCD3lVdl8L4cw9BVpKrJCs1c5taGjDgdInQKBgHm/fVvv96bJxc9x1tffXAcj\n"
      + "3OVdUN0UgXNCSaf/3A/phbeBQe9xS+3mpc4r6qvx+iy69mNBeNZ0xOitIjpjBo2+\n"
      + "dBEjSBwLk5q5tJqHmy/jKMJL4n9ROlx93XS+njxgibTvU6Fp9w+NOFD/HvxB3Tcz\n"
      + "6+jJF85D5BNAG3DBMKBjAoGBAOAxZvgsKN+JuENXsST7F89Tck2iTcQIT8g5rwWC\n"
      + "P9Vt74yboe2kDT531w8+egz7nAmRBKNM751U/95P9t88EDacDI/Z2OwnuFQHCPDF\n"
      + "llYOUI+SpLJ6/vURRbHSnnn8a/XG+nzedGH5JGqEJNQsz+xT2axM0/W/CRknmGaJ\n"
      + "kda/AoGANWrLCz708y7VYgAtW2Uf1DPOIYMdvo6fxIB5i9ZfISgcJ/bbCUkFrhoH\n"
      + "+vq/5CIWxCPp0f85R4qxxQ5ihxJ0YDQT9Jpx4TMss4PSavPaBH3RXow5Ohe+bYoQ\n"
      + "NE5OgEXk2wVfZczCZpigBKbKZHNYcelXtTt/nP3rsCuGcM4h53s=\n"
      + "-----END RSA PRIVATE KEY-----";

  String publicKey = "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzIw+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9HZyN1Q9qgCgzUFtdOKLv6IedplqoPkcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2hMNG0zQPyUecp4pzC6kivAIhyfHilFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NOTd0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcWyLbIbEgE98OHlnVYCzRdK8jlqm8tehUc9c9WhQ== vagrant insecure public key";
  SSHClient client = new SSHClient();
  client.addHostKeyVerifier(new PromiscuousVerifier());
  KeyProvider keys = client.loadKeys(privateKey, publicKey, null);
  client.connect("192.168.33.10", 22);
  client.authPublickey("vagrant", keys);

  Session session = client.startSession();
  final Session.Command cmd = session.exec("ls");
  cmd.join();
  final byte[] buffer = new byte[65536];
  InputStream is = cmd.getInputStream();
  int r;
  while ((r = is.read(buffer)) > 0) {
    String decoded = new String(buffer, "UTF-8");
    System.out.println(decoded);
  }

}