net.schmizz.sshj.common.IOUtils Java Examples
The following examples show how to use
net.schmizz.sshj.common.IOUtils.
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 |
@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 |
@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 |
@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: FirmwareQuery.java From rpicheck with MIT License | 6 votes |
@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 #5
Source File: LoadAverageQuery.java From rpicheck with MIT License | 6 votes |
@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 #6
Source File: SystemtimeQuery.java From rpicheck with MIT License | 6 votes |
@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 #7
Source File: RaspiQuery.java From rpicheck with MIT License | 6 votes |
/** * 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 #8
Source File: NetworkInformationQuery.java From rpicheck with MIT License | 6 votes |
/** * 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 #9
Source File: NetworkInformationQuery.java From rpicheck with MIT License | 6 votes |
/** * 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 #10
Source File: NetworkInformationQuery.java From rpicheck with MIT License | 6 votes |
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 #11
Source File: NetworkInformationQuery.java From rpicheck with MIT License | 6 votes |
/** * 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: NetworkInformationQuery.java From rpicheck with MIT License | 5 votes |
/** * 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 #13
Source File: RaspiQuery.java From rpicheck with MIT License | 5 votes |
@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 #14
Source File: RaspiQuery.java From rpicheck with MIT License | 5 votes |
@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 #15
Source File: RaspiQuery.java From rpicheck with MIT License | 5 votes |
/** * 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 #16
Source File: RaspiQuery.java From rpicheck with MIT License | 5 votes |
/** * 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 #17
Source File: RawContentTag.java From lognavigator with Apache License 2.0 | 5 votes |
@Override public int doEndTag() throws JspException { // Get input and ouput variables Reader rawContent = (Reader) pageContext.getAttribute(Constants.RAW_CONTENT_KEY, PageContext.REQUEST_SCOPE); JspWriter out = pageContext.getOut(); try { // Copy input (rawContent) to output (out) char[] buffer = new char[StreamUtils.BUFFER_SIZE]; int bytesRead = -1; while ((bytesRead = rawContent.read(buffer)) != -1) { String stringToWrite = new String(buffer, 0, bytesRead); stringToWrite = HtmlUtils.htmlEscape(stringToWrite); out.write(stringToWrite); } out.flush(); return EVAL_PAGE; } catch (IOException e) { throw new JspException(e); } finally { IOUtils.closeQuietly(rawContent); } }
Example #18
Source File: MemoryQuery.java From rpicheck with MIT License | 5 votes |
@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 #19
Source File: UptimeQuery.java From rpicheck with MIT License | 5 votes |
@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 #20
Source File: SerialNoQuery.java From rpicheck with MIT License | 5 votes |
@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 #21
Source File: SshJClientActions.java From cloudbreak with Apache License 2.0 | 5 votes |
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 #22
Source File: SshLogAccessService.java From lognavigator with Apache License 2.0 | 5 votes |
@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 #23
Source File: SshCloseFilterInputStream.java From lognavigator with Apache License 2.0 | 4 votes |
@Override public void close() throws IOException { // Close the stream, session and ssh client IOUtils.closeQuietly(super.in, command, session, sshClient); }
Example #24
Source File: SshLogAccessService.java From lognavigator with Apache License 2.0 | 4 votes |
@Override protected Set<FileInfo> listFilesUsingNativeSystem(LogAccessConfig logAccessConfig, String subPath) throws LogAccessException { // Get ssh client SSHClient sshClient = sshClientThreadLocal.get(); // Define target directory String targetPath = logAccessConfig.getDirectory(); if (subPath != null) { targetPath += "/" + subPath; } // List files and directories (keep only the 'fileListMaxCount' last modified resources) SFTPClient sftpClient = null; Collection<RemoteResourceInfo> remoteResourceInfos; try { sftpClient = sshClient.newSFTPClient(); LastUpdatedRemoteResourceFilter remoteResourcefilter = new LastUpdatedRemoteResourceFilter(configService.getFileListMaxCount()); sftpClient.ls(targetPath, remoteResourcefilter); remoteResourceInfos = remoteResourcefilter.getRemoteResourceInfos(); } catch (IOException e) { throw new LogAccessException("Error when listing files and directories on " + logAccessConfig, e); } finally { IOUtils.closeQuietly(sftpClient, sshClient); } // Extract meta-informations Set<FileInfo> fileInfos = new TreeSet<FileInfo>(); for (RemoteResourceInfo remoteResourceInfo : remoteResourceInfos) { FileInfo fileInfo = new FileInfo(); fileInfo.setFileName(remoteResourceInfo.getName()); fileInfo.setRelativePath(remoteResourceInfo.getPath().substring(logAccessConfig.getDirectory().length() + 1).replace('\\', '/')); fileInfo.setDirectory(remoteResourceInfo.isDirectory()); fileInfo.setLastModified(new Date(remoteResourceInfo.getAttributes().getMtime() * 1000L)); fileInfo.setFileSize(remoteResourceInfo.isDirectory() ? 0L : remoteResourceInfo.getAttributes().getSize()); fileInfo.setLogAccessType(LogAccessType.SSH); fileInfos.add(fileInfo); } // Return meta-informations about files and folders return fileInfos; }
Example #25
Source File: CommandController.java From lognavigator with Apache License 2.0 | 4 votes |
@RequestMapping("/logs/{logAccessConfigId}/command") public String executeCommand(Model model, HttpServletRequest request, @PathVariable String logAccessConfigId, @RequestParam(value="cmd", required=false, defaultValue=DEFAULT_LIST_COMMAND) String cmd, @RequestParam(value="encoding", required=false) String encoding, @RequestParam(value="displayType", required=false) DisplayType displayType ) throws AuthorizationException, LogAccessException, IOException { // Parse command line CommandLine commandLine = CommandLineParser.parseCommandLine(cmd); // Is command forbidden ? checkForbiddenCommand(commandLine); // Forward to 'list' action, if command is 'ls' if ((displayType == null || displayType == DisplayType.TABLE) && commandLine.getCommand().equals(DEFAULT_LIST_COMMAND) && !cmd.contains("|")) { if (commandLine.hasParams()) { return UrlBasedViewResolver.FORWARD_URL_PREFIX + FOLDER_VIEW_URL_PREFIX + commandLine.getParam(0); } else { return UrlBasedViewResolver.FORWARD_URL_PREFIX + LOGS_LIST_URL; } } // Define default encoding when not given by client if (encoding == null) { encoding = configService.getDefaultEncoding(logAccessConfigId); } // Define default displayType when not given by client if (displayType == null) { if (cmd.startsWith(TAR_GZ_FILE_VIEW_COMMAND_START) || cmd.endsWith(TAR_GZ_FILE_VIEW_COMMAND_END)) { displayType = DisplayType.TABLE; } else { displayType = DisplayType.RAW; } } // Add options to model request.setAttribute(SHOW_OPTIONS_KEY, true); request.setAttribute(ENCODING_KEY, encoding); request.setAttribute(DISPLAY_TYPE_KEY, displayType); // Generate Breadcrumbs generateBreadcrumbs(logAccessConfigId, commandLine, request); // Execute the command InputStream resultStream = logAccessService.executeCommand(logAccessConfigId, cmd); BufferedReader resultReader = new BufferedReader(new InputStreamReader(resultStream, encoding)); // Process the result lines for raw display if (displayType == DisplayType.RAW) { model.addAttribute(RAW_CONTENT_KEY, resultReader); return VIEW_RAW; } // Process the result lines for html table display else { try { if (cmd.startsWith(TAR_GZ_FILE_VIEW_COMMAND_START) || cmd.endsWith(TAR_GZ_FILE_VIEW_COMMAND_END)) { return processTarGzList(resultReader, model, cmd); } else { processOtherCommand(resultReader, model); } } finally { IOUtils.closeQuietly(resultReader); } return VIEW_TABLE; } }