Java 类com.jcraft.jsch.Channel 实例源码

项目:LesPatternsDuSwag    文件:SFTPUploader.java   
private void upload(String filename) {
    try {
        JSch jsch = new JSch();
        Session session = jsch.getSession(login, server, 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("sftp");
        channel.connect();
        ChannelSftp channelSftp = (ChannelSftp) channel;
        channelSftp.cd(workingDirectory);
        File f = new File(filename);

        channelSftp.put(new FileInputStream(f), f.getName());

        f.delete();

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
项目:vtn    文件:RemoteIpCommandUtil.java   
/**
 * 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;
    }
}
项目:bamboobsc    文件:SFtpClientUtils.java   
@SuppressWarnings("unchecked")
public static Vector<LsEntry> getRemoteFileList(String user, String password, String addr, int port, String cwd) throws JSchException, 
    SftpException, Exception {

    Session session = getSession(user, password, addr, port);   
    Vector<LsEntry> lsVec=null;
    Channel channel = session.openChannel("sftp");
    channel.connect();
    ChannelSftp sftpChannel = (ChannelSftp) channel;
    try {
        lsVec=(Vector<LsEntry>)sftpChannel.ls(cwd); //sftpChannel.lpwd()
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        sftpChannel.exit();
        channel.disconnect();
        session.disconnect();           
    }       
    return lsVec;       
}
项目:KitchenSink    文件:App.java   
/**
 * Lists directory files on remote server.
 * @throws URISyntaxException 
 * @throws JSchException 
 * @throws SftpException 
 */
private void listFiles() throws URISyntaxException, JSchException, SftpException {

    JSch jsch = new JSch();
    JSch.setLogger(new JschLogger());
    setupSftpIdentity(jsch);

    URI uri = new URI(sftpUrl);
    Session session = jsch.getSession(sshLogin, uri.getHost(), 22);
    session.setConfig("StrictHostKeyChecking", "no");
    session.connect();
    System.out.println("Connected to SFTP server");

    Channel channel = session.openChannel("sftp");
    channel.connect();
    ChannelSftp sftpChannel = (ChannelSftp) channel;
    Vector<LsEntry> directoryEntries = sftpChannel.ls(uri.getPath());
    for (LsEntry file : directoryEntries) {
        System.out.println(String.format("File - %s", file.getFilename()));
    }
    sftpChannel.exit();
    session.disconnect();
}
项目:aos-FileCoreLibrary    文件:SftpFileEditor.java   
@Override
public boolean rename(String newName){
    Channel channel = null;
    try {
         channel = SFTPSession.getInstance().getSFTPChannel(mUri);
        ((ChannelSftp)channel).rename(mUri.getPath(), new File(new File(mUri.getPath()).getParentFile(), newName).getAbsolutePath());
        channel.disconnect();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        if(channel!=null&&channel.isConnected())
            channel.disconnect();
    }
    return false;
}
项目:aos-FileCoreLibrary    文件:SftpFileEditor.java   
@Override
public boolean move(Uri uri) {
    if(!mUri.getScheme().equals(uri.getScheme())|| !mUri.getHost().equals(uri.getHost())||mUri.getPort()!=uri.getPort())
        return false;
    Channel channel = null;
    try {
        channel = SFTPSession.getInstance().getSFTPChannel(mUri);
        ((ChannelSftp)channel).rename(mUri.getPath(),uri.getPath());
        channel.disconnect();
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        if(channel!=null&&channel.isConnected())
            channel.disconnect();
    }
    return false;
}
项目:aos-FileCoreLibrary    文件:SftpFileEditor.java   
@Override
public boolean exists() {
    Channel channel = null;
    try {
        channel = SFTPSession.getInstance().getSFTPChannel(mUri);
        SftpATTRS attrs =  ((ChannelSftp)channel).stat(mUri.getPath());
        channel.disconnect();
        return attrs !=null;
    } catch (Exception e) {
        if(channel!=null&&channel.isConnected())
            channel.disconnect();
        e.printStackTrace();
    }finally {
        if(channel!=null&&channel.isConnected())
            channel.disconnect();
    }
    return false;
}
项目:gerrit-events    文件:SshConnectionImpl.java   
/**
 * 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);
    }
}
项目:BigDataScript    文件:Ssh.java   
/**
 * 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;
}
项目:nus-soc-print    文件:SSHConnectivity.java   
public void uploadFile(InputStream toBePrinted, String directory, String filename, SftpProgressMonitor progressMonitor) throws SftpException, JSchException, IOException {
    if(session== null){
        throw new JSchException(context.getString(R.string.misc_connection_not_set_up));
    }

    Channel channel = session.openChannel("sftp");

    channel.connect();
    ChannelSftp channelSftp = (ChannelSftp)channel;

    try{
        channelSftp.mkdir(directory);
    } catch (SftpException e){
        //If cannot make directory, means directory already created
    }
    channelSftp.cd(directory);
    channelSftp.put(toBePrinted, filename, progressMonitor, ChannelSftp.OVERWRITE);
    channelSftp.disconnect();
}
项目:kheera    文件:SeleniumGridManager.java   
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;

}
项目:keepass2android    文件:SftpStorage.java   
ChannelSftp init(String filename) throws JSchException, UnsupportedEncodingException {
    jsch = new JSch();
    ConnectionInfo ci = splitStringToConnectionInfo(filename);

    Session session = jsch.getSession(ci.username, ci.host, ci.port);
    UserInfo ui = new SftpUserInfo(ci.password);
    session.setUserInfo(ui);

    session.connect();

    Channel channel = session.openChannel("sftp");
    channel.connect();
    ChannelSftp c = (ChannelSftp) channel;

    logDebug("success: init Sftp");
    return c;

}
项目:bamboobsc    文件:SFtpClientUtils.java   
/**
 * 本地檔案放到遠端SFTP上
 *  
 * @param user
 * @param password
 * @param addr
 * @param port
 * @param localFile
 * @param remoteFile
 * @throws JSchException
 * @throws SftpException
 * @throws Exception
 */
public static void put(String user, String password, String addr, int port,
        List<String> localFile, List<String> remoteFile) throws JSchException, SftpException, Exception {

    Session session = getSession(user, password, addr, port);   
    Channel channel = session.openChannel("sftp");
    channel.connect();
    ChannelSftp sftpChannel = (ChannelSftp) channel;        
    try {
        for (int i=0; i<localFile.size(); i++) {
            String rf=remoteFile.get(i);
            String lf=localFile.get(i);
            logger.info("put local file: " + lf + " write to " + addr + " :" + rf );
            sftpChannel.put(lf, rf);
            logger.info("success write to " + addr + " :" + rf);
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        sftpChannel.exit();
        channel.disconnect();
        session.disconnect();               
    }       
}
项目:Ifc2Rdf    文件:SshFileUploader.java   
/**
     * 
     * @param sourceFilePath
     * @param destinationFilePath
     * @param destinationHost
     * @param destinationPort
     * @param destinationUserName
     * @param destinationUserPassword
     * @param destinationPrivateKeyFilePath
     * @param destinationPrivateKeyPassphrase
     * @throws IOException
     * @throws JSchException
     * @throws SftpException
     */
    public static void copyFile(
            String sourceFilePath,
            String destinationFilePath,
            String destinationHost,
            String destinationPort,
            String destinationUserName,
            String destinationUserPassword,
            String destinationPrivateKeyFilePath,
            String destinationPrivateKeyPassphrase) throws IOException, JSchException, SftpException {

        JSch jsch = new JSch();

        if (!StringUtils.isEmptyOrNull(destinationPrivateKeyFilePath)) {
            jsch.addIdentity(destinationPrivateKeyFilePath, destinationPrivateKeyPassphrase);
        }

        int destinationPortNumber = 22;
        if (!StringUtils.isEmptyOrNull(destinationPort)) {
            destinationPortNumber = Integer.parseInt(destinationPort);
        }

        Session session = jsch.getSession(destinationUserName, destinationHost, destinationPortNumber);
        if (!StringUtils.isEmptyOrNull(destinationUserPassword)) {
            session.setPassword(destinationUserPassword);
        }

//      Properties config = new Properties();
//        config.put("StrictHostKeyChecking", "no");
//        session.setConfig(config);
        session.connect();

        Channel channel = session.openChannel("sftp");
        channel.connect();

        ChannelSftp channelSftp = (ChannelSftp)channel;        
        File destinationFile = new File(destinationFilePath);
        channelSftp.cd(destinationFile.getPath());
        channelSftp.put(new FileInputStream(sourceFilePath), destinationFile.getName());


    }
项目:embeddedlinux-jvmdebugger-intellij    文件:JavaStatusChecker.java   
/**
 * Stops java application that needs to, this should be called when the user wants to manually stop the application
 * so that it kills the remote java process
 *
 * @param session
 * @param isRunningAsRoot
 * @param mainClass
 * @throws JSchException
 * @throws IOException
 */
public void forceStopJavaApplication(@Nullable Session session, @NotNull boolean isRunningAsRoot, @NotNull String mainClass) throws JSchException, IOException {
    if (session == null) {
        return;
    }
    String javaKillCmd = String.format("%s kill -9 $(ps -efww | grep \"%s\"| grep -v grep | tr -s \" \"| cut -d\" \" -f2)",
            isRunningAsRoot ? "sudo" : "", mainClass);
    Channel channel = session.openChannel("shell");

    OutputStream inputstream_for_the_channel = channel.getOutputStream();
    PrintStream commander = new PrintStream(inputstream_for_the_channel, true);

    channel.connect();

    commander.println(javaKillCmd);
    commander.close();
    channel.disconnect();
    session.disconnect();
}
项目:vertx-shell    文件:SSHServerTest.java   
@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();
}
项目:vertx-shell    文件:SSHServerTest.java   
@Test
public void testWrite() throws Exception {
  termHandler = term -> {
    term.write("hello");
  };
  startShell();
  Session session = createSession("paulo", "secret", false);
  session.connect();
  Channel channel = session.openChannel("shell");
  channel.connect();
  Reader in = new InputStreamReader(channel.getInputStream());
  int count = 5;
  StringBuilder sb = new StringBuilder();
  while (count > 0) {
    int code = in.read();
    if (code == -1) {
      count = 0;
    } else {
      count--;
      sb.append((char)code);
    }
  }
  assertEquals("hello", sb.toString());
  channel.disconnect();
  session.disconnect();
}
项目:vertx-shell    文件:SSHServerTest.java   
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);
  }
}
项目:vertx-shell    文件:SSHServerTest.java   
@Test
public void testDifferentCharset(TestContext context) throws Exception {
  termHandler = term -> {
    term.write("\u20AC");
    term.close();
  };
  startShell(new SSHTermOptions().setDefaultCharset("ISO_8859_1").setPort(5000).setHost("localhost").setKeyPairOptions(
      new JksOptions().setPath("src/test/resources/server-keystore.jks").setPassword("wibble")).
      setAuthOptions(new ShiroAuthOptions().setType(ShiroAuthRealmType.PROPERTIES).setConfig(
          new JsonObject().put("properties_path", "classpath:test-auth.properties"))));
  Session session = createSession("paulo", "secret", false);
  session.connect();
  Channel channel = session.openChannel("shell");
  channel.connect();
  InputStream in = channel.getInputStream();
  int b = in.read();
  context.assertEquals(63, b);
}
项目:vertx-shell    文件:SSHTestBase.java   
@Test
public void testAuthenticate() throws Exception {
  startShell();
  for (boolean interactive : new boolean[]{false, true}) {
    Session session = createSession("paulo", "secret", interactive);
    session.connect();
    Channel channel = session.openChannel("shell");
    channel.connect();
    InputStream in = channel.getInputStream();
    byte[] out = new byte[2];
    assertEquals(2, in.read(out));
    assertEquals("% ", new String(out));
    channel.disconnect();
    session.disconnect();
  }
}
项目:Lucee    文件:SSHManager.java   
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();
}
项目:ant    文件:ScpToMessage.java   
private void doSingleTransfer() throws IOException, JSchException {
    StringBuilder sb = new StringBuilder("scp -t ");
    if (getPreserveLastModified()) {
        sb.append("-p ");
    }
    if (getCompressed()) {
        sb.append("-C ");
    }
    sb.append(remotePath);
    final String cmd = sb.toString();
    final Channel channel = openExecChannel(cmd);
    try {
        final OutputStream out = channel.getOutputStream();
        final InputStream in = channel.getInputStream();

        channel.connect();

        waitForAck(in);
        sendFileToRemote(localFile, in, out);
    } finally {
        if (channel != null) {
            channel.disconnect();
        }
    }
}
项目:ant    文件:ScpToMessage.java   
private void doMultipleTransfer() throws IOException, JSchException {
    StringBuilder sb = new StringBuilder("scp -r -d -t ");
    if (getPreserveLastModified()) {
        sb.append("-p ");
    }
    if (getCompressed()) {
        sb.append("-C ");
    }
    sb.append(remotePath);
    final Channel channel = openExecChannel(sb.toString());
    try {
        final OutputStream out = channel.getOutputStream();
        final InputStream in = channel.getInputStream();

        channel.connect();

        waitForAck(in);
        for (Directory current : directoryList) {
            sendDirectory(current, in, out);
        }
    } finally {
        if (channel != null) {
            channel.disconnect();
        }
    }
}
项目:jnrpe    文件:CheckSsh.java   
@Override
public final Collection<Metric> gatherMetrics(final ICommandLine cl) throws MetricGatheringException {
    List<Metric> metrics = new ArrayList<Metric>();
    Session session = null;
    try {
        session = SshUtils.getSession(cl);
        Channel channel = session.openChannel("shell");
        channel.setInputStream(System.in);

        channel.setOutputStream(System.out);
        channel.connect();
        metrics.add(new Metric("connected", "", new BigDecimal(1), null, null));
        channel.disconnect();
        session.disconnect();

    } catch (Exception e) {

        String message = e.getMessage();

        metrics.add(new Metric("connected", message, new BigDecimal(0), null, null));
        LOG.debug(getContext(), message, e);
    }
    return metrics;
}
项目:jumbune    文件:ProfilerJMXDump.java   
/**
 * Gets the list of partitions on the disk.
 * 
 * @param session
 *            the Session
 * @return the list of partitions on the disk
 * @throws JSchException
 *             the j sch exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private List<DiskPartitionInfo> getPartitionStats(Session session) throws JSchException, IOException {

    Channel channel = getChannel(session, PARTITION_LIST_COMMAND);
    InputStream in = null;
    List<DiskPartitionInfo> partitions = null;

    try {
        in = channel.getInputStream();
        partitions = new ArrayList<DiskPartitionInfo>();
        ResultParser resultParser = new ResultParser();
        resultParser.parseDiskPartitionResult(in, partitions);
    } finally {
        if (in != null) {
            in.close();
        }
        channel.disconnect();
    }
    getVmStatsForPartition(session, partitions);
    return partitions;
}
项目:jumbune    文件:ProfilerJMXDump.java   
/**
 * Gets VM stats for a partition of the disk.
 * 
 * @param session
 *            the session
 * @param partitionStats
 *            the partition stats
 * @return VM stats for a partition of the disk
 * @throws JSchException
 *             the j sch exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private void getVmStatsForPartition(Session session, List<DiskPartitionInfo> partitionStats) throws JSchException, IOException {

    StringBuffer sb = new StringBuffer();
    for (DiskPartitionInfo diskPartitionInfo : partitionStats) {
        sb.append(PARTITION_STATS_COMMAND).append(diskPartitionInfo.getName()).append(";");
    }

    Channel channel = getChannel(session, sb.toString());
    InputStream in = null;
    try {
        in = channel.getInputStream();
        ResultParser resultParser = new ResultParser();
        resultParser.parseVmStatsPartitionResult(in, partitionStats);
    } finally {
        if (in != null) {
            in.close();
        }
        channel.disconnect();
    }
}
项目:jumbune    文件:ProfilerJMXDump.java   
/**
 * Returns the network latency between two nodes.
 * 
 * @param session
 *            the Session to node-1
 * @param node2
 *            the node2
 * @return the network latency
 * @throws JSchException
 *             the j sch exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private float getNetworkLatency(Session session, String node2) throws JSchException, IOException {

    Channel channel = getChannel(session, NETWORK_LATENCY_COMMAND + " " + node2);
    InputStream in = null;
    float latency = 0.0f;
    try {
        in = channel.getInputStream();
        ResultParser resultParser = new ResultParser();
        latency = resultParser.parseNetworkLatencyResult(in);
    } finally {
        if (in != null) {
            in.close();
        }
        channel.disconnect();
    }

    return latency;
}
项目:gerrit-events    文件:SshConnectionImpl.java   
/**
 * 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!");
    }
}
项目:airavata    文件:StandardOutReader.java   
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);
    }

}
项目:twister.github.io    文件:LibrariesPanel.java   
private void initializeSftp(){
    try{
        JSch jsch = new JSch();
        session = jsch.getSession(RunnerRepository.user, RunnerRepository.host, 22);
        session.setPassword(RunnerRepository.password);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        Channel channel = session.openChannel("sftp");
        channel.connect();
        connection = (ChannelSftp)channel;
    } catch (Exception e){
        e.printStackTrace();
    }
}
项目:twister.github.io    文件:RunnerRepository.java   
private static void ssh(String user, String passwd, String host){
    try{JSch jsch = new JSch();
        session = jsch.getSession(user, host, 22);
        session.setPassword(passwd);
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();
        Channel channel = session.openChannel("shell");
        channel.connect();
        Thread.sleep(1000);
        channel.disconnect();
        session.disconnect();
    }catch(Exception e){
        e.printStackTrace();
    }
}
项目:twister.github.io    文件:RunnerRepository.java   
public static boolean userpassword(String user,String password, String host){
        boolean passed = false;
            try{
                JSch jsch = new JSch();
                session = jsch.getSession(user, host, 22);
                session.setPassword(password);
                Properties config = new Properties();
                config.put("StrictHostKeyChecking", "no");
                session.setConfig(config);
                session.connect();
                Channel channel = session.openChannel("sftp");
                channel.connect();
                connection = (ChannelSftp)channel;
                try{USERHOME = connection.pwd();}
                catch(Exception e){
                    System.out.println("ERROR: Could not retrieve remote user home directory");}
                REMOTECONFIGDIRECTORY = USERHOME+"/twister/config/";
                passed = true;
            }
            catch(JSchException ex){
                if(ex.toString().indexOf("Auth fail")!=-1)
                    System.out.println("wrong user and/or password");
                else{ex.printStackTrace();
                    System.out.println("Could not connect to server");}}
//                 }
        return true;}
项目:twister.github.io    文件:ConfigTree.java   
private void initializeSftp(){
    try{
        JSch jsch = new JSch();
        session = jsch.getSession(RunnerRepository.user, RunnerRepository.host, 22);
        session.setPassword(RunnerRepository.password);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        Channel channel = session.openChannel("sftp");
        channel.connect();
        connection = (ChannelSftp)channel;
    } catch (Exception e){
        e.printStackTrace();
    }
}
项目:nus-soc-print    文件:SSHConnectivity.java   
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;
}
项目:aos-FileCoreLibrary    文件:SFTPSession.java   
private synchronized void keepSessionConnected(Channel channel){
    try {
        Session session = channel.getSession();
        boolean contains = false;
        for(Entry<Session, Integer> e2 : usedSessions.entrySet()){
            if (e2.getKey() == session) {
                contains = true;
                break;
            }
        }
        if(contains){
            usedSessions.put(session,usedSessions.get(session)+1);
        }
        else {
            usedSessions.put(session, 1);

        }
    } catch (JSchException e) {
        e.printStackTrace();
    }

}
项目:aos-FileCoreLibrary    文件:SFTPSession.java   
public synchronized void releaseSession(Channel channel) {
    try {

        Session session = channel.getSession();
        boolean contains = false;
        for(Entry<Session, Integer> e2 : usedSessions.entrySet()){
            if (e2.getKey() == session) {
                contains = true;
                break;
            }
        }
        if(contains){
            if(usedSessions.get(session)<=1){
                usedSessions.remove(session);
                if(!sessions.values().contains(session))
                    channel.getSession().disconnect();
            }
            else{
                usedSessions.put(session, usedSessions.get(session) - 1);
            }
        }
    } catch (JSchException e) {
        e.printStackTrace();
    }

}
项目:Hydrograph    文件:SCPUtility.java   
/**
 * 
 * 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();       
}
项目:Hydrograph    文件:ScpFrom.java   
/**
 * @param host
 * @param user
 * @param pwd
 * @param remoteFile
 */
