com.jcraft.jsch.ChannelExec Java Examples
The following examples show how to use
com.jcraft.jsch.ChannelExec.
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: RemoteLauncherCommands.java From gemfirexd-oss with Apache License 2.0 | 8 votes |
/** * Connect to a remote host via SSH and execute a command. * * @param host * Host to connect to * @param user * User to login with * @param password * Password for the user * @param command * Command to execute * @return The result of the command execution */ private Result executeSshCommand(final String host, final String user, final String password, final String command) { StringBuilder result = new StringBuilder(); try { JSch jsch = new JSch(); Session session = jsch.getSession(user, host, 22); session.setUserInfo(createUserInfo(password)); session.connect(5000); ChannelExec channel = (ChannelExec) session.openChannel("exec"); channel.setCommand(command); channel.setInputStream(null); 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; result.append(new String(tmp, 0, i)); } if (channel.isClosed()) { break; } } channel.disconnect(); session.disconnect(); } catch (Exception jex) { return createResult(Result.Status.ERROR, jex.getMessage()); } return createResult(Result.Status.OK, result.toString()); }
Example #2
Source File: JSchExecutorTests.java From vividus with Apache License 2.0 | 7 votes |
@Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void shouldExecuteSuccessfullyWithoutAgentForwarding() throws Exception { ServerConfiguration server = getDefaultServerConfiguration(); JSch jSch = mock(JSch.class); whenNew(JSch.class).withNoArguments().thenReturn(jSch); Session session = mock(Session.class); when(jSch.getSession(server.getUsername(), server.getHost(), server.getPort())).thenReturn(session); ChannelExec channelExec = mockChannelOpening(session); SshOutput actual = new TestJSchExecutor().execute(server, COMMANDS); assertEquals(SSH_OUTPUT, actual); InOrder ordered = inOrder(jSch, session, channelExec); ordered.verify(jSch).addIdentity(IDENTITY_NAME, server.getPrivateKey().getBytes(StandardCharsets.UTF_8), server.getPublicKey().getBytes(StandardCharsets.UTF_8), server.getPassphrase().getBytes(StandardCharsets.UTF_8)); verifyFullConnection(ordered, server, session, channelExec); }
Example #3
Source File: CommandRunner.java From jsch-extension with MIT License | 6 votes |
public ChannelExecWrapper( Session session, String command, InputStream stdIn, OutputStream stdOut, OutputStream stdErr ) throws JSchException, IOException { this.command = command; this.channel = (ChannelExec) session.openChannel( "exec" ); if ( stdIn != null ) { this.passedInStdIn = stdIn; this.channel.setInputStream( stdIn ); } if ( stdOut != null ) { this.passedInStdOut = stdOut; this.channel.setOutputStream( stdOut ); } if ( stdErr != null ) { this.passedInStdErr = stdErr; this.channel.setErrStream( stdErr ); } this.channel.setCommand( command ); this.channel.connect(); }
Example #4
Source File: JSchExecutorTests.java From vividus with Apache License 2.0 | 6 votes |
@Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void shouldExecuteSuccessfullyWithAgentForwarding() throws Exception { ServerConfiguration server = getDefaultServerConfiguration(); server.setAgentForwarding(true); JSch jSch = mock(JSch.class); whenNew(JSch.class).withNoArguments().thenReturn(jSch); mockStatic(ConnectorFactory.class); ConnectorFactory connectorFactory = mock(ConnectorFactory.class); when(ConnectorFactory.getDefault()).thenReturn(connectorFactory); Connector connector = mock(Connector.class); when(connectorFactory.createConnector()).thenReturn(connector); RemoteIdentityRepository remoteIdentityRepository = mock(RemoteIdentityRepository.class); whenNew(RemoteIdentityRepository.class).withArguments(connector).thenReturn(remoteIdentityRepository); doNothing().when(jSch).setIdentityRepository(remoteIdentityRepository); Session session = mock(Session.class); when(jSch.getSession(server.getUsername(), server.getHost(), server.getPort())).thenReturn(session); ChannelExec channelExec = mockChannelOpening(session); SshOutput actual = new TestJSchExecutor().execute(server, COMMANDS); assertEquals(SSH_OUTPUT, actual); InOrder ordered = inOrder(jSch, session, channelExec); ordered.verify(jSch).setIdentityRepository(remoteIdentityRepository); verifyFullConnection(ordered, server, session, channelExec); }
Example #5
Source File: JSchExecutorTests.java From vividus with Apache License 2.0 | 6 votes |
@Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void shouldFailOnCommandExecutionError() throws Exception { ServerConfiguration server = getDefaultServerConfiguration(); server.setPublicKey(null); JSch jSch = mock(JSch.class); whenNew(JSch.class).withNoArguments().thenReturn(jSch); Session session = mock(Session.class); when(jSch.getSession(server.getUsername(), server.getHost(), server.getPort())).thenReturn(session); ChannelExec channelExec = mockChannelOpening(session); JSchException jSchException = new JSchException(); CommandExecutionException exception = assertThrows(CommandExecutionException.class, () -> new TestJSchExecutor() { @Override protected SshOutput executeCommand(ServerConfiguration serverConfig, Commands commands, ChannelExec channel) throws JSchException { throw jSchException; } }.execute(server, COMMANDS)); assertEquals(jSchException, exception.getCause()); InOrder ordered = inOrder(jSch, session, channelExec); verifyFullConnection(ordered, server, session, channelExec); }
Example #6
Source File: SshExecutor.java From vividus with Apache License 2.0 | 6 votes |
@Override protected SshOutput executeCommand(ServerConfiguration serverConfig, Commands commands, ChannelExec channel) throws JSchException, IOException { channel.setAgentForwarding(serverConfig.isAgentForwarding()); SshOutput executionOutput = new SshOutput(); try (ByteArrayOutputStream errorStream = new ByteArrayOutputStream()) { channel.setCommand(commands.getJoinedCommands()); channel.setErrStream(errorStream); channel.connect(); executionOutput.setOutputStream(readChannelInputStream(channel)); executionOutput.setErrorStream(new String(errorStream.toByteArray(), StandardCharsets.UTF_8)); executionOutput.setExitStatus(channel.getExitStatus()); } return executionOutput; }
Example #7
Source File: SSHPushWorker.java From uyuni with GNU General Public License v2.0 | 6 votes |
/** * Wait for a given {@link ChannelExec} to be closed. * Will close channel if maxWait is set and exceeded. * @param channel the channel */ private void waitForChannelClosed(ChannelExec channel) { long startTime = System.currentTimeMillis(); while (!channel.isClosed()) { // Check to see if we have been waiting too long, converts ms to minutes long elapsedTimeInMins = TimeUnit.MILLISECONDS.toMinutes(System.currentTimeMillis() - startTime); if (maxWait > 0 && elapsedTimeInMins > maxWait) { log.error("Task took too long to complete"); channel.disconnect(); } try { Thread.sleep(1000); } catch (InterruptedException e) { // Should not happen } } }
Example #8
Source File: DeploymentEngine.java From if1007 with MIT License | 6 votes |
private boolean executeSSH(){ //get deployment descriptor, instead of this hard coded. // or execute a script on the target machine which download artifact from nexus String command ="nohup java -jar -Dserver.port=8091 ./work/codebox/chapter6/chapter6.search/target/search-1.0.jar &"; try{ System.out.println("Executing "+ command); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); JSch jsch = new JSch(); Session session=jsch.getSession("rajeshrv", "localhost", 22); session.setPassword("rajeshrv"); session.setConfig(config); session.connect(); System.out.println("Connected"); ChannelExec channelExec = (ChannelExec)session.openChannel("exec"); InputStream in = channelExec.getInputStream(); channelExec.setCommand(command); channelExec.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; int index = 0; while ((line = reader.readLine()) != null) { System.out.println(++index + " : " + line); } channelExec.disconnect(); session.disconnect(); System.out.println("Done!"); }catch(Exception e){ e.printStackTrace(); return false; } return true; }
Example #9
Source File: BinaryDistributionControlServiceImplTest.java From jwala with Apache License 2.0 | 6 votes |
@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)); }
Example #10
Source File: Ssh.java From BigDataScript with Apache License 2.0 | 6 votes |
/** * 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; }
Example #11
Source File: SSHHandlerTarget.java From embeddedlinux-jvmdebugger-intellij with Apache License 2.0 | 6 votes |
/** * 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()); } }
Example #12
Source File: SSHHandlerTarget.java From embeddedlinux-jvmdebugger-intellij with Apache License 2.0 | 6 votes |
/** * 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()); } }
Example #13
Source File: SshProviderMockTest.java From parallec with Apache License 2.0 | 6 votes |
@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(); } }
Example #14
Source File: SshProviderMockTest.java From parallec with Apache License 2.0 | 6 votes |
@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()); }
Example #15
Source File: SshProviderMockTest.java From parallec with Apache License 2.0 | 6 votes |
@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()); }
Example #16
Source File: Scp.java From ant-ivy with Apache License 2.0 | 6 votes |
/** * 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); } }
Example #17
Source File: Scp.java From ant-ivy with Apache License 2.0 | 6 votes |
/** * 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; }
Example #18
Source File: SessionEstablisher.java From jumbune with GNU Lesser General Public License v3.0 | 6 votes |
/** * This method execute the given command over SSH * * @param session * @param command * Command to be executed * @throws JSchException * @throws IOException * @throws InterruptedException */ static String executeCommand(Session session, String command) throws JSchException, IOException { InputStream in = null; Channel channel = null; String msg = null; try { channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); ((ChannelExec) channel).setErrStream(System.err); in = channel.getInputStream(); channel.connect(); msg = validateCommandExecution(channel, in); } catch (InterruptedException e) { CONSOLE_LOGGER.error(e); } finally { if (in != null) { in.close(); } if (channel != null) { channel.disconnect(); } } return msg; }
Example #19
Source File: SshProvider.java From parallec with Apache License 2.0 | 6 votes |
/** * 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; }
Example #20
Source File: SshConnectionImpl.java From gerrit-events with MIT License | 6 votes |
/** * 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); } }
Example #21
Source File: SshExecutor.java From vividus with Apache License 2.0 | 6 votes |
private String readChannelInputStream(ChannelExec channel) throws IOException { try (InputStream in = channel.getInputStream(); InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8); StringWriter stringWriter = new StringWriter()) { while (true) { IOUtils.copy(reader, stringWriter); if (channel.isClosed()) { if (in.available() > 0) { continue; } return stringWriter.toString(); } Sleeper.sleep(Duration.ofSeconds(1)); } } }
Example #22
Source File: SshConnectionImpl.java From gerrit-events with MIT License | 6 votes |
/** * 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); } }
Example #23
Source File: ScpConnection.java From jsch-extension with MIT License | 6 votes |
public ScpConnection( SessionFactory sessionFactory, String path, ScpMode scpMode, CopyMode copyMode ) throws JSchException, IOException { this.session = sessionFactory.newSession(); logger.debug( "connecting session" ); session.connect(); String command = getCommand( path, scpMode, copyMode ); channel = session.openChannel( "exec" ); logger.debug( "setting exec command to '{}'", command ); ((ChannelExec) channel).setCommand( command ); logger.debug( "connecting channel" ); channel.connect(); outputStream = channel.getOutputStream(); inputStream = channel.getInputStream(); if ( scpMode == ScpMode.FROM ) { writeAck(); } else if ( scpMode == ScpMode.TO ) { checkAck(); } this.entryStack = new Stack<CurrentEntry>(); }
Example #24
Source File: SshRepository.java From ant-ivy with Apache License 2.0 | 5 votes |
/** * Tries to create a directory path on the target system * * @param path * to create * @param session * to use */ private void makePath(String path, Session session) throws IOException { ChannelExec channel = null; String trimmed = path; try { while (trimmed.length() > 0 && trimmed.charAt(trimmed.length() - 1) == fileSeparator) { trimmed = trimmed.substring(0, trimmed.length() - 1); } if (trimmed.length() == 0 || checkExistence(trimmed, session)) { return; } int nextSlash = trimmed.lastIndexOf(fileSeparator); if (nextSlash > 0) { String parent = trimmed.substring(0, nextSlash); makePath(parent, session); } channel = getExecChannel(session); String mkdir = replaceArgument(createDirCommand, trimmed); Message.debug("SShRepository: trying to create path: " + mkdir); channel.setCommand(mkdir); StringBuilder stdOut = new StringBuilder(); StringBuilder stdErr = new StringBuilder(); readSessionOutput(channel, stdOut, stdErr); } finally { if (channel != null) { channel.disconnect(); } } }
Example #25
Source File: SSHInfrastructureV2.java From scheduling with GNU Affero General Public License v3.0 | 5 votes |
private void declareLostAndThrow(String errMsg, List<String> nodesUrl, ChannelExec chan, ByteArrayOutputStream baos, Exception e) throws RMException { String lf = System.lineSeparator(); StringBuilder sb = new StringBuilder(errMsg); sb.append(lf).append(" > Process exit code: ").append(chan.getExitStatus()); sb.append(lf).append(" > Process output: ").append(lf).append(new String(baos.toByteArray())); this.multipleDeclareDeployingNodeLost(nodesUrl, sb.toString()); throw new RMException(errMsg, e); }
Example #26
Source File: SshRepository.java From ant-ivy with Apache License 2.0 | 5 votes |
/** * check for existence of file or dir on target system * * @param filePath * to the object to check * @param session * to use * @return true: object exists, false otherwise */ private boolean checkExistence(String filePath, Session session) throws IOException { Message.debug("SShRepository: checkExistence called: " + filePath); ChannelExec channel = null; channel = getExecChannel(session); String fullCmd = replaceArgument(existCommand, filePath); channel.setCommand(fullCmd); StringBuilder stdOut = new StringBuilder(); StringBuilder stdErr = new StringBuilder(); readSessionOutput(channel, stdOut, stdErr); return channel.getExitStatus() == 0; }
Example #27
Source File: SftpLightWeightFileSystem.java From incubator-gobblin with Apache License 2.0 | 5 votes |
@Override public FileStatus getFileStatus(Path path) throws IOException { ChannelSftp channelSftp = null; ChannelExec channelExec1 = null; ChannelExec channelExec2 = null; try { channelSftp = this.fsHelper.getSftpChannel(); SftpATTRS sftpAttrs = channelSftp.stat(HadoopUtils.toUriPath(path)); FsPermission permission = new FsPermission((short) sftpAttrs.getPermissions()); channelExec1 = this.fsHelper.getExecChannel("id " + sftpAttrs.getUId()); String userName = IOUtils.toString(channelExec1.getInputStream()); channelExec2 = this.fsHelper.getExecChannel("id " + sftpAttrs.getGId()); String groupName = IOUtils.toString(channelExec2.getInputStream()); FileStatus fs = new FileStatus(sftpAttrs.getSize(), sftpAttrs.isDir(), 1, 0l, sftpAttrs.getMTime(), sftpAttrs.getATime(), permission, StringUtils.trimToEmpty(userName), StringUtils.trimToEmpty(groupName), path); return fs; } catch (SftpException e) { throw new IOException(e); } finally { safeDisconnect(channelSftp); safeDisconnect(channelExec1); safeDisconnect(channelExec2); } }
Example #28
Source File: SshUtilities.java From hortonmachine with GNU General Public License v3.0 | 5 votes |
/** * Launch a command on the remote host and exit once the command is done. * * @param session the session to use. * @param command the command to launch. * @return the output of the command. * @throws JSchException * @throws IOException */ private static String launchACommand( Session session, String command ) throws JSchException, IOException { Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); ((ChannelExec) channel).setErrStream(System.err); InputStream in = channel.getInputStream(); channel.connect(); StringBuilder sb = new StringBuilder(); 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()) { if (in.available() > 0) continue; System.out.println("exitstatus: " + channel.getExitStatus()); break; } try { Thread.sleep(1000); } catch (Exception ee) { } } channel.disconnect(); String remoteResponseStr = sb.toString().trim(); return remoteResponseStr; }
Example #29
Source File: SshUtilities.java From hortonmachine with GNU General Public License v3.0 | 5 votes |
/** * Upload a file to the remote host via scp. * * @param session the session to use. * @param localFile the local file path. * @param remoteFile the remote file path to copy into. * @throws Exception */ public static void uploadFile( Session session, String localFile, String remoteFile ) throws Exception { boolean ptimestamp = true; // exec 'scp -t rfile' remotely String command = "scp " + (ptimestamp ? "-p" : "") + " -t " + 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(); if (checkAck(in) != 0) { throw new RuntimeException(); } File _lfile = new File(localFile); if (ptimestamp) { command = "T" + (_lfile.lastModified() / 1000) + " 0"; // The access time should be sent here, // but it is not accessible with JavaAPI ;-< command += (" " + (_lfile.lastModified() / 1000) + " 0\n"); out.write(command.getBytes()); out.flush(); if (checkAck(in) != 0) { throw new RuntimeException(); } } // send "C0644 filesize filename", where filename should not include '/' long filesize = _lfile.length(); command = "C0644 " + filesize + " "; if (localFile.lastIndexOf('/') > 0) { command += localFile.substring(localFile.lastIndexOf('/') + 1); } else { command += localFile; } command += "\n"; out.write(command.getBytes()); out.flush(); if (checkAck(in) != 0) { throw new RuntimeException(); } // send a content of lfile FileInputStream fis = new FileInputStream(localFile); byte[] buf = new byte[1024]; while( true ) { int len = fis.read(buf, 0, buf.length); if (len <= 0) break; out.write(buf, 0, len); // out.flush(); } fis.close(); fis = null; // send '\0' buf[0] = 0; out.write(buf, 0, 1); out.flush(); if (checkAck(in) != 0) { throw new RuntimeException(); } out.close(); channel.disconnect(); }
Example #30
Source File: SshUtilities.java From hortonmachine with GNU General Public License v3.0 | 5 votes |
/** * Launch a command on the remote host and exit even if the command is not done (useful for launching daemons). * * @param session the session to use. * @param command the command to launch. * @return the output of the command. * @throws JSchException * @throws IOException */ private static String launchACommandAndExit( Session session, String command ) throws JSchException, IOException { Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); ((ChannelExec) channel).setErrStream(System.err); InputStream in = channel.getInputStream(); channel.connect(); StringBuilder sb = new StringBuilder(); 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()) { if (in.available() > 0) continue; break; } try { if (sb.length() > 0) { break; } Thread.sleep(1000); } catch (Exception ee) { } } channel.disconnect(); String remoteResponseStr = sb.toString().trim(); return remoteResponseStr; }