Java Code Examples for net.schmizz.sshj.connection.channel.direct.Session#allocateDefaultPTY()

The following examples show how to use net.schmizz.sshj.connection.channel.direct.Session#allocateDefaultPTY() . 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: 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 2
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 3
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 4
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 5
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 6
Source File: RudimentaryPTY.java    From karamel with Apache License 2.0 4 votes vote down vote up
public static void main(String... args)
    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);
  try {

    final Session session = client.startSession();
    try {

      session.allocateDefaultPTY();

      final Shell shell = session.startShell();

      new StreamCopier(shell.getInputStream(), System.out, LoggerFactory.DEFAULT)
          .bufSize(shell.getLocalMaxPacketSize())
          .spawn("stdout");

      new StreamCopier(shell.getErrorStream(), System.err, LoggerFactory.DEFAULT)
          .bufSize(shell.getLocalMaxPacketSize())
          .spawn("stderr");

      // Now make System.in act as stdin. To exit, hit Ctrl+D (since that results in an EOF on System.in)
      // This is kinda messy because java only allows console input after you hit return
      // But this is just an example... a GUI app could implement a proper PTY
      new StreamCopier(System.in, shell.getOutputStream(), LoggerFactory.DEFAULT)
          .bufSize(shell.getRemoteMaxPacketSize())
          .copy();

    } finally {
      session.close();
    }

  } finally {
    client.disconnect();
  }
}
 
Example 7
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 8
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;
}