/** * Executes a given command. It opens exec channel for the command and closes * the channel when it's done. * * @param session ssh connection to a remote server * @param command command to execute * @return command output string if the command succeeds, or null */ private static String executeCommand(Session session, String command) { if (session == null || !session.isConnected()) { return null; } log.trace("Execute command {} to {}", command, session.getHost()); try { Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); InputStream output = channel.getInputStream(); channel.connect(); String result = CharStreams.toString(new InputStreamReader(output)); channel.disconnect(); log.trace("Result of command {} on {}: {}", command, session.getHost(), result); return result; } catch (JSchException | IOException e) { log.error("Failed to execute command {} on {} due to {}", command, session.getHost(), e.toString()); return null; } }
/** * Execute an ssh command on the server, without closing the session * so that a Reader can be returned with streaming data from the server. * * @param command the command to execute. * @return a Reader with streaming data from the server. * @throws IOException if it is so. * @throws SshException if there are any ssh problems. */ @Override public synchronized Reader executeCommandReader(String command) throws SshException, IOException { if (!isConnected()) { throw new IllegalStateException("Not connected!"); } try { Channel channel = connectSession.openChannel("exec"); ((ChannelExec)channel).setCommand(command); InputStreamReader reader = new InputStreamReader(channel.getInputStream(), "utf-8"); channel.connect(); return reader; } catch (JSchException ex) { throw new SshException(ex); } }
/** * Connect to a remote host and return a channel (session and jsch are set) */ Channel connect(String channleType, String sshCommand) throws Exception { JSch.setConfig("StrictHostKeyChecking", "no"); // Not recommended, but useful jsch = new JSch(); // Some "reasonable" defaults if (Gpr.exists(defaultKnownHosts)) jsch.setKnownHosts(defaultKnownHosts); for (String identity : defaultKnownIdentity) if (Gpr.exists(identity)) jsch.addIdentity(identity); // Create session and connect if (debug) Gpr.debug("Create conection:\n\tuser: '" + host.getUserName() + "'\n\thost : '" + host.getHostName() + "'\n\tport : " + host.getPort()); session = jsch.getSession(host.getUserName(), host.getHostName(), host.getPort()); session.setUserInfo(new SshUserInfo()); session.connect(); // Create channel channel = session.openChannel(channleType); if ((sshCommand != null) && (channel instanceof ChannelExec)) ((ChannelExec) channel).setCommand(sshCommand); return channel; }
public static String connectAndExecute(String user, String host, String password, String command1) { String CommandOutput = null; try { java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); JSch jsch = new JSch(); Session session = jsch.getSession(user, host, 22); session.setPassword(password); session.setConfig(config); session.connect(); // System.out.println("Connected"); Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command1); channel.setInputStream(null); ((ChannelExec) channel).setErrStream(System.err); InputStream in = channel.getInputStream(); channel.connect(); byte[] tmp = new byte[1024]; while (true) { while (in.available() > 0) { int i = in.read(tmp, 0, 1024); if (i < 0) break; // System.out.print(new String(tmp, 0, i)); CommandOutput = new String(tmp, 0, i); } if (channel.isClosed()) { // System.out.println("exit-status: " + // channel.getExitStatus()); break; } try { Thread.sleep(1000); } catch (Exception ee) { } } channel.disconnect(); session.disconnect(); // System.out.println("DONE"); } catch (Exception e) { e.printStackTrace(); } return CommandOutput; }
public String sendCommand(String command) throws JSchException, IOException { StringBuilder outputBuffer = new StringBuilder(); Channel channel = sesConnection.openChannel("exec"); ((ChannelExec)channel).setCommand(command); InputStream commandOutput = channel.getInputStream(); channel.connect(); int readByte = commandOutput.read(); while(readByte != 0xffffffff) { outputBuffer.append((char)readByte); readByte = commandOutput.read(); } channel.disconnect(); return outputBuffer.toString(); }
public String runCommand(String command) throws Exception { Log.i(TAG + " runCommand", command); StringBuilder outputBuffer = new StringBuilder(); Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); channel.connect(); InputStream commandOutput = channel.getInputStream(); int readByte = commandOutput.read(); while (readByte != 0xffffffff) { outputBuffer.append((char) readByte); readByte = commandOutput.read(); } channel.disconnect(); String output = outputBuffer.toString(); Log.i(TAG + " runCommand", command + ", output: " + output); return output; }
/** * * Scp file from remote server * * @param host * @param user * @param password * @param remoteFile * @param localFile * @throws JSchException * @throws IOException */ public void scpFileFromRemoteServer(String host, String user, String password, String remoteFile, String localFile) throws JSchException, IOException { String prefix = null; if (new File(localFile).isDirectory()) { prefix = localFile + File.separator; } JSch jsch = new JSch(); Session session = jsch.getSession(user, host, 22); // username and password will be given via UserInfo interface. UserInfo userInfo = new UserInformation(password); session.setUserInfo(userInfo); session.connect(); // exec 'scp -f remoteFile' remotely String command = "scp -f " + remoteFile; Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); // get I/O streams for remote scp OutputStream out = channel.getOutputStream(); InputStream in = channel.getInputStream(); channel.connect(); byte[] buf = new byte[1024]; // send '\0' buf[0] = 0; out.write(buf, 0, 1); out.flush(); readRemoteFileAndWriteToLocalFile(localFile, prefix, out, in, buf); session.disconnect(); }
@Test public void testSecureCopyFile() throws JSchException, IOException { final JschBuilder mockJschBuilder = mock(JschBuilder.class); final JSch mockJsch = mock(JSch.class); final Session mockSession = mock(Session.class); final ChannelExec mockChannelExec = mock(ChannelExec.class); final byte [] bytes = {0}; final ByteArrayOutputStream out = new ByteArrayOutputStream(); when(mockChannelExec.getInputStream()).thenReturn(new TestInputStream()); when(mockChannelExec.getOutputStream()).thenReturn(out); when(mockSession.openChannel(eq("exec"))).thenReturn(mockChannelExec); when(mockJsch.getSession(anyString(), anyString(), anyInt())).thenReturn(mockSession); when(mockJschBuilder.build()).thenReturn(mockJsch); when(Config.mockSshConfig.getJschBuilder()).thenReturn(mockJschBuilder); when(Config.mockRemoteCommandExecutorService.executeCommand(any(RemoteExecCommand.class))).thenReturn(mock(RemoteCommandReturnInfo.class)); final String source = BinaryDistributionControlServiceImplTest.class.getClassLoader().getResource("binarydistribution/copy.txt").getPath(); binaryDistributionControlService.secureCopyFile("someHost", source, "./build/tmp"); verify(Config.mockSshConfig).getJschBuilder(); assertEquals("C0644 12 copy.txt\nsome content\0", out.toString(StandardCharsets.UTF_8)); }
/** * Convenience method to execute a command on the given remote session, using the given string * as part of the error if it fails to run. * * @param roboRioSession The ssh session of the roboRio * @param command The command to execute * @param errorString The error string to put in the exception if an error occurs. The return * code will be appended to the end * @throws JSchException If an ssh error occurs * @throws IOException Thrown if there is an io error, or if the command fails to run */ private void executeCommand(Session roboRioSession, String command, String errorString) throws JSchException, IOException { // Extract the JRE m_logger.debug("Running command " + command); ChannelExec channel = (ChannelExec) roboRioSession.openChannel(EXEC_COMMAND); channel.setCommand(command); channel.connect(); int sleepCount = 0; // Sleep for up to 10 seconds while we wait for the command to execute, checking every 100 milliseconds do { try { Thread.sleep(100); } catch (InterruptedException e) { m_logger.warn("Interrupted exception while waiting for command " + command + " to finish", e); } } while (!channel.isClosed() && sleepCount++ < 100); int res = channel.getExitStatus(); if (res != SUCCESS) { m_logger.debug("Error with command " + command); throw new IOException(errorString + " " + res); } channel.disconnect(); }
public void executeCommand(final String command) throws IOException { // Cliente SSH final JSch jsch = new JSch(); Properties props = new Properties(); props.put("StrictHostKeyChecking", "no"); try { Session session = jsch.getSession(user, host, 22); session.setConfig(props); session.setPassword(password); session.connect(); java.util.logging.Logger.getLogger(RemoteShell.class.getName()) .log(Level.INFO, session.getServerVersion()); Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); // Daqui para baixo é somente para imprimir a saida channel.setInputStream(null); ((ChannelExec) channel).setErrStream(System.err); InputStream in = channel.getInputStream(); channel.connect(); byte[] tmp = new byte[1024]; while (true) { while (in.available() > 0) { int i = in.read(tmp, 0, 1024); if (i < 0) { break; } System.out.print(new String(tmp, 0, i)); } if (channel.isClosed()) { if (in.available() > 0) { continue; } System.out .println("exit-status: " + channel.getExitStatus()); break; } try { Thread.sleep(1000); } catch (Exception ee) { } } channel.disconnect(); session.disconnect(); } catch (JSchException ex) { java.util.logging.Logger.getLogger(RemoteShell.class.getName()) .log(Level.SEVERE, null, ex); } }
private void streamOutput(ChannelExec channel, InputStream in) throws IOException { byte[] buf = new byte[1024]; while (true) { while (in.available() > 1) { int bytesRead = in.read(buf); if (bytesRead < 0 ) break; this.out.write(buf); } if (channel.isClosed()) break; sleepForOneSecondAndIgnoreInterrupt(); } }
public static void executeCommandNoResponse( Session sessionObj, String command ) throws JSchException, IOException { logger.debug( "Starting to execute command [" + maskedPasswordString( command ) + "]" ); if ( sessionObj != null && command != null && !"".equals( command ) ) { Channel channel = null; try { channel = sessionObj.openChannel( "exec" ); ( (ChannelExec) channel ).setCommand( command ); channel.setInputStream( null ); ( (ChannelExec) channel ).setErrStream( System.err ); channel.getInputStream(); channel.connect(); /* We do not care about whether the command succeeds or not */ if ( channel.isClosed() && channel.getExitStatus() != 0 ) { logger.debug( "Command exited with error code " + channel.getExitStatus() ); } } catch ( Exception e ) { logger.error( "Received exception during command execution", e ); } finally { if ( channel != null && channel.isConnected() ) { channel.disconnect(); } logger.debug( "End of execution of command [" + maskedPasswordString( command ) + "]" ); } } }
public static void executeCommandNoResponse( Session sessionObj, String command ) throws JSchException, IOException { logger.debug( "Starting to execute command [" + command + "]" ); if ( sessionObj != null && command != null && !"".equals( command ) ) { Channel channel = null; try { channel = sessionObj.openChannel( "exec" ); ( (ChannelExec) channel ).setCommand( command ); channel.setInputStream( null ); ( (ChannelExec) channel ).setErrStream( System.err ); channel.getInputStream(); channel.connect(); /* We do not care about whether the command succeeds or not */ if ( channel.isClosed() && channel.getExitStatus() != 0 ) { logger.debug( "Command exited with error code " + channel.getExitStatus() ); } } catch ( Exception e ) { logger.error( "Received exception during command execution", e ); } finally { if ( channel != null && channel.isConnected() ) { channel.disconnect(); } logger.debug( "End of execution of command [" + command + "]" ); } } }
@SneakyThrows public static int exec(@Nonnull String host, int port, @Nonnull String username, @Nonnull String password, @Nonnull String cmd) { JSch jSch = new JSch(); Session session = jSch.getSession(username, host, port); session.setPassword(password); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(cmd); ((ChannelExec) channel).setInputStream(null); ((ChannelExec) channel).setErrStream(System.err); InputStream inputStream = channel.getInputStream(); channel.connect(); log.info("# successful connect to server [{}:{}]", host, port); log.info("# exec cmd [{}]", cmd); StringBuilder sb = new StringBuilder(); byte[] bytes = new byte[1024]; int exitStatus; while (true) { while (inputStream.available() > 0) { int i = inputStream.read(bytes, 0, 1024); if (i < 0) { break; } sb.append(new String(bytes, 0, i, StandardCharsets.UTF_8)); } if (channel.isClosed()) { if (inputStream.available() > 0) { continue; } exitStatus = channel.getExitStatus(); break; } Thread.sleep(1000); } if (StringUtils.isNotEmpty(sb)) { log.info("# cmd-rs \n" + sb); } channel.disconnect(); session.disconnect(); log.info("# successful disconnect to server [{}:{}]", host, port); return exitStatus; }
/** * Force create directories, if it exists it won't do anything * * @param path * @throws IOException * @throws RuntimeConfigurationException */ private void forceCreateDirectories(@NotNull final String path) throws IOException, RuntimeConfigurationException { Session session = connect(ssh.get()); try { ChannelExec channelExec = (ChannelExec) session.openChannel("exec"); List<String> commands = Arrays.asList( String.format("mkdir -p %s", path), String.format("cd %s", path), String.format("mkdir -p %s", FileUtilities.CLASSES), String.format("mkdir -p %s", FileUtilities.LIB), String.format("cd %s", path + FileUtilities.SEPARATOR + FileUtilities.CLASSES), "rm -rf *" ); for (String command : commands) { consoleView.print(EmbeddedLinuxJVMBundle.getString("pi.deployment.command") + command + NEW_LINE, ConsoleViewContentType.SYSTEM_OUTPUT); } channelExec.setCommand(LinuxCommand.builder().commands(commands).build().toString()); channelExec.connect(); channelExec.disconnect(); } catch (JSchException e) { setErrorOnUI(e.getMessage()); } }
/** * Runs that java app with the specified command and then takes the console output from target to host machine * * @param path * @param cmd * @throws IOException */ private void runJavaApp(@NotNull final String path, @NotNull final String cmd) throws IOException, RuntimeConfigurationException { consoleView.print(NEW_LINE + EmbeddedLinuxJVMBundle.getString("pi.deployment.build") + NEW_LINE + NEW_LINE, ConsoleViewContentType.SYSTEM_OUTPUT); Session session = connect(ssh.get()); consoleView.setSession(session); try { ChannelExec channelExec = (ChannelExec) session.openChannel("exec"); channelExec.setOutputStream(System.out, true); channelExec.setErrStream(System.err, true); List<String> commands = Arrays.asList( String.format("%s kill -9 $(ps -efww | grep \"%s\"| grep -v grep | tr -s \" \"| cut -d\" \" -f2)", params.isRunAsRoot() ? "sudo" : "", params.getMainclass()), String.format("cd %s", path), String.format("tar -xvf %s.tar", consoleView.getProject().getName()), "rm *.tar", cmd); for (String command : commands) { consoleView.print(EmbeddedLinuxJVMBundle.getString("pi.deployment.command") + command + NEW_LINE, ConsoleViewContentType.SYSTEM_OUTPUT); } channelExec.setCommand(LinuxCommand.builder().commands(commands).build().toString()); channelExec.connect(); checkOnProcess(channelExec); } catch (JSchException e) { setErrorOnUI(e.getMessage()); } }
/** * finally: will close the connection. * * @return the response on singe request */ public ResponseOnSingeRequest executeSshCommand() { ResponseOnSingeRequest sshResponse = new ResponseOnSingeRequest(); try { session = startSshSessionAndObtainSession(); channel = sessionConnectGenerateChannel(session); sshResponse = executeAndGenResponse((ChannelExec) channel); } catch (Exception e) { sshResponse = genErrorResponse(e); } finally { if (session != null) session.disconnect(); if (channel != null) channel.disconnect(); } return sshResponse; }
@Test public void sessionConnectGenerateChannelTestWithSuperUser() { Session session = mock(Session.class); ChannelExec channel = mock(ChannelExec.class); OutputStream out = mock(OutputStream.class); sshProvider = new SshProvider(sshMetaPasswordSuperUser, hostIpSample); try { when(session.openChannel("exec")).thenReturn(channel); when(channel.getOutputStream()).thenReturn(out); sshProvider.sessionConnectGenerateChannel(session); } catch (Exception e) { e.printStackTrace(); } }
@Test public void testExecuteAndGenResponse() { // ResponseOnSingeReq (Channel channel) { ResponseOnSingeRequest sshResponse = new ResponseOnSingeRequest(); ChannelExec channel = mock(ChannelExec.class); sshProvider = new SshProvider(sshMetaKey, hostIpSample); String stdoutStr = "Mon Sep 14 21:52:27 UTC 2015"; InputStream in = new ByteArrayInputStream( stdoutStr.getBytes(Charsets.UTF_8)); try { when(channel.getInputStream()).thenReturn(in); when(channel.isClosed()).thenReturn(false).thenReturn(true); sshResponse = sshProvider.executeAndGenResponse(channel); } catch (IOException e) { e.printStackTrace(); } logger.info(sshResponse.toString()); }
@Test public void executeAndGenResponseThrowsExceptionTest() { // ResponseOnSingeReq (Channel channel) { ResponseOnSingeRequest sshResponse = new ResponseOnSingeRequest(); ChannelExec channel = mock(ChannelExec.class); sshProvider = new SshProvider(sshMetaKey, hostIpSample); String stdoutStr = "Mon Sep 14 21:52:27 UTC 2015"; InputStream in = new ByteArrayInputStream( stdoutStr.getBytes(Charsets.UTF_8)); try { when(channel.getInputStream()).thenReturn(in); when(channel.isClosed()).thenReturn(false).thenThrow( new RuntimeException("fake exception")); sshResponse = sshProvider.executeAndGenResponse(channel); } catch (Throwable e) { logger.info("expected exception {}", "String", e); } logger.info(sshResponse.toString()); }
public void execute(String command) { if (session == null) { throw new IllegalArgumentException("Session object is null."); } if (command != null && command.isEmpty()) { throw new IllegalArgumentException("SSH command is blank."); } try { session.connect(); Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); ((ChannelExec) channel).setPty(false); channel.connect(); channel.disconnect(); session.disconnect(); } catch (JSchException e) { throw new RuntimeException("Error durring SSH command execution. Command: " + command); } }
@Override public CliProcess execute(String command) { try { Session session = createSession(); LOGGER.info("Executing on {}@{}:{}: {}", session.getUserName(), session.getHost(), session.getPort(), command); ChannelExec channel = (ChannelExec) session.openChannel("exec"); channel.setCommand(command); JSchCliProcess process = new JSchCliProcess(session, channel); process.connect(); return process; } catch (JSchException | IOException exception) { throw new RuntimeException(exception); } }
@Override public void upload(Path file, String remotePath) { Session session = null; try { session = createSession(); LOGGER.info("Uploading {} onto {}@{}:{}:{}", file, session.getUserName(), session.getHost(), session.getPort(), remotePath); ChannelExec channel = (ChannelExec) session.openChannel("exec"); String command = "scp -t " + remotePath; channel.setCommand(command); OutputStream out = channel.getOutputStream(); InputStream in = channel.getInputStream(); sendSCPFile(file, channel, in, out); } catch (JSchException | IOException exception) { Throwables.propagate(exception); } finally { if (session != null) { session.disconnect(); } } }
private void sendSCPFile(Path file, ChannelExec channel, InputStream in, OutputStream out) throws IOException, JSchException { channel.connect(); try { checkAck(channel, in); sendSCPHandshake(file, out); checkAck(channel, in); try (InputStream fileStream = newInputStream(file)) { ByteStreams.copy(fileStream, out); } out.write(0); out.flush(); checkAck(channel, in); } finally { channel.disconnect(); } }
@Test(timeout = 5000) public void testExec(TestContext context) throws Exception { startShell(); Session session = createSession("paulo", "secret", false); session.connect(); ChannelExec channel = (ChannelExec) session.openChannel("exec"); channel.setCommand("the-command arg1 arg2"); channel.connect(); InputStream in = channel.getInputStream(); StringBuilder input = new StringBuilder(); while (!input.toString().equals("the_output")) { int a = in.read(); if (a == -1) { break; } input.append((char)a); } OutputStream out = channel.getOutputStream(); out.write("the_input".getBytes()); out.flush(); while (channel.isConnected()) { Thread.sleep(1); } assertEquals(2, channel.getExitStatus()); session.disconnect(); }
@SuppressWarnings("resource") public String exec(String command, InputStream opt) throws JSchException, IOException { ChannelExec channel = (ChannelExec) getSession().openChannel("exec"); try { channel.setCommand(command); channel.setInputStream(opt); InputStream in = channel.getInputStream(); InputStream err = channel.getErrStream(); channel.connect(); Scanner s = new Scanner(err).useDelimiter("\\A"); error = s.hasNext() ? s.next() : null; s = new Scanner(in).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } finally { channel.disconnect(); } }
@Override public OutputStream scpPut(String remoteFilePath, long length, String mode) throws Throwable { open(); if (!Pattern.matches("\\d{4}", mode)) { throw new IllegalArgumentException("Invalid file mode: " + mode); } String dir = PathUtil.getParentDirectory(remoteFilePath); String fileName = PathUtil.getFileName(remoteFilePath); // exec 'scp -t -d remoteTargetDirectory' remotely String command = "scp -t -d \"" + dir + "\""; final ChannelExec channel = (ChannelExec) _jschSession.openChannel("exec"); ((ChannelExec) channel).setCommand(command); // get I/O streams for remote scp OutputStream out = channel.getOutputStream(); final InputStream in = channel.getInputStream(); channel.connect(); return new ScpOutputStream(channel, in, out, new FileInfo(mode, length, fileName)); }
public static String activateAPK(String host, String user, String password, String cmd ){ String s = null; try{ java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); JSch jsch = new JSch(); Session session=jsch.getSession(user, host, 22); session.setPassword(password); session.setConfig(config); session.connect(); //System.out.println("Connected "+user+"@"+host); Channel channel=session.openChannel("exec"); ((ChannelExec)channel).setCommand(cmd); ((ChannelExec)channel).setErrStream(System.err); channel.connect(); BufferedReader stdInput = new BufferedReader(new InputStreamReader(channel.getInputStream())); String line = null; while ((line = stdInput.readLine()) != null) s = (s == null)?line:(s+"\n"+line); channel.disconnect(); session.disconnect(); //System.out.println("disconnected"); }catch(Exception e){ //e.printStackTrace(); } return (s != null)?s:"no matches found"; }
private void executeCommand(String command) throws JSchException, IOException, InterruptedException { connectIfNot(); Channel channel = session.openChannel("exec"); try { ((ChannelExec) channel).setCommand(command); ((ChannelExec) channel).setErrStream(System.err); ((ChannelExec) channel).setPty(true); ((ChannelExec) channel).setPtyType("vt100"); channel.setInputStream(null); channel.setOutputStream(System.out); InputStream in = channel.getInputStream(); logger.info("ssh exec command => {}", command); channel.connect(); byte[] buffer = new byte[1024]; while (true) { while (in.available() > 0) { int i = in.read(buffer, 0, 1024); if (i < 0) break; messageLogger.info(new String(buffer, 0, i, Charsets.UTF_8)); } if (channel.isClosed()) { logger.info("ssh exec exit status => " + channel.getExitStatus()); break; } Thread.sleep(1000); } if (channel.getExitStatus() != 0) { throw new JSchException("failed to run command, command=" + command); } } finally { channel.disconnect(); } }
@Override public int exec() throws IOException { try { final ChannelExec channel = ChannelExec.class.cast( this.session.openChannel("exec") ); channel.setErrStream(this.stderr, false); channel.setOutputStream(this.stdout, false); channel.setInputStream(this.stdin, false); channel.setCommand(this.command); channel.connect(); Logger.info(this, "$ %s", this.command); return this.exec(channel); } catch (final JSchException ex) { throw new IOException(ex); } finally { this.session.disconnect(); } }
/** * Tests that {@link Execution} executes a command and returns a correct * exit code. * @throws Exception If fails */ @Test public void executesCommand() throws Exception { final Session session = Mockito.mock(Session.class); final ChannelExec channel = Mockito.mock(ChannelExec.class); Mockito.when(session.openChannel(Mockito.anyString())) .thenReturn(channel); Mockito.when(channel.isClosed()).thenReturn(Boolean.TRUE); Mockito.when(channel.getExitStatus()).thenReturn( ExecutionTest.EXIT_CODE ); MatcherAssert.assertThat( new Execution.Default( "hello", new DeadInputStream(), new ByteArrayOutputStream(), new ByteArrayOutputStream(), session ).exec(), Matchers.equalTo(ExecutionTest.EXIT_CODE) ); }
/** * Download a file from the remote server into an OutputStream * * @param remoteFile * Path and name of the remote file. * @param localTarget * OutputStream to store the data. * @throws IOException * in case of network problems * @throws RemoteScpException * in case of problems on the target system (connection ok) */ @SuppressWarnings("unused") public void get(String remoteFile, OutputStream localTarget) throws IOException, RemoteScpException { ChannelExec channel = null; if (remoteFile == null || localTarget == null) { throw new IllegalArgumentException("Null argument."); } String cmd = "scp -p -f " + remoteFile; try { channel = getExecChannel(); channel.setCommand(cmd); receiveStream(channel, remoteFile, localTarget); channel.disconnect(); } catch (JSchException e) { if (channel != null) { channel.disconnect(); } throw new IOException("Error during SCP transfer. " + e.getMessage(), e); } }
/** * Initiates an SCP sequence but stops after getting fileinformation header * * @param remoteFile * to get information for * @return the file information got * @throws IOException * in case of network problems * @throws RemoteScpException * in case of problems on the target system (connection ok) */ public FileInfo getFileinfo(String remoteFile) throws IOException, RemoteScpException { ChannelExec channel = null; FileInfo fileInfo = null; if (remoteFile == null) { throw new IllegalArgumentException("Null argument."); } String cmd = "scp -p -f \"" + remoteFile + "\""; try { channel = getExecChannel(); channel.setCommand(cmd); fileInfo = receiveStream(channel, remoteFile, null); channel.disconnect(); } catch (JSchException e) { throw new IOException("Error during SCP transfer. " + e.getMessage(), e); } finally { if (channel != null) { channel.disconnect(); } } return fileInfo; }
/** * @param positiveExitCodes The exit codes to consider the command a success. This will normally be only 0, but in case of * f.ex. 'diff' 1 is also ok. */ public void runCommand(String server, String command, int commandTimeout, String quotes, int[] positiveExitCodes) throws Exception { RemoteCommand remoteCommand = new RemoteCommand(server, command, quotes); log.info("Running JSch command: " + remoteCommand); BufferedReader inReader = null; BufferedReader errReader = null; JSch jsch = new JSch(); Session session = jsch.getSession("test", TestEnvironment.DEPLOYMENT_SERVER); setupJSchIdentity(jsch); session.setConfig("StrictHostKeyChecking", "no"); long startTime = System.currentTimeMillis(); session.connect(); Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(remoteCommand.commandAsString()); channel.setInputStream(null); ((ChannelExec) channel).setErrStream(null); InputStream in = channel.getInputStream(); InputStream err = ((ChannelExec) channel).getErrStream(); channel.connect(1000); log.debug("Channel connected, command: " + remoteCommand.commandAsString()); inReader = new BufferedReader(new InputStreamReader(in)); errReader = new BufferedReader(new InputStreamReader(err)); int numberOfSecondsWaiting = 0; int maxNumberOfSecondsToWait = 60*10; while (true) { if (channel.isClosed()) { log.info("Command finished in " + (System.currentTimeMillis() - startTime) / 1000 + " seconds. " + "Exit code was " + channel.getExitStatus()); boolean errorOccured = true; for (int positiveExit:positiveExitCodes) { if (positiveExit == channel.getExitStatus()) { errorOccured = false; break; } } if (errorOccured || err.available() > 0) { throw new RuntimeException("Failed to run command, exit code " + channel.getExitStatus()); } break; } else if ( numberOfSecondsWaiting > maxNumberOfSecondsToWait) { log.info("Command not finished after " + maxNumberOfSecondsToWait + " seconds. " + "Forcing disconnect."); channel.disconnect(); break; } try { Thread.sleep(1000); String s; while ((s = inReader.readLine()) != null) { if (!s.trim().isEmpty()) log.debug("ssh: " + s); } while ((s = errReader.readLine()) != null) { if (!s.trim().isEmpty()) log.warn("ssh error: " + s); } } catch (InterruptedException ie) { } } }
private static String execCommand(Session session, TextStream out, String command) throws JSchException, IOException { ChannelExec channel = (ChannelExec) session.openChannel("exec"); channel.setCommand(command); channel.setInputStream(null); channel.setErrStream(System.err); InputStream in = channel.getInputStream(); channel.connect(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); int count = 0; String line = br.readLine(); StringWriter sw = new StringWriter(); while (line != null) { String info = String.format("%d: %s\n", count++, line); sw.append(info); out.appendText(info); line = br.readLine(); } session.disconnect(); return sw.toString(); }
/** * Gets the channel. * * @param session * the session * @param command * the command * @return the channel * @throws JSchException * the j sch exception * @throws IOException * Signals that an I/O exception has occurred. */ public static Channel getChannel(Session session, String command) throws JSchException, IOException { session.connect(); LOGGER.debug("Session ["+session+"] connected"); Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); InputStream in = channel.getInputStream(); channel.connect(); ((ChannelExec) channel).setErrStream(System.err); byte[] tmp = new byte[RemotingConstants.ONE_ZERO_TWO_FOUR]; while (true) { while (in.available() > 0) { int i = in.read(tmp, 0, RemotingConstants.ONE_ZERO_TWO_FOUR); if (i < 0){ break; } } if (channel.isClosed()) { break; } } LOGGER.debug("Channel connected, mode [exec]"); return channel; }
private String runCommand(Session session, String command) throws IOException, JSchException { Channel channel = session.openChannel("exec"); //$NON-NLS-1$ ((ChannelExec) channel).setCommand(command); channel.connect(); InputStream inputStream = channel.getInputStream(); String result = IOUtils.toString(inputStream); IOUtils.closeQuietly(inputStream); channel.disconnect(); return result; }
/** * This version takes a command to run, and then returns a wrapper instance * that exposes all the standard state of the channel (stdin, stdout, * stderr, exit status, etc). Channel connection is established if establishConnection * is true. * * @param command the command to execute. * @param establishConnection true if establish channel connetction within this method. * @return a Channel with access to all streams and the exit code. * @throws IOException if it is so. * @throws SshException if there are any ssh problems. * @see #executeCommandReader(String) */ @Override public synchronized ChannelExec executeCommandChannel(String command, Boolean establishConnection) throws SshException, IOException { if (!isConnected()) { throw new IOException("Not connected!"); } try { ChannelExec channel = (ChannelExec)connectSession.openChannel("exec"); channel.setCommand(command); if (establishConnection) { channel.connect(); } return channel; } catch (JSchException ex) { throw new SshException(ex); } }
protected String exec(String command) { final ChannelExec channel = openChannel(command); final String res; try { final InputStream in = getInputStream(channel); connect(channel); res = readOutput(command, channel, in); } finally { try { if (channel.isConnected()) channel.disconnect(); } catch (Exception e) { log.warn("failed to disconnect channel", e); } } return res; }