当前位置: 首页>>代码示例>>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;未经允许,请勿转载。