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

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: 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: 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 #5
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 #6
Source File: SshjTool.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public int execCommands(Map<String,?> props, List<String> commands, Map<String,?> env) {
    if (Boolean.FALSE.equals(props.get("blocks"))) {
        throw new IllegalArgumentException("Cannot exec non-blocking: command="+commands);
    }

    // If async is set, then do it as execScript
    Boolean execAsync = getOptionalVal(props, PROP_EXEC_ASYNC);
    if (Boolean.TRUE.equals(execAsync) && BrooklynFeatureEnablement.isEnabled(BrooklynFeatureEnablement.FEATURE_SSH_ASYNC_EXEC)) {
        return execScriptAsyncAndPoll(props, commands, env);
    }

    OutputStream out = getOptionalVal(props, PROP_OUT_STREAM);
    OutputStream err = getOptionalVal(props, PROP_ERR_STREAM);
    String separator = getOptionalVal(props, PROP_SEPARATOR);
    Duration execTimeout = getOptionalVal(props, PROP_EXEC_TIMEOUT);

    List<String> allcmds = toCommandSequence(commands, env);
    String singlecmd = Joiner.on(separator).join(allcmds);

    if (Boolean.TRUE.equals(getOptionalVal(props, PROP_RUN_AS_ROOT))) {
        LOG.warn("Cannot run as root when executing as command; run as a script instead (will run as normal user): "+singlecmd);
    }

    if (LOG.isTraceEnabled()) LOG.trace("Running command at {}: {}", host, singlecmd);

    Command result = acquire(new ExecAction(singlecmd, out, err, execTimeout));
    if (LOG.isTraceEnabled()) LOG.trace("Running command at {} completed: exit code {}", host, result.getExitStatus());
    // can be null if no exit status is received (observed on kill `ps aux | grep thing-to-grep-for | awk {print $2}`
    if (result.getExitStatus()==null) LOG.warn("Null exit status running at {}: {}", host, singlecmd);

    return asInt(result.getExitStatus(), -1);
}
 
Example #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
Source File: SshjTool.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public Command create() throws Exception {
    try {
        session = acquire(newSessionAction());

        Command output = session.exec(checkNotNull(command, "command"));

        if (out != null) {
            outgobbler = new StreamGobbler(output.getInputStream(), out, (Logger)null);
            outgobbler.start();
        }
        if (err != null) {
            errgobbler = new StreamGobbler(output.getErrorStream(), err, (Logger)null);
            errgobbler.start();
        }
        try {
            output.join((int)Math.min(timeout.toMilliseconds(), Integer.MAX_VALUE), TimeUnit.MILLISECONDS);
            return output;

        } finally {
            // wait for all stdout/stderr to have been re-directed
            try {
                // Don't use forever (i.e. 0) because BROOKLYN-106: ssh hangs
                long joinTimeout = 10*1000;
                if (outgobbler != null) outgobbler.join(joinTimeout);
                if (errgobbler != null) errgobbler.join(joinTimeout);
            } catch (InterruptedException e) {
                LOG.warn("Interrupted gobbling streams from ssh: "+command, e);
                Thread.currentThread().interrupt();
            }
        }

    } finally {
        clear();
    }
}
 
Example #15
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 #16
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;
}
 
Example #17
Source File: CommandMocker.java    From rpicheck with MIT License 4 votes vote down vote up
public Command mock() {
    return this.command;
}