private String execAndGetOutput(String command) throws JSchException, MachineException, IOException { ChannelExec exec = (ChannelExec) session.openChannel("exec"); exec.setCommand(command); try (BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream())); InputStream erStream = exec.getErrStream()) { exec.connect(connectionTimeout); ListLineConsumer listLineConsumer = new ListLineConsumer(); String line; while ((line = reader.readLine()) != null) { listLineConsumer.writeLine(line); } // read stream to wait until command finishes its work IoUtil.readStream(erStream); if (exec.getExitStatus() != 0) { throw new MachineException( format( "Error code: %s. Error: %s", exec.getExitStatus(), IoUtil.readAndCloseQuietly(exec.getErrStream()))); } return listLineConsumer.getText(); } finally { exec.disconnect(); } }
public ExecResult executeCommand(Session session, String command, String workingDir) throws PortalServiceException { ChannelExec channel = null; if (workingDir != null) { command = "cd " + workingDir + "; " + command; } try { channel = (ChannelExec) session.openChannel("exec"); channel.setCommand(command); channel.setInputStream(null); channel.setErrStream(null); channel.connect(); try (InputStream out = channel.getInputStream(); InputStream err = channel.getErrStream()) { String outStr = readStream(out, channel); String errStr = readStream(err, channel); return new ExecResult(outStr, errStr, channel.getExitStatus()); } catch (IOException | InterruptedException e) { throw new PortalServiceException(e.getMessage(), e); } } catch (JSchException e) { throw new PortalServiceException(e.getMessage(), e); } finally { if (channel != null) { channel.disconnect(); } } }
private void executeCommand(final String command) throws JSchException, IOException { c = (ChannelExec) session.openChannel("exec"); c.setCommand(command); latestChannelOutputStream = c.getOutputStream(); latestChannelInputStream = c.getInputStream(); c.connect(); }
void scpStringToFile(Session session, String workingDir, String fileName, String userDataString) throws PortalServiceException { String command = "scp -t " + workingDir + "/" + fileName; ChannelExec channel; try { channel = (ChannelExec) session.openChannel("exec"); } catch (JSchException e1) { throw new PortalServiceException(e1.getMessage(), e1); } channel.setCommand(command); // get I/O streams for remote scp try (OutputStream out = channel.getOutputStream(); InputStream in = channel.getInputStream()) { channel.connect(); checkAck(in); byte[] userData = userDataString.getBytes("UTF-8"); // send "C0644 filesize filename", where filename should not include '/' long filesize = userData.length; command = "C0644 " + filesize + " " + fileName; // if (lfile.lastIndexOf('/') > 0) { // command += lfile.substring(lfile.lastIndexOf('/') + 1); // } else { // command += lfile; // } command += "\n"; out.write(command.getBytes()); out.flush(); checkAck(in); out.write(userData); out.write(0); out.flush(); checkAck(in); out.close(); } catch (IOException | JSchException e) { throw new PortalServiceException(e.getMessage(), e); } channel.disconnect(); }
/** * Gets the value of the specified environment variable. * * @param ses SSH session. * @param cmd environment variable name. * @return environment variable value. * @throws JSchException In case of SSH error. * @throws IOException If failed. */ private String exec(Session ses, String cmd) throws JSchException, IOException { ChannelExec ch = null; try { ch = (ChannelExec) ses.openChannel("exec"); ch.setCommand(cmd); ch.connect(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(ch.getInputStream()))) { return reader.readLine(); } } finally { if (ch != null && ch.isConnected()) ch.disconnect(); } }
/** * FIXME Comment this * * @param session * @param cmd * @return return code of the process. * @throws JSchException if there's an underlying problem exposed in SSH * @throws IOException if there's a problem attaching streams. * @throws TimeoutException if we exceeded our timeout */ private int executeCommand(Session session, String cmd) throws JSchException, IOException, TimeoutException { final ChannelExec channel; session.setTimeout((int) maxwait); /* execute the command */ channel = (ChannelExec) session.openChannel("exec"); channel.setCommand(cmd); attachStreams(channel); project.log("executing command: " + cmd, Project.MSG_VERBOSE); channel.connect(); try { waitFor(channel); } finally { streamHandler.stop(); closeStreams(channel); } return channel.getExitStatus(); }
private int execAndGetCode(String command) throws JSchException, IOException { ChannelExec exec = (ChannelExec) session.openChannel("exec"); exec.setCommand(command); try (InputStream inStream = exec.getInputStream(); InputStream erStream = exec.getErrStream()) { exec.connect(connectionTimeout); // read streams to wait until command finishes its work IoUtil.readStream(inStream); IoUtil.readStream(erStream); } finally { exec.disconnect(); } return exec.getExitStatus(); }
/** * Reads out the output of a ssh session exec * * @param channel Channel to read from * @param strStdout StringBuffer that receives Session Stdout output * @param strStderr StringBuffer that receives Session Stderr output * @throws IOException in case of trouble with the network */ private void readSessionOutput( ChannelExec channel, StringBuffer strStdout, StringBuffer strStderr) throws IOException { InputStream stdout = channel.getInputStream(); InputStream stderr = channel.getErrStream(); try { channel.connect(); } catch (JSchException e1) { throw (IOException) new IOException("Channel connection problems").initCause(e1); } byte[] buffer = new byte[BUFFER_SIZE]; while (true) { int avail = 0; while ((avail = stdout.available()) > 0) { int len = stdout.read(buffer, 0, (avail > BUFFER_SIZE - 1 ? BUFFER_SIZE : avail)); strStdout.append(new String(buffer, 0, len)); } while ((avail = stderr.available()) > 0) { int len = stderr.read(buffer, 0, (avail > BUFFER_SIZE - 1 ? BUFFER_SIZE : avail)); strStderr.append(new String(buffer, 0, len)); } if (channel.isClosed()) { break; } try { Thread.sleep(POLL_SLEEP_TIME); } catch (Exception ee) { // ignored } } int avail = 0; while ((avail = stdout.available()) > 0) { int len = stdout.read(buffer, 0, (avail > BUFFER_SIZE - 1 ? BUFFER_SIZE : avail)); strStdout.append(new String(buffer, 0, len)); } while ((avail = stderr.available()) > 0) { int len = stderr.read(buffer, 0, (avail > BUFFER_SIZE - 1 ? BUFFER_SIZE : avail)); strStderr.append(new String(buffer, 0, len)); } }
public Streams executeCommand(String command, boolean ignoreFailures) throws CommandExecutionException { ChannelExec channel = null; BufferedReader stdoutReader = null; BufferedReader stderrReader = null; try { channel = (ChannelExec) session.openChannel(EXEC_CHANNEL); channel.setCommand(command + "\n"); InputStream stdout = channel.getInputStream(); InputStream stderr = channel.getErrStream(); channel.connect(); stdoutReader = new BufferedReader(new InputStreamReader(stdout)); stderrReader = new BufferedReader(new InputStreamReader(stderr)); Streams streams = CommandExecutorStreamProcessor.processStreams(stderrReader, stdoutReader); if (streams.getErr().length() > 0 && !ignoreFailures) { int exitCode = channel.getExitStatus(); throw new CommandExecutionException("Exit code: " + exitCode + " - " + streams.getErr()); } return streams; } catch (IOException e) { throw new CommandExecutionException("Cannot execute remote command: " + command, e); } catch (JSchException e) { throw new CommandExecutionException("Cannot execute remote command: " + command, e); } finally { IOUtil.close(stdoutReader); IOUtil.close(stderrReader); if (channel != null) { channel.disconnect(); } } }
public ExecResponse exec(String command) { checkConnected(); ChannelExec executor = null; try { try { executor = (ChannelExec) session.openChannel("exec"); executor.setPty(true); } catch (JSchException e) { throw new SshException( String.format("%s@%s:%d: Error connecting to exec.", username, host, port), e); } executor.setCommand(command); ByteArrayOutputStream error = new ByteArrayOutputStream(); executor.setErrStream(error); try { executor.connect(); String outputString = Strings2.toStringAndClose(executor.getInputStream()); String errorString = error.toString(); int errorStatus = executor.getExitStatus(); int i = 0; while ((errorStatus = executor.getExitStatus()) == -1 && i < this.sshRetries) backoffForAttempt(++i, String.format("%s@%s:%d: bad status: -1", username, host, port)); if (errorStatus == -1) throw new SshException( String.format( "%s@%s:%d: received exit status %d executing %s", username, host, port, executor.getExitStatus(), command)); return new ExecResponse(outputString, errorString, errorStatus); } catch (Exception e) { throw new SshException( String.format("%s@%s:%d: Error executing command: %s", username, host, port, command), e); } } finally { if (executor != null) executor.disconnect(); } }
@Override public ExecChannel create() throws Exception { this.sessionConnection = acquire( SessionConnection.builder() .from(JschSshClient.this.sessionConnection) .sessionTimeout(0) .build()); String channel = "exec"; executor = (ChannelExec) sessionConnection.openChannel(channel); executor.setCommand(command); executor.setErrStream(new ByteArrayOutputStream()); InputStream inputStream = executor.getInputStream(); InputStream errStream = executor.getErrStream(); OutputStream outStream = executor.getOutputStream(); executor.connect(); return new ExecChannel( outStream, inputStream, errStream, new Supplier<Integer>() { @Override public Integer get() { int exitStatus = executor.getExitStatus(); return exitStatus != -1 ? exitStatus : null; } }, new Closeable() { @Override public void close() throws IOException { clear(); } }); }
@Override public Integer call() { int exitstatus = Integer.MAX_VALUE; Boolean useIdentityFile = null; String credentials = null; String userName = nodeCredentials.getUsername(); if (nodeCredentials instanceof LoginCredentialsPassword) { useIdentityFile = false; credentials = ((LoginCredentialsPassword) nodeCredentials).getPassword(); } else if (nodeCredentials instanceof LoginCredentialsPrivateKey) { useIdentityFile = true; credentials = ((LoginCredentialsPrivateKey) nodeCredentials).getKey().getKeyPath(); } ChannelExec c = null; SshClient ssh = null; try { ssh = new SshClient(); ssh.createSession(nodeAddress, userName, false); log.info("connecting with username: "******"connecting using identity file: " + credentials); } else { log.info("connecting using password: "******"executing command: " + command); c.connect(); new Thread( new Runnable() { public void run() { String line; BufferedReader bufferedInputReader = new BufferedReader(new InputStreamReader(is)); try { while ((line = bufferedInputReader.readLine()) != null) { output.append(line); synchronized (timeStamp) { timeStamp = System.currentTimeMillis(); } } } catch (IOException e) { e.printStackTrace(); } } }) .start(); new Thread( new Runnable() { public void run() { String line; BufferedReader bufferedErrorReader = new BufferedReader(new InputStreamReader(err)); try { while ((line = bufferedErrorReader.readLine()) != null) { error.append(line); synchronized (timeStamp) { timeStamp = System.currentTimeMillis(); } } } catch (IOException e) { e.printStackTrace(); } } }) .start(); while (!c.isClosed()) { synchronized (this.timeStamp) { if (System.currentTimeMillis() - this.timeStamp > MAXIMUM_WAITING_TIME_INACTIVITY) { log.warn("command execution seems inactive, canceling!"); break; } } log.info("waiting for command to finish."); try { Thread.sleep(SshClient.DEFAULT_WAITING_TIME_PER_CYCLE); } catch (InterruptedException e) { e.printStackTrace(); } } exitstatus = c.getExitStatus(); } catch (JSchException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (c != null) { c.disconnect(); } if (ssh != null) { try { ssh.disconnectSession(); } catch (JSchException e) { e.printStackTrace(); } } } return exitstatus; }
/** * Execute the command on the destination path and parse the output to return an integer * * @param command * @param path * @return Process PID or null if can't get it. * @throws RemoteAccessException if connection down */ private Integer execute(String command, Path path) throws RemoteAccessException { log.debug(command); ChannelExec channel = null; StringBuilder sb = new StringBuilder(); try { channel = channelManager.getExecChannel(path); // TODO: Decor with tee to write on standard err and out stream and // alse remote scratch file channel.setCommand(command); channel.setInputStream(null); channel.setErrStream(System.err); InputStream in = channel.getInputStream(); channel.connect(); // Read Pid byte[] tmp = new byte[1024]; while (true) { while (in.available() > 0) { int i = in.read(tmp, 0, 1024); if (i < 0) { break; } sb.append(new String(tmp, 0, i)); } if (channel.isClosed()) { break; } try { Thread.sleep(1000); } catch (Exception e) { log.error("Runtime error. Thread Interupted.", e); throw new RemoteAccessException("Thread interupted", e); } } if (channel.getExitStatus() < 0) { throw new RemoteAccessException("SSH connection close abruptly"); } } catch (Exception e) { throw new RemoteAccessException("Unable to SSH connect. Command: " + command, e); } finally { try { if (channel != null) { channel.disconnect(); } } catch (Exception e) { log.error("SSH disconnect error", e); } } // parse pid Integer pid = null; try { pid = Integer.valueOf(sb.toString().trim()); } catch (NumberFormatException e) { log.warn("Unable to convert the command output to PID. Output = " + sb.toString()); } return pid; }