当前位置: 首页>>代码示例>>Java>>正文


Java Channel.isClosed方法代码示例

本文整理汇总了Java中com.jcraft.jsch.Channel.isClosed方法的典型用法代码示例。如果您正苦于以下问题:Java Channel.isClosed方法的具体用法?Java Channel.isClosed怎么用?Java Channel.isClosed使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在com.jcraft.jsch.Channel的用法示例。


在下文中一共展示了Channel.isClosed方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: executeCommand

import com.jcraft.jsch.Channel; //导入方法依赖的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

示例2: connectAndExecute

import com.jcraft.jsch.Channel; //导入方法依赖的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

示例3: testClose

import com.jcraft.jsch.Channel; //导入方法依赖的package包/类
private void testClose(TestContext context, Consumer<Term> closer) throws Exception {
  Async async = context.async();
  termHandler = term -> {
    term.closeHandler(v -> {
      async.complete();
    });
    closer.accept(term);
  };
  startShell();
  Session session = createSession("paulo", "secret", false);
  session.connect();
  Channel channel = session.openChannel("shell");
  channel.connect();
  while (channel.isClosed()) {
    Thread.sleep(10);
  }
}
 
开发者ID:vert-x3,项目名称:vertx-shell,代码行数:18,代码来源:SSHServerTest.java

示例4: waitForChannelClosure

import com.jcraft.jsch.Channel; //导入方法依赖的package包/类
/**
 * Blocks until the given channel is close or the timout is reached
 *
 * @param channel the channel to wait for
 * @param timoutInMs the timeout
 */
private static void waitForChannelClosure(Channel channel, long timoutInMs) {
    final long start = System.currentTimeMillis();
    final long until = start + timoutInMs;
    try {
        while (!channel.isClosed() && System.currentTimeMillis() < until) {
            Thread.sleep(CLOSURE_WAIT_INTERVAL);
        }
        logger.trace("Time waited for channel closure: " + (System.currentTimeMillis() - start));
    } catch (InterruptedException e) {
        logger.trace("Interrupted", e);
    }
    if (!channel.isClosed()) {
        logger.trace("Channel not closed in timely manner!");
    }
}
 
开发者ID:sonyxperiadev,项目名称:gerrit-events,代码行数:22,代码来源:SshConnectionImpl.java

示例5: onOutput

import com.jcraft.jsch.Channel; //导入方法依赖的package包/类
public void onOutput(Channel channel) {
    try {
        StringBuffer pbsOutput = new StringBuffer("");
        InputStream inputStream =  channel.getInputStream();
        byte[] tmp = new byte[1024];
        do {
            while (inputStream.available() > 0) {
                int i = inputStream.read(tmp, 0, 1024);
                if (i < 0) break;
                pbsOutput.append(new String(tmp, 0, i));
            }
        } while (!channel.isClosed()) ;
        String output = pbsOutput.toString();
        this.setStdOutputString(output);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }

}
 
开发者ID:apache,项目名称:airavata,代码行数:20,代码来源:StandardOutReader.java

示例6: executeCommandNoResponse

import com.jcraft.jsch.Channel; //导入方法依赖的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

示例7: executeCommandNoResponse

import com.jcraft.jsch.Channel; //导入方法依赖的package包/类
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 + "]" );
        }
    }
}
 
开发者ID:vmware,项目名称:OHMS,代码行数:39,代码来源:EsxiSshUtil.java

示例8: exec

import com.jcraft.jsch.Channel; //导入方法依赖的package包/类
@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;
}
 
开发者ID:srarcbrsent,项目名称:tc,代码行数:56,代码来源:TcSshBin.java

示例9: executeCommand

import com.jcraft.jsch.Channel; //导入方法依赖的package包/类
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();
    }
}
 
开发者ID:neowu,项目名称:cmn-project,代码行数:37,代码来源:SSH.java

示例10: runCommand

import com.jcraft.jsch.Channel; //导入方法依赖的package包/类
/**
 * @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) {
        }
    }
}
 
开发者ID:netarchivesuite,项目名称:netarchivesuite-svngit-migration,代码行数:74,代码来源:TestEnvironmentManager.java

示例11: getChannel

import com.jcraft.jsch.Channel; //导入方法依赖的package包/类
/**
 * 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;
}
 
开发者ID:Impetus,项目名称:jumbune,代码行数:42,代码来源:JschUtil.java

示例12: validateCommandExecution

import com.jcraft.jsch.Channel; //导入方法依赖的package包/类
/**
 * This method validates the executed command
 * 
 * @param channel
 *            SSH channel
 * @param in
 *            input stream
 * @return Error message if any

 *             If any error occurred
 */
private static String validateCommandExecution(Channel channel, InputStream in) throws IOException, InterruptedException {
	StringBuilder sb = new StringBuilder();
	byte[] tmp = new byte[Constants.ONE_ZERO_TWO_FOUR];
	while (true) {
		while (in.available() > 0) {
			int i = in.read(tmp, 0,Constants.ONE_ZERO_TWO_FOUR);
			if (i < 0){
				break;
			}
			sb.append(new String(tmp, 0, i));
		}
		if (channel.isClosed()) {
			break;
		}
		Thread.sleep(Constants.THOUSAND);
	}
	return sb.toString();
}
 
开发者ID:Impetus,项目名称:jumbune,代码行数:30,代码来源:SessionEstablisher.java

