當前位置: 首頁>>代碼示例>>Java>>正文


Java ChannelExec類代碼示例

本文整理匯總了Java中com.jcraft.jsch.ChannelExec的典型用法代碼示例。如果您正苦於以下問題:Java ChannelExec類的具體用法?Java ChannelExec怎麽用?Java ChannelExec使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


ChannelExec類屬於com.jcraft.jsch包,在下文中一共展示了ChannelExec類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: executeCommand

import com.jcraft.jsch.ChannelExec; //導入依賴的package包/類
/**
 * 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;
    }
}
 
開發者ID:opencord,項目名稱:vtn,代碼行數:34,代碼來源:RemoteIpCommandUtil.java

示例2: connect

import com.jcraft.jsch.ChannelExec; //導入依賴的package包/類
/**
 * 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;
}
 
開發者ID:pcingola,項目名稱:BigDataScript,代碼行數:25,代碼來源:Ssh.java

示例3: executeCommand

import com.jcraft.jsch.ChannelExec; //導入依賴的package包/類
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);
    }
}
 
開發者ID:nailtonvieira,項目名稱:pswot-cloud-java-spring-webapp,代碼行數:54,代碼來源:RemoteShell.java

示例4: executeCommandReader

import com.jcraft.jsch.ChannelExec; //導入依賴的package包/類
/**
 * 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);
    }
}
 
開發者ID:sonyxperiadev,項目名稱:gerrit-events,代碼行數:25,代碼來源:SshConnectionImpl.java

示例5: connectAndExecute

import com.jcraft.jsch.ChannelExec; //導入依賴的package包/類
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;

}
 
開發者ID:saiscode,項目名稱:kheera,代碼行數:54,代碼來源:SeleniumGridManager.java

示例6: execute

import com.jcraft.jsch.ChannelExec; //導入依賴的package包/類
@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);
    }
}
 
開發者ID:prestodb,項目名稱:tempto,代碼行數:17,代碼來源:JSchSshClient.java

示例7: sendCommand

import com.jcraft.jsch.ChannelExec; //導入依賴的package包/類
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();
}
 
開發者ID:lucee,項目名稱:Lucee,代碼行數:22,代碼來源:SSHManager.java

示例8: runCommand

import com.jcraft.jsch.ChannelExec; //導入依賴的package包/類
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;
}
 
開發者ID:yeokm1,項目名稱:nus-soc-print,代碼行數:24,代碼來源:SSHConnectivity.java

示例9: createTCPProxy

import com.jcraft.jsch.ChannelExec; //導入依賴的package包/類
private void createTCPProxy() {
	try {
		final String cleanCommand = String.format("sudo docker ps -a | grep 'hours ago' | awk '{print $1}' | xargs --no-run-if-empty sudo docker rm",
				containerName,
				this.targetHost,
				this.targetPort,
				sourceIPs,
				ImageRegistry.get().tcpProxy());
		LOGGER.info("Establishing SSH shell");
		ssh = SshUtil.getInstance()
				.createSshSession(TestConfiguration.proxyHostUsername(), getProxyHost());
		ssh.connect();
		LOGGER.debug("Connected to ssh console");

		final ChannelExec cleanChannel = (ChannelExec) ssh.openChannel("exec");
		cleanChannel.setPty(true);
		cleanChannel.setCommand(cleanCommand);
		cleanChannel.setInputStream(null);
		cleanChannel.setOutputStream(System.err);

		LOGGER.debug("Executing command: '{}'", cleanCommand);
		cleanChannel.connect();
		cleanChannel.disconnect();

		final String command = String.format("sudo docker run -it --name %s --net=host --rm -e AB_OFF=true -e TARGET_HOST=%s -e TARGET_PORT=%s -e TARGET_VIA=%s %s",
				containerName,
				this.targetHost,
				this.targetPort,
				sourceIPs,
				ImageRegistry.get().tcpProxy());
		LOGGER.info("Establishing SSH shell");
		ssh = SshUtil.getInstance()
				.createSshSession(TestConfiguration.proxyHostUsername(), getProxyHost());
		ssh.connect();
		LOGGER.debug("Connected to ssh console");

		final ChannelExec channel = (ChannelExec) ssh.openChannel("exec");
		channel.setPty(true);
		channel.setCommand(command);
		channel.setInputStream(null);
		channel.setOutputStream(System.err);

		LOGGER.debug("Executing command: '{}'", command);
		channel.connect();
		final LineIterator li = IOUtils.lineIterator(new InputStreamReader(channel.getInputStream()));
		final Pattern portLine = Pattern.compile(".*Listening on port ([0-9]*).*$");
		listenPort = 0;
		while (li.hasNext()) {
			final String line = li.next();
			LOGGER.trace("Shell line: {}", line);
			final Matcher m = portLine.matcher(line);
			if (m.matches()) {
				listenPort = Integer.parseInt(m.group(1));
				LOGGER.info("Connection listening on port {}", listenPort);
				break;
			}
		}
		channel.disconnect();
	} catch (final JSchException | IOException e) {
		LOGGER.debug("Error in creating SSH connection to proxy host", e);
		throw new IllegalStateException("Cannot open SSH connection", e);
	}
}
 
開發者ID:xtf-cz,項目名稱:xtf,代碼行數:64,代碼來源:ProxiedConnectionManager.java

示例10: scpFileFromRemoteServer

import com.jcraft.jsch.ChannelExec; //導入依賴的package包/類
/**
 * 
 * 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();		
}
 
開發者ID:capitalone,項目名稱:Hydrograph,代碼行數:50,代碼來源:SCPUtility.java

示例11: testSecureCopyFile

import com.jcraft.jsch.ChannelExec; //導入依賴的package包/類
@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));
}
 
開發者ID:cerner,項目名稱:jwala,代碼行數:21,代碼來源:BinaryDistributionControlServiceImplTest.java

示例12: executeSSH

import com.jcraft.jsch.ChannelExec; //導入依賴的package包/類
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;
}
 
開發者ID:rajeshrv,項目名稱:SpringMicroservice,代碼行數:41,代碼來源:DeploymentEngine.java

示例13: executeCommand

import com.jcraft.jsch.ChannelExec; //導入依賴的package包/類
/**
 * 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();
}
 
開發者ID:wpilibsuite,項目名稱:java-installer,代碼行數:35,代碼來源:DeployController.java

示例14: streamOutput

import com.jcraft.jsch.ChannelExec; //導入依賴的package包/類
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();
  }
}
 
開發者ID:mleoking,項目名稱:PhET,代碼行數:18,代碼來源:SshCommand.java

示例15: executeCommandNoResponse

import com.jcraft.jsch.ChannelExec; //導入依賴的package包/類
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 ) + "]" );
        }
    }
}
 
開發者ID:vmware,項目名稱:OHMS,代碼行數:39,代碼來源:SshUtil.java


注:本文中的com.jcraft.jsch.ChannelExec類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。