public void deleteFile(String host, String user, String pwd,
        String remoteFile) {
    try {
        JSch ssh = new JSch();
        Session session = ssh.getSession(user, host, 22);

        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.setPassword(pwd);

        session.connect();
        Channel channel = session.openChannel("exec");
        channel.connect();

        String command = "rm -rf " + remoteFile;
        System.out.println("command: " + command);
        // ((ChannelExec) channel).setCommand(command);

        channel.disconnect();
        session.disconnect();
    } catch (JSchException e) {
        System.out.println(e.getMessage().toString());
        e.printStackTrace();
    }
}
项目:jwala    文件:JschServiceImpl.java   
@Override
public RemoteCommandReturnInfo runShellCommand(RemoteSystemConnection remoteSystemConnection, String command, long timeout) {
    final ChannelSessionKey channelSessionKey = new ChannelSessionKey(remoteSystemConnection, ChannelType.SHELL);
    LOGGER.debug("channel session key = {}", channelSessionKey);
    Channel channel = null;
    try {
        channel = getChannelShell(channelSessionKey);

        final InputStream in = channel.getInputStream();
        final OutputStream out = channel.getOutputStream();

        LOGGER.debug("Executing command \"{}\"", command);
        out.write(command.getBytes(StandardCharsets.UTF_8));
        out.write(CRLF.getBytes(StandardCharsets.UTF_8));
        out.write("echo 'EXIT_CODE='$?***".getBytes(StandardCharsets.UTF_8));
        out.write(CRLF.getBytes(StandardCharsets.UTF_8));
        out.write("echo -n -e '\\xff'".getBytes(StandardCharsets.UTF_8));
        out.write(CRLF.getBytes(StandardCharsets.UTF_8));
        out.flush();

        return getShellRemoteCommandReturnInfo(command, in, timeout);
    } catch (final Exception e) {
        final String errMsg = MessageFormat.format("Failed to run the following command: {0}", command);
        LOGGER.error(errMsg, e);
        throw new JschServiceException(errMsg, e);
    } finally {
        if (channel != null) {
            channelPool.returnObject(channelSessionKey, channel);
            LOGGER.debug("channel {} returned", channel.getId());
        }
    }
}
项目:jwala    文件:JschServiceImpl.java   
/**
 * Get a {@link ChannelShell}
 *
 * @param channelSessionKey the session key that identifies the channel
 * @return {@link ChannelShell}
 * @throws Exception thrown by borrowObject and invalidateObject
 */
