com.jcraft.jsch.Channel类的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(11.7k)|赞(0)|评价(0)|浏览(158)

本文整理了Java中com.jcraft.jsch.Channel类的一些代码示例,展示了Channel类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Channel类的具体详情如下:
包路径:com.jcraft.jsch.Channel
类名称:Channel

Channel介绍

[英]The abstract base class for the different types of channel which may be associated with a Session.

It should be considered an implementation detail that Channel implements Runnable – external code never has to invoke the #run method.
[中]可与会话关联的不同类型通道的抽象基类。
应该将通道实现Runnable视为一个实现细节——外部代码永远不必调用#run方法。

代码示例

代码示例来源:origin: alibaba/jstorm

Session session = jsch.getSession(user, host, 22);
session.setPassword("123fj");
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
OutputStream out = channel.getOutputStream();
InputStream in = channel.getInputStream();
channel.connect();
channel.disconnect();
session.disconnect();

代码示例来源:origin: alibaba/jstorm

session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.setInputStream(null);
InputStream in = channel.getInputStream();
channel.connect();
  if (channel.isClosed()) {
    if (in.available() > 0) continue;
    if (channel.getExitStatus() != 0)
      throw new Exception("exitStatus:" + channel.getExitStatus());
channel.disconnect();
session.disconnect();

代码示例来源:origin: looly/hutool

/**
 * 关闭会话通道
 * 
 * @param channel 会话通道
 * @since 4.0.3
 */
public static void close(Channel channel) {
  if (channel != null && channel.isConnected()) {
    channel.disconnect();
  }
}

代码示例来源:origin: apache/kylin

session.connect();
  Channel channel = session.openChannel("exec");
  ((ChannelExec) channel).setCommand(command);
  channel.setInputStream(null);
  ((ChannelExec) channel).setErrStream(System.err);
  InputStream in = channel.getInputStream();
  InputStream err = ((ChannelExec) channel).getErrStream();
  channel.connect();
    if (channel.isClosed()) {
      if (in.available() > 0)
        continue;
      exitCode = channel.getExitStatus();
      logger.info("[" + username + "@" + hostname + "] Command exit-status: " + exitCode);
      throw new Exception("Remote command not finished within " + timeoutSeconds + " seconds.");
  channel.disconnect();
  session.disconnect();
  return new SSHClientOutput(exitCode, text.toString());
} catch (Exception e) {

代码示例来源:origin: Impetus/jumbune

public static String getDaemonProcessId(Session session, String daemon) throws JSchException, IOException {
  String command = PID_COMMAND_PREFIX + daemon + PID_COMMAND_SUFFIX;
  session.connect();
  Channel channel = session.openChannel("shell");
  channel.connect();
  OutputStream os = channel.getOutputStream();
  InputStream is = channel.getInputStream();
  PrintStream ps = new PrintStream(os, true);
  String pid = "";
  try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
    ps.println(command);
    for (String line = br.readLine(); line != null; line = br.readLine()) {
      if (line.contains(daemon) && !line.contains("awk ")) {
        pid = line.split("\\s+")[1];
      }
    }
  }
  LOGGER.debug(" exit status - " + channel.getExitStatus() + ", daemon = " + daemon + ", PID = " + pid);
  if (channel != null && channel.isConnected()) {
    channel.disconnect();
  }
  if (session != null && session.isConnected()) {
    session.disconnect();
  }
  return pid;
}

代码示例来源:origin: apache/usergrid

String message;
try {
  channel = session.openChannel( "exec" );
  ( ( ChannelExec ) channel ).setCommand( command.getCommand() );
  channel.connect();
  BufferedReader inputReader = new BufferedReader( new InputStreamReader( channel.getInputStream() ) );
  BufferedReader errorReader = new BufferedReader( new InputStreamReader(
      ( ( ChannelExec ) channel ).getErrStream() ) );
  try {
    if ( channel != null ) {
      channel.disconnect();

代码示例来源:origin: hyperic/hq

JSch jsch = new JSch();
  session = jsch.getSession(user, host, 22);
  session.setConfig("PreferredAuthentications", "password");
  session.setUserInfo(this);
  session.setTimeout(10 * 1000);
  session.connect();
  channel = session.openChannel("exec");
  ((ChannelExec) channel).setCommand(cmd);
  channel.setInputStream(System.in);
  InputStream in = channel.getInputStream();
  channel.connect();
  while (!channel.isClosed()) {
    while (in.available() > 0) {
      int i = in.read(tmp, 0, 1024);
  System.out.println("exit-status: " + channel.getExitStatus());
} finally {
  if (channel != null) {
    channel.disconnect();

代码示例来源:origin: net.sourceforge.expectj/expectj

public void start() throws IOException {
  if (m_toSocket != null) {
    // We've probably been created by the SshSpawn(Channel) constructor,
    // or start() has already been called.  No need to do anything
    // anyway.
    return;
  }
  try {
    m_session = new JSch().getSession(m_username, m_remoteHost, m_remotePort) ;
    m_session.setPassword(m_password) ;
    m_session.setConfig("StrictHostKeyChecking", "no");
    m_session.connect() ;
    m_channel = m_session.openChannel("shell") ;
    m_channel.connect() ;
  } catch (JSchException e) {
    throw new IOException("Unable to establish SSH session/channel", e) ;
  }
  m_toSocket = m_channel.getInputStream() ;
  m_fromSocket = m_channel.getOutputStream();
}

代码示例来源:origin: pentaho/pentaho-kettle

public void login( String password ) throws KettleJobException {
 this.password = password;
 s.setPassword( this.getPassword() );
 try {
  java.util.Properties config = new java.util.Properties();
  config.put( "StrictHostKeyChecking", "no" );
  // set compression property
  // zlib, none
  String compress = getCompression();
  if ( compress != null ) {
   config.put( COMPRESSION_S2C, compress );
   config.put( COMPRESSION_C2S, compress );
  }
  s.setConfig( config );
  s.connect();
  Channel channel = s.openChannel( "sftp" );
  channel.connect();
  c = (ChannelSftp) channel;
 } catch ( JSchException e ) {
  throw new KettleJobException( e );
 }
}

代码示例来源:origin: Microsoft/azure-tools-for-java

String resultErr = "";
try {
 Channel channel = session.openChannel("exec");
 ((ChannelExec)channel).setCommand(command);
 InputStream commandOutput = channel.getInputStream();
 InputStream commandErr = ((ChannelExec) channel).getErrStream();
 channel.connect();
 byte[] tmp  = new byte[4096];
 while(true){
   resultErr += new String(tmp, 0, i);
  if(channel.isClosed()){
   if(commandOutput.available()>0) continue;
   if (getExitStatus) {
    result += "exit-status: " + channel.getExitStatus();
    if (withErr) {
     result += "\n With error:\n" + resultErr;
 channel.disconnect();

代码示例来源:origin: caskdata/cdap

@Override
public SSHProcess execute(List<String> commands) throws IOException {
 try {
  Channel channel = session.openChannel("exec");
  try {
   ChannelExec channelExec = (ChannelExec) channel;
   // Should get the stream before connecting.
   // Otherwise JSch will write the output to some default stream, causing data missing from
   // the InputStream that acquired later.
   SSHProcess process = new DefaultSSHProcess(channelExec, channelExec.getOutputStream(),
                         channelExec.getInputStream(), channelExec.getErrStream());
   channelExec.setCommand(commands.stream().collect(Collectors.joining(";")));
   channelExec.connect();
   return process;
  } catch (Exception e) {
   channel.disconnect();
   throw e;
  }
 } catch (JSchException e) {
  throw new IOException(e);
 }
}

代码示例来源:origin: io.vertx/vertx-shell

@Test
public void testRead(TestContext context) throws Exception {
 Async async = context.async();
 termHandler = term -> {
  term.stdinHandler(s -> {
   context.assertEquals("hello", s);
   async.complete();
  });
 };
 startShell();
 Session session = createSession("paulo", "secret", false);
 session.connect();
 Channel channel = session.openChannel("shell");
 channel.connect();
 OutputStream out = channel.getOutputStream();
 out.write("hello".getBytes());
 out.flush();
 channel.disconnect();
 session.disconnect();
}

代码示例来源:origin: eBay/parallec

/**
 * 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;
}

代码示例来源:origin: looly/hutool

/**
 * 打开Shell连接
 * 
 * @param session Session会话
 * @return {@link ChannelShell}
 * @since 4.0.3
 */
public static ChannelShell openShell(Session session) {
  Channel channel;
  try {
    channel = session.openChannel("shell");
    channel.connect();
  } catch (JSchException e) {
    throw new JschRuntimeException(e);
  }
  return (ChannelShell) channel;
}

代码示例来源:origin: org.apache.airavata/gsissh

Channel channel = session.openChannel("exec");
StandardOutReader stdOutReader = new StandardOutReader();
((ChannelExec) channel).setCommand(command);
((ChannelExec) channel).setErrStream(stdOutReader.getStandardError());
try {
  channel.connect();
} catch (JSchException e) {
  channel.disconnect();
      " on server - " + session.getHost() + ":" + session.getPort() +
      " connecting user name - "
      + session.getUserName(), e);
channel.disconnect();

代码示例来源:origin: hadooparchitecturebook/fraud-detection-tutorial

try {
 System.out.println("1");
 Channel channel = session.openChannel("exec");
 System.out.println("2");
 InputStream in = channel.getInputStream();
 System.out.println("3");
 ((ChannelExec) channel).setCommand(getCommand());
 channel.connect();
 System.out.println("5");
   strBuffer.append(new String(tmp, 0, i));
  if (channel.isClosed()) {
   if (in.available() > 0) continue;
   System.out.println("exit-status: " + channel.getExitStatus());
   break;
 processResults(session.getHost(), session.getPort(), results, listener);

代码示例来源:origin: com.pastdev/jsch-extension

public void connect( SocketFactory socketFactory, String host, int port, int timeout ) throws Exception {
  logger.debug( "connecting session" );
  session.connect();
  channel = session.getStreamForwarder( host, port );
  inputStream = channel.getInputStream();
  outputStream = channel.getOutputStream();
  channel.connect( timeout );
}

代码示例来源:origin: io.vertx/vertx-shell

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);
 }
}

代码示例来源:origin: Adobe-Consulting-Services/acs-aem-commons

@Override
public InputStream getStream() throws IOException {
  try {
    URI uri = new URI(encodeUriParts(getSourcePath()));
    if (channel == null || channel.isClosed()) {
      channel = getSessionForHost(uri).openChannel("sftp");
      channel.connect();
    }
    ChannelSftp sftpChannel = (ChannelSftp) channel;
    currentStream = sftpChannel.get(decodeUriParts(uri.getRawPath()));
    return currentStream;
  } catch (URISyntaxException ex) {
    Logger.getLogger(FileOrRendition.class.getName()).log(Level.SEVERE, null, ex);
    throw new IOException("Bad URI format", ex);
  } catch (JSchException ex) {
    Logger.getLogger(FileOrRendition.class.getName()).log(Level.SEVERE, null, ex);
    throw new IOException("Error with connection", ex);
  } catch (SftpException ex) {
    Logger.getLogger(FileOrRendition.class.getName()).log(Level.SEVERE, null, ex);
    throw new IOException("Error retrieving file", ex);
  }
}

代码示例来源:origin: io.openscore.content/score-ssh

try {
  Channel channel = session.openChannel(SHELL_CHANNEL);
  ((ChannelShell) channel).setPty(usePseudoTerminal);
  ((ChannelShell) channel).setAgentForwarding(agentForwarding);
  InputStream in = new ByteArrayInputStream(command.getBytes(characterSet));
  channel.setInputStream(in);
  OutputStream out = new ByteArrayOutputStream();
  channel.setOutputStream(out);
  OutputStream err = new ByteArrayOutputStream();
  channel.setExtOutputStream(err);
  channel.connect(connectTimeout);
  } while (!channel.isEOF() && commandTimeout > 0);
  result.setStandardError(((ByteArrayOutputStream) err).toString(characterSet));
  channel.disconnect();
  result.setExitCode(channel.getExitStatus());
  return result;
} catch (JSchException | UnsupportedEncodingException e) {

相关文章