示例13: getRemoteHomePath

import com.jcraft.jsch.Channel; //导入方法依赖的package包/类
private String getRemoteHomePath() {
  final String getHomeCommand = "pwd";
  try {
    final Channel channel = this.remoteSession.openChannel("exec");
    ((ChannelExec) channel).setCommand(getHomeCommand);
    channel.setInputStream(null);
    final InputStream stdout = channel.getInputStream();
    channel.connect();

    byte[] tmp = new byte[1024];
    StringBuilder homePath = new StringBuilder();
    while (true) {
      while (stdout.available() > 0) {
        final int len = stdout.read(tmp, 0, 1024);
        if (len < 0) {
          break;
        }
        homePath = homePath.append(new String(tmp, 0, len, StandardCharsets.UTF_8));
      }
      if (channel.isClosed()) {
        if (stdout.available() > 0) {
          continue;
        }
        break;
      }
    }
    return homePath.toString().trim();
  } catch (final JSchException | IOException ex) {
    throw new RuntimeException("Unable to retrieve home directory from " +
        this.remoteHostName + " with the pwd command", ex);
  }
}
 
开发者ID:apache,项目名称:reef,代码行数:33,代码来源:SshProcessContainer.java

示例14: execCmd

import com.jcraft.jsch.Channel; //导入方法依赖的package包/类
/**
 * Execute command
 * @param host
 * @param user
 * @param passwd
 * @param cmd
 * @return String the reply of remote session
 */
public String execCmd (String host, String user, String passwd, String cmd){
    String replyy = "";
    String reply = null;
    try{
        JSch jsch=new JSch();
        Session session=jsch.getSession(user, host, 22);
        UserInfo ui = new MyUserInfo(passwd);
        session.setUserInfo(ui);
        session.setTimeout(600000);
        session.connect();
        Channel channel=session.openChannel("exec");
        ((ChannelExec)channel).setCommand(cmd);
        channel.setInputStream(null);
        InputStreamReader in = new InputStreamReader(channel.getInputStream());
        OutputStreamWriter out = new OutputStreamWriter(channel.getOutputStream());
        BufferedWriter bw = new BufferedWriter(out);
        BufferedReader br = new BufferedReader(in);
        channel.connect();
        while ((reply = br.readLine()) != null) {
            bw.write(reply);
            replyy=replyy+"\n"+reply;
            bw.flush();
            Thread.sleep(100);
        }
        while(true){
            if(channel.isClosed()){
                break;
            } try{
                Thread.sleep(1500);
            } catch(Exception ee){
            }
        }
        in.close();
        out.close();
        br.close();
        bw.close();
        channel.disconnect();
        session.disconnect();
    }
    catch(Exception e){
        log.error("ERROR , Possible no connection with : "+user+" "+passwd+ " "+host+"\n\t\t please check LAN and vpn connection or host");
    }
    return replyy;
}
 
开发者ID:GiannisPapadakis,项目名称:seletest,代码行数:53,代码来源:SSHUtils.java

示例15: outputCommandSSH

import com.jcraft.jsch.Channel; //导入方法依赖的package包/类
/**
 * Execute SSH command and return output
 * @param username The ssh user
 * @param host The host to connect
 * @param key The ssh key
 * @param commandssh The command to launch
 * @return the output of the command
 */
public String outputCommandSSH(String username, String host, String key, String commandssh){
	String res = "";
	try{
	      JSch jsch=new JSch();
	      java.util.Properties config = new java.util.Properties();
	      config.put("StrictHostKeyChecking", "no"); //avoid host key checking

	      int SSH_port = 22; 
	      
	      jsch.addIdentity(key , "passphrase");

	      Session session=jsch.getSession(username, host, SSH_port); //SSH connection
	 
			if(new Configuration().Debug){
				System.out.println("Connection to "+host+" on the port "+SSH_port+" with key: "+key+" and username: "+username);
			}
	      
	      // username and passphrase will be given via UserInfo interface.
	      UserInfo ui=new MyUserInfo();
	      session.setUserInfo(ui);
	      session.setConfig(config);
	      session.connect();

	      Channel channel=session.openChannel("exec"); // open channel for exec command
	      ((ChannelExec)channel).setCommand(commandssh);

	      channel.setInputStream(null);

	      ((ChannelExec)channel).setErrStream(System.err);
		
	      InputStream in=channel.getInputStream();
		
	      channel.connect();
		
		/*
		 * get output ssh command launched
		 */
		byte[] tmp=new byte[1024];
		while(true){
			while(in.available()>0){
				int i=in.read(tmp, 0, 1024);
				if(i<0)break;
				res += new String(tmp, 0, i);
				//System.out.print(new String(tmp, 0, i));
			}
			if(channel.isClosed()){
				if(in.available()>0) continue; 
				if(new Configuration().Debug){
					System.out.println("exit-status: "+channel.getExitStatus());
				}
				break;
			}
			try{Thread.sleep(1000);}catch(Exception ee){}
		}
		channel.disconnect();
		session.disconnect();
		}
		
		catch(Exception e){
			System.out.println(e);
		}
	return res;
}
 
开发者ID:franblas,项目名称:Shavadoop,代码行数:72,代码来源:CommandSSH.java


注:本文中的com.jcraft.jsch.Channel.isClosed方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。