private ChannelShell getChannelShell(final ChannelSessionKey channelSessionKey) throws Exception {
    final long startTime = System.currentTimeMillis();
    Channel channel;
    do {
        LOGGER.debug("borrowing a channel...");
        channel = channelPool.borrowObject(channelSessionKey);
        if (channel != null) {
            LOGGER.debug("channel {} borrowed", channel.getId());
            if (!channel.isConnected()) {
                try {
                    LOGGER.debug("channel {} connecting...", channel.getId());
                    channel.connect(CHANNEL_CONNECT_TIMEOUT);
                    LOGGER.debug("channel {} connected!", channel.getId());
                } catch (final JSchException jsche) {
                    LOGGER.error("Borrowed channel {} connection failed! Invalidating the channel...",
                            channel.getId(), jsche);
                    channelPool.invalidateObject(channelSessionKey, channel);
                }
            } else {
                LOGGER.debug("Channel {} already connected!", channel.getId());
            }
        }

        if ((channel == null || !channel.isConnected()) && (System.currentTimeMillis() - startTime) > CHANNEL_BORROW_LOOP_WAIT_TIME) {
            final String errMsg = MessageFormat.format("Failed to get a channel within {0} ms! Aborting channel acquisition!",
                    CHANNEL_BORROW_LOOP_WAIT_TIME);
            LOGGER.error(errMsg);
            throw new JschServiceException(errMsg);
        }
    } while (channel == null || !channel.isConnected());
    return (ChannelShell) channel;
}