Java Examples for com.jcraft.jsch.Channel

The following java examples will help you to understand the usage of com.jcraft.jsch.Channel. These source code samples are taken from different open source projects.

Example 1
Project: rhevm-api-master  File: TestSshSpawn.java View source code
/**
     * Verify that a channel session holds together.
     *
     * @throws Exception If testing goes exceptionally bad.
     */
public void testSshSpawnChannel() throws Exception {
    InputStream inputStream = (InputStream) Mockito.mock(InputStream.class);
    OutputStream outputStream = (OutputStream) Mockito.mock(OutputStream.class);
    Channel channel = (Channel) Mockito.mock(Channel.class);
    Mockito.when(channel.getInputStream()).thenReturn(inputStream);
    Mockito.when(channel.getOutputStream()).thenReturn(outputStream);
    Spawnable testMe = new SshSpawn(channel);
    // This should be a no-op
    testMe.start();
    assertSame(inputStream, testMe.getStdout());
    assertSame(outputStream, testMe.getStdin());
    assertNull(testMe.getStderr());
    assertFalse(testMe.isClosed());
    ((Channel) (Mockito.verify(channel))).isClosed();
    testMe.stop();
    ((Channel) (Mockito.verify(channel))).disconnect();
    assertTrue(testMe.isClosed());
    assertTrue(testMe.getExitValue() == 0);
}
Example 2
Project: tradelib-master  File: SftpUploader.java View source code
public void upload(Map<String, String> files) throws Exception {
    JSch jsch = new JSch();
    Session session = null;
    session = jsch.getSession(user, host, 22);
    session.setConfig("StrictHostKeyChecking", "no");
    session.setPassword(password);
    session.connect();
    Channel channel = session.openChannel("sftp");
    channel.connect();
    ChannelSftp sftp = (ChannelSftp) channel;
    for (Map.Entry<String, String> ff : files.entrySet()) {
        // key - source, value - destination
        sftp.put(ff.getKey(), ff.getValue());
    }
    sftp.exit();
    session.disconnect();
}
Example 3
Project: ExpectIt-master  File: SshLocalhostExample.java View source code
public static void main(String[] args) throws JSchException, IOException {
    JSch jSch = new JSch();
    Session session = jSch.getSession(System.getenv("USER"), "localhost");
    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    jSch.addIdentity(System.getProperty("user.home") + "/.ssh/id_rsa");
    session.setConfig(config);
    session.connect();
    Channel channel = session.openChannel("shell");
    channel.connect();
    Expect expect = new ExpectBuilder().withOutput(channel.getOutputStream()).withInputs(channel.getInputStream(), channel.getExtInputStream()).build();
    try {
        expect.expect(contains("$"));
        expect.sendLine("pwd");
        System.out.println("pwd1:" + expect.expect(times(2, contains("\n"))).getResults().get(1).getBefore());
        expect.sendLine("pwd");
        // a regexp which captures the output of pwd
        System.out.println("pwd2:" + expect.expect(regexp("(?m)\\n([^\\n]*)\\n")).group(1));
        expect.expect(contains("$"));
        expect.sendLine("ls -l");
        // skipping the echo command
        expect.expect(times(2, contains("\n")));
        // getting the output of ls
        System.out.println(expect.expect(regexp(".*\\$")).getBefore().trim());
        expect.sendLine("exit");
    } finally {
        expect.close();
        channel.disconnect();
        session.disconnect();
    }
}
Example 4
Project: fraud-detection-tutorial-master  File: AbstractSshExecOperation.java View source code
@Override
public void execute(Session session, EventListener listener) {
    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("df");
        //((ChannelExec)channel).setCommand("top -n 1 -b");
        //((ChannelExec)channel).setCommand("ifconfig");
        //((ChannelExec)channel).setCommand("netstat -s");
        ((ChannelExec) channel).setCommand(getCommand());
        System.out.println("4");
        channel.connect();
        System.out.println("5");
        StringBuffer strBuffer = new StringBuffer();
        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0)
                    break;
                strBuffer.append(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) {
            }
        }
        System.out.println("6");
        //channel.disconnect();
        String results = strBuffer.toString();
        processResults(session.getHost(), session.getPort(), results, listener);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 5
Project: hello-world-master  File: TcSshBin.java View source code
@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;
}
Example 6
Project: jscp-master  File: Scp.java View source code
public static void exec(final SecureContext pContext, String pLocalFile, String pRemoteFile) throws JSchException, IOException {
    if (pContext.getPassword() == null && pContext.getPrivateKeyFile() == null) {
        throw new IllegalStateException("Must specifiy either a password or private key file");
    }
    FileInputStream fis = null;
    OutputStream out = null;
    InputStream in = null;
    try {
        Session session = pContext.createSession();
        session.connect();
        Channel channel = sendCommand(pRemoteFile, session);
        out = channel.getOutputStream();
        in = channel.getInputStream();
        channel.connect();
        if (checkAck(in) != 0) {
            System.exit(0);
        }
        sendFileSize(pLocalFile, out, in);
        fis = sendContent(pLocalFile, out, in);
        out.close();
        channel.disconnect();
        session.disconnect();
    } finally {
        IOUtils.closeQuietly(fis);
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(in);
    }
}
Example 7
Project: Lucee-master  File: SFTPClientImpl.java View source code
@Override
public void connect() throws SocketException, IOException {
    try {
        session = jsch.getSession(username, host.getHostAddress(), port);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        UserInfo ui = new UserInfoImpl(password, null);
        session.setUserInfo(ui);
        if (timeout > 0)
            session.setTimeout(timeout);
        session.connect();
        Channel channel = session.openChannel("sftp");
        channel.connect();
        channelSftp = (ChannelSftp) channel;
        // check fingerprint
        if (!StringUtil.isEmpty(fingerprint)) {
            if (!fingerprint.equalsIgnoreCase(fingerprint())) {
                disconnect();
                throw new IOException("given fingerprint is not a match.");
            }
        }
        handleSucess();
    } catch (JSchException e) {
        handleFail(e, stopOnError);
    }
}
Example 8
Project: ts-android-master  File: SSHSession.java View source code
/**
     * Connections the session
     * @return
     * @throws JSchException
     * @throws UnsupportedEncodingException
     */
public static Channel openSession(String user, String server, int port) throws JSchException, UnsupportedEncodingException {
    JSch jsch = new JSch();
    // configure keys
    File sshDir = AppContext.context().getKeysFolder();
    for (File file : sshDir.listFiles(new FilenameFilter() {

        @Override
        public boolean accept(File file, String s) {
            String[] pieces = s.split("\\.");
            if (pieces.length >= 2) {
                String ext = pieces[pieces.length - 1];
                return !ext.equals("pub");
            } else {
                return true;
            }
        }
    })) {
        jsch.addIdentity(file.getAbsolutePath());
    }
    // configure session
    Session session = jsch.getSession(user, server);
    session.setConfig("StrictHostKeyChecking", "no");
    session.setPort(port);
    session.connect();
    // open channel
    Channel channelssh = session.openChannel("shell");
    channelssh.connect();
    return channelssh;
}
Example 9
Project: airavata-master  File: Factory.java View source code
public static synchronized Session getSSHSession(AuthenticationInfo authenticationInfo, ServerInfo serverInfo) throws GFacException {
    if (authenticationInfo == null || serverInfo == null) {
        throw new IllegalArgumentException("Can't create ssh session, argument should be valid (not null)");
    }
    SSHKeyAuthentication authentication;
    if (authenticationInfo instanceof SSHKeyAuthentication) {
        authentication = (SSHKeyAuthentication) authenticationInfo;
    } else {
        throw new GFacException("Support ssh key authentication only");
    }
    String key = buildKey(serverInfo);
    Session session = sessionCache.getIfPresent(key);
    boolean valid = isValidSession(session);
    // FIXME - move following info logs to debug
    if (valid) {
        log.info("SSH Session validation succeeded, key :" + key);
        valid = testChannelCreation(session);
        if (valid) {
            log.info("Channel creation test succeeded, key :" + key);
        } else {
            log.info("Channel creation test failed, key :" + key);
        }
    } else {
        log.info("Session validation failed, key :" + key);
    }
    if (!valid) {
        if (session != null) {
            log.info("Reinitialize a new SSH session for :" + key);
        } else {
            log.info("Initialize a new SSH session for :" + key);
        }
        try {
            JSch jSch = new JSch();
            jSch.addIdentity(UUID.randomUUID().toString(), authentication.getPrivateKey(), authentication.getPublicKey(), authentication.getPassphrase().getBytes());
            session = jSch.getSession(serverInfo.getUserName(), serverInfo.getHost(), serverInfo.getPort());
            session.setUserInfo(new DefaultUserInfo(serverInfo.getUserName(), null, authentication.getPassphrase()));
            if (authentication.getStrictHostKeyChecking().equals("yes")) {
                jSch.setKnownHosts(authentication.getKnownHostsFilePath());
            } else {
                session.setConfig("StrictHostKeyChecking", "no");
            }
            // 0 connection timeout
            session.connect();
            sessionCache.put(key, session);
        } catch (JSchException e) {
            throw new GFacException("JSch initialization error ", e);
        }
    } else {
        // FIXME - move following info log to debug
        log.info("Reuse SSH session for :" + key);
    }
    return session;
}
Example 10
Project: aws-tasks-master  File: ScpDownloadCommand.java View source code
@Override
public void execute(Session session) throws IOException {
    String command = constructScpInitCommand(_remoteFile, _recursive);
    Channel channel = SshUtil.openExecChannel(session, command);
    try {
        OutputStream out = channel.getOutputStream();
        InputStream in = channel.getInputStream();
        SshUtil.sendAckOk(out);
        download(in, out, _localFile);
    } finally {
        if (channel != null) {
            channel.disconnect();
        }
    }
}
Example 11
Project: batch-upload-tool-master  File: SftpUtils.java View source code
public static void landFile(File fileToLand, UploadProperties properties) throws Exception {
    JSch jsch = new JSch();
    String host = properties.getSftpServer();
    String user = properties.getUser();
    String password = properties.getPassword();
    int port = properties.getPort();
    Session session = jsch.getSession(user, host, port);
    session.setOutputStream(System.out);
    session.setPassword(password);
    session.setConfig("StrictHostKeyChecking", "no");
    session.connect(TIMEOUT);
    Channel channel = session.openChannel("sftp");
    channel.connect();
    ChannelSftp c = (ChannelSftp) channel;
    // delete any existing file with the target filename, so that rename will work
    @SuppressWarnings("unchecked") Vector<LsEntry> files = c.ls(".");
    for (LsEntry file : files) {
        if (FINAL_REMOTE_FILENAME.equals(file.getFilename())) {
            c.rm(FINAL_REMOTE_FILENAME);
        }
    }
    // transmit file, using temp remote name, so ingestion won't process file until complete
    c.put(new FileInputStream(fileToLand), TEMP_REMOTE_FILENAME, ChannelSftp.OVERWRITE);
    // rename remote file so ingestion can begin
    c.rename(TEMP_REMOTE_FILENAME, FINAL_REMOTE_FILENAME);
    c.disconnect();
    channel.disconnect();
    session.disconnect();
}
Example 12
Project: gMix-master  File: SimpleSSHClient.java View source code
public boolean executeCommand(String cmd) throws JSchException {
    if (!session.isConnected())
        session.connect();
    Channel channel = session.openChannel("exec");
    ((ChannelExec) channel).setCommand(cmd);
    try {
        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;
            }
            if (channel.isClosed()) {
                if (in.available() > 0)
                    continue;
                break;
            }
            try {
                Thread.sleep(50);
            } catch (Exception ee) {
            }
        }
        channel.disconnect();
    } catch (IOException e) {
    }
    return channel.getExitStatus() == 0;
}
Example 13
Project: openshift-deployer-plugin-master  File: SSHClient.java View source code
public void deploy(File deployment) throws IOException {
    try {
        log.info("Deployging " + deployment.getAbsolutePath());
        log.info("Starting SSH connection to " + app.getSshUrl());
        URI uri = new URI(app.getSshUrl());
        JSch jsch = new JSch();
        // confgure logger
        JSch.setLogger(new com.jcraft.jsch.Logger() {

            private final java.util.logging.Logger LOG = java.util.logging.Logger.getLogger(JSch.class.getName());

            public void log(int level, String message) {
                LOG.fine(message);
                if (isEnabled(level)) {
                    try {
                        log.info(message);
                    } catch (Exception e) {
                    }
                }
            }

            public boolean isEnabled(int level) {
                return level >= WARN;
            }
        });
        // add ssh keys
        jsch.addIdentity(sshPrivateKey);
        log.info("Using SSH private key " + sshPrivateKey);
        Session session = jsch.getSession(uri.getUserInfo(), uri.getHost());
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect(10000);
        FileInputStream in = new FileInputStream(deployment);
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setErrStream(new CloseShieldOutputStream(log.getOutputStream()));
        ((ChannelExec) channel).setOutputStream(new CloseShieldOutputStream(log.getOutputStream()));
        ((ChannelExec) channel).setInputStream(in);
        ((ChannelExec) channel).setCommand(BINARY_DEPLOY_CMD);
        channel.connect();
        try {
            while (!channel.isEOF()) {
            }
            in.close();
            channel.disconnect();
            session.disconnect();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    } catch (JSchException e) {
        throw new IOException("Failed to deploy the binary. " + e.getMessage(), e);
    } catch (URISyntaxException e) {
        throw new IOException(e.getMessage(), e);
    }
}
Example 14
Project: arduino-eclipse-plugin-master  File: SSH.java View source code
@SuppressWarnings("resource")
public boolean execSyncCommand(String command, MessageConsoleStream stdoutConsumer, MessageConsoleStream stderrConsumer) throws JSchException, IOException {
    InputStream stdout = null;
    InputStream stderr = null;
    Channel channel = null;
    try {
        channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        channel.setInputStream(null);
        stdout = channel.getInputStream();
        stderr = ((ChannelExec) channel).getErrStream();
        channel.connect();
        int exitCode = consumeOutputSyncAndReturnExitCode(channel);
        return exitCode == 0;
    } finally {
        try {
            if (stdout != null) {
                stdout.close();
            }
            if (stderr != null) {
                stderr.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (channel != null) {
            channel.disconnect();
        }
    }
}
Example 15
Project: choreos_middleware-master  File: SshUtil.java View source code
public String runCommandOnce(String command) throws JSchException, SshCommandFailed {
    String output = null;
    Session session = getSession();
    try {
        session.connect(CONNECTION_TIMEOUT);
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        StringBuffer sb = new StringBuffer();
        channel.setOutputStream(new StringBufferOutputStream(sb));
        channel.connect();
        while (!channel.isClosed()) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                logger.error("Sleep exception! Cause: ", e.getCause());
            }
        }
        if (channel.getExitStatus() > 0) {
            throw new SshCommandFailed(command);
        }
        channel.disconnect();
        session.disconnect();
        output = sb.toString();
    } catch (JSchException e) {
        logger.debug("Could not connect to " + user + "@" + hostname + " with key " + privateKeyFile);
        throw e;
    }
    return output;
}
Example 16
Project: embeddedlinux-jvmdebugger-intellij-master  File: JavaStatusChecker.java View source code
/**
     * 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();
}
Example 17
Project: jdbc-ssh-master  File: SshTunnel.java View source code
public void start() {
    int assignedPort = 0;
    try {
        JSch jsch = new JSch();
        String username = config.getProperty(CONFIG_USERNAME);
        String password = config.getProperty(CONFIG_PASSWORD);
        String keyPrivate = config.getProperty(CONFIG_KEY_PRIVATE);
        String keyPublic = config.getProperty(CONFIG_KEY_PUBLIC);
        String passphrase = config.getProperty(CONFIG_PASSPHRASE);
        String knownHosts = config.getProperty(CONFIG_KNOWN_HOSTS);
        String host = config.getProperty(CONFIG_HOST);
        Integer port = Integer.valueOf(config.getProperty(CONFIG_PORT));
        assert host != null;
        assert port != null;
        boolean useKey = (keyPrivate != null && !"".equals(keyPrivate.trim()));
        session = jsch.getSession(username, host, port);
        jsch.setKnownHosts(knownHosts);
        if (useKey) {
            if (passphrase == null || "".equals(passphrase.trim())) {
                jsch.addIdentity(keyPrivate, keyPublic);
            } else {
                jsch.addIdentity(keyPrivate, keyPublic, passphrase.getBytes());
            }
        } else {
            session.setPassword(password);
        }
        session.setConfig(config.getProperties());
        session.setDaemonThread(true);
        // Connect
        session.connect();
        Channel channel = session.openChannel("shell");
        channel.connect();
        String forwardHost = config.getProperty(CONFIG_HOST_REMOTE);
        Integer remotePort = Integer.valueOf(config.getProperty(CONFIG_PORT_REMOTE));
        int nextPort = localPort.incrementAndGet();
        // NOTE: scan max next 10 ports
        for (int i = 0; i < 10; i++) {
            if (isPortOpen("127.0.0.1", nextPort)) {
                break;
            }
            nextPort = localPort.incrementAndGet();
        }
        assignedPort = session.setPortForwardingL(nextPort, forwardHost, remotePort);
        if (logger.isDebugEnabled()) {
            logger.debug("Server version: {}", session.getServerVersion());
            logger.debug("Client version: {}", session.getClientVersion());
            logger.debug("Host          : {}", session.getHost());
            logger.debug("Port          : {}", session.getPort());
            logger.debug("Forwarding    : {}", session.getPortForwardingL());
            logger.debug("Connected     : {}", session.isConnected());
            logger.debug("Private key   : {}", useKey);
        }
    } catch (Exception e) {
        logger.error(e.toString(), e);
    }
    if (assignedPort == 0) {
        throw new RuntimeException("Port forwarding failed !");
    }
}
Example 18
Project: jnrpe-master  File: CheckBySsh.java View source code
@Override
public final Collection<Metric> gatherMetrics(final ICommandLine cl) throws MetricGatheringException {
    List<Metric> metrics = new ArrayList<Metric>();
    Session session = null;
    Channel channel = null;
    String command = cl.getOptionValue("command");
    InputStream in = null;
    boolean hasSession = false;
    long then = System.currentTimeMillis();
    try {
        session = SshUtils.getSession(cl);
        channel = session.openChannel("exec");
        hasSession = true;
        metrics.add(new Metric("session", "", new BigDecimal(1), null, null));
    } catch (Exception e) {
        LOG.debug(getContext(), e.getMessage(), e);
        throw new MetricGatheringException("SSH not started, permission denied.", Status.UNKNOWN, e);
    }
    try {
        if (hasSession) {
            ((ChannelExec) channel).setCommand(command);
            channel.setInputStream(null);
            ((ChannelExec) channel).setErrStream(System.err);
            in = channel.getInputStream();
        } else {
            return metrics;
        }
    } catch (IOException e1) {
        throw new MetricGatheringException(e1.getMessage(), Status.UNKNOWN, e1);
    }
    try {
        channel.connect();
        metrics.add(new Metric("connected", "", new BigDecimal(1), null, null));
    } catch (JSchException e2) {
        throw new MetricGatheringException(e2.getMessage(), Status.UNKNOWN, e2);
    }
    StringBuilder sb = new StringBuilder();
    byte[] tmp = new byte[1024];
    int exitStatus = 0;
    while (true) {
        try {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0)
                    break;
                sb.append(new String(tmp, 0, i, "UTF-8"));
            }
        } catch (IOException e1) {
            throw new MetricGatheringException(e1.getMessage(), Status.UNKNOWN, e1);
        }
        if (channel.isClosed()) {
            exitStatus = channel.getExitStatus();
            break;
        }
        try {
            Thread.sleep(1000);
        } catch (Exception e) {
            LOG.error(getContext(), "gatherMetrics - " + e.getMessage(), e);
        }
    }
    if (channel != null) {
        channel.disconnect();
    }
    session.disconnect();
    long response = (System.currentTimeMillis() - then) / 1000;
    metrics.add(new Metric("response", "", new BigDecimal(response), null, null));
    // sb.append("\nexit-status: " + channel.getExitStatus());
    String msg = "";
    switch(channel.getExitStatus()) {
        case ERR_CMD_NOT_FOUND:
            msg = "Command not found.";
            break;
        case ERR_NO_PERMISSION:
            msg = "Not enough permission to execute command.";
            break;
        default:
            break;
    }
    metrics.add(new Metric("result", msg + " " + sb.toString(), new BigDecimal(Utils.getIntValue(exitStatus == 0)), null, null));
    return metrics;
}
Example 19
Project: linuxtools-master  File: TapsetParser.java View source code
private String runRemoteStapAttempt(String[] args, boolean getErrors) throws JSchException {
    StringOutputStream str = new StringOutputStream();
    StringOutputStream strErr = new StringOutputStream();
    IPreferenceStore p = ConsoleLogPlugin.getDefault().getPreferenceStore();
    String user = p.getString(ConsoleLogPreferenceConstants.SCP_USER);
    String host = p.getString(ConsoleLogPreferenceConstants.HOST_NAME);
    String password = p.getString(ConsoleLogPreferenceConstants.SCP_PASSWORD);
    int port = p.getInt(ConsoleLogPreferenceConstants.PORT_NUMBER);
    Channel channel = LinuxtoolsProcessFactory.execRemoteAndWait(args, str, strErr, user, host, password, port, EnvironmentVariablesPreferencePage.getEnvironmentVariables());
    if (channel == null) {
        return null;
    }
    channel.getSession().disconnect();
    channel.disconnect();
    return (!getErrors ? str : strErr).toString();
}
Example 20
Project: mina-sshd-master  File: KeyReExchangeTest.java View source code
@Test
public void testReExchangeFromJschClient() throws Exception {
    Assume.assumeTrue("DH Group Exchange not supported", SecurityUtils.isDHGroupExchangeSupported());
    setUp(0L, 0L, 0L);
    JSch.setConfig("kex", BuiltinDHFactories.Constants.DIFFIE_HELLMAN_GROUP_EXCHANGE_SHA1);
    JSch sch = new JSch();
    com.jcraft.jsch.Session s = sch.getSession(getCurrentTestName(), TEST_LOCALHOST, port);
    try {
        s.setUserInfo(new SimpleUserInfo(getCurrentTestName()));
        s.connect();
        com.jcraft.jsch.Channel c = s.openChannel(Channel.CHANNEL_SHELL);
        c.connect();
        try (OutputStream os = c.getOutputStream();
            InputStream is = c.getInputStream()) {
            String expected = "this is my command\n";
            byte[] bytes = expected.getBytes(StandardCharsets.UTF_8);
            byte[] data = new byte[bytes.length + Long.SIZE];
            for (int i = 1; i <= 10; i++) {
                os.write(bytes);
                os.flush();
                int len = is.read(data);
                String str = new String(data, 0, len, StandardCharsets.UTF_8);
                assertEquals("Mismatched data at iteration " + i, expected, str);
                outputDebugMessage("Request re-key #%d", i);
                s.rekey();
            }
        } finally {
            c.disconnect();
        }
    } finally {
        s.disconnect();
    }
}
Example 21
Project: nextreports-server-master  File: SftpDistributor.java View source code
protected void connect(SftpDestination destination) throws DistributionException {
    if (connected) {
        // ?!
        throw new DistributionException("Already connected to sftp server");
    }
    JSch jsch = new JSch();
    Session session;
    try {
        session = jsch.getSession(destination.getUsername(), destination.getHost(), destination.getPort());
    } catch (JSchException e) {
        throw new DistributionException(e);
    }
    SshUserInfo userInfo = new SshUserInfo();
    userInfo.setPassword(destination.getPassword());
    // username and password will be given via UserInfo interface.
    session.setUserInfo(userInfo);
    try {
        session.connect();
        Channel channel = session.openChannel("sftp");
        channel.connect();
        connected = true;
        channelSftp = (ChannelSftp) channel;
    } catch (JSchException e) {
        throw new DistributionException(e);
    }
}
Example 22
Project: nus-soc-print-master  File: SSHConnectivity.java View source code
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;
}
Example 23
Project: QTAF-master  File: SftpExecUtil.java View source code
private Channel getChannel() {
    if (null != channel) {
        closeChannelOnly();
    }
    session = getSession();
    try {
        // 打开exec通�
        channel = session.openChannel("exec");
        return channel;
    } catch (JSchException e) {
        log.error("连接 SFTP通�创建失败");
        log.error(e.getMessage());
        return null;
    }
}
Example 24
Project: rhq-master  File: SSHInstallUtility.java View source code
private String read(InputStream is, Channel channel) throws IOException {
    byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final long endTime = System.currentTimeMillis() + TIMEOUT;
    while (System.currentTimeMillis() < endTime) {
        while (is.available() > 0) {
            int count = is.read(buffer, 0, DEFAULT_BUFFER_SIZE);
            if (count >= 0) {
                bos.write(buffer, 0, count);
            } else {
                break;
            }
        }
        if (channel.isClosed()) {
            if (log.isDebugEnabled()) {
                log.debug("SSH reading exit status=" + channel.getExitStatus());
            }
            break;
        }
        try {
            Thread.sleep(POLL_TIMEOUT);
        } catch (InterruptedException e) {
        }
    }
    return bos.toString();
}
Example 25
Project: scisoft-icat-master  File: Sftp.java View source code
public static void main(String[] arg) {
    try {
        JSch jsch = new JSch();
        String host = null;
        if (arg.length > 0) {
            host = arg[0];
        } else {
            host = JOptionPane.showInputDialog("Enter username@hostname", System.getProperty("user.name") + "@localhost");
        }
        String user = host.substring(0, host.indexOf('@'));
        host = host.substring(host.indexOf('@') + 1);
        int port = 22;
        Session session = jsch.getSession(user, host, port);
        // username and password will be given via UserInfo interface.
        UserInfo ui = new MyUserInfo();
        session.setUserInfo(ui);
        session.connect();
        Channel channel = session.openChannel("sftp");
        channel.connect();
        ChannelSftp c = (ChannelSftp) channel;
        java.io.InputStream in = System.in;
        java.io.PrintStream out = System.out;
        java.util.Vector cmds = new java.util.Vector();
        byte[] buf = new byte[1024];
        int i;
        String str;
        int level = 0;
        while (true) {
            out.print("sftp> ");
            cmds.removeAllElements();
            i = in.read(buf, 0, 1024);
            if (i <= 0)
                break;
            i--;
            if (i > 0 && buf[i - 1] == 0x0d)
                i--;
            // str=new String(buf, 0, i);
            // System.out.println("|"+str+"|");
            int s = 0;
            for (int ii = 0; ii < i; ii++) {
                if (buf[ii] == ' ') {
                    if (ii - s > 0) {
                        cmds.addElement(new String(buf, s, ii - s));
                    }
                    while (ii < i) {
                        if (buf[ii] != ' ')
                            break;
                        ii++;
                    }
                    s = ii;
                }
            }
            if (s < i) {
                cmds.addElement(new String(buf, s, i - s));
            }
            if (cmds.size() == 0)
                continue;
            String cmd = (String) cmds.elementAt(0);
            if (cmd.equals("quit")) {
                c.quit();
                break;
            }
            if (cmd.equals("exit")) {
                c.exit();
                break;
            }
            if (cmd.equals("rekey")) {
                session.rekey();
                continue;
            }
            if (cmd.equals("compression")) {
                if (cmds.size() < 2) {
                    out.println("compression level: " + level);
                    continue;
                }
                try {
                    level = Integer.parseInt((String) cmds.elementAt(1));
                    if (level == 0) {
                        session.setConfig("compression.s2c", "none");
                        session.setConfig("compression.c2s", "none");
                    } else {
                        session.setConfig("compression.s2c", "zlib@openssh.com,zlib,none");
                        session.setConfig("compression.c2s", "zlib@openssh.com,zlib,none");
                    }
                } catch (Exception e) {
                }
                session.rekey();
                continue;
            }
            if (cmd.equals("cd") || cmd.equals("lcd")) {
                if (cmds.size() < 2)
                    continue;
                String path = (String) cmds.elementAt(1);
                try {
                    if (cmd.equals("cd"))
                        c.cd(path);
                    else
                        c.lcd(path);
                } catch (SftpException e) {
                    System.out.println(e.toString());
                }
                continue;
            }
            if (cmd.equals("rm") || cmd.equals("rmdir") || cmd.equals("mkdir")) {
                if (cmds.size() < 2)
                    continue;
                String path = (String) cmds.elementAt(1);
                try {
                    if (cmd.equals("rm"))
                        c.rm(path);
                    else if (cmd.equals("rmdir"))
                        c.rmdir(path);
                    else
                        c.mkdir(path);
                } catch (SftpException e) {
                    logger.error("sftp exception: ", e);
                }
                continue;
            }
            if (cmd.equals("chgrp") || cmd.equals("chown") || cmd.equals("chmod")) {
                if (cmds.size() != 3)
                    continue;
                String path = (String) cmds.elementAt(2);
                int foo = 0;
                if (cmd.equals("chmod")) {
                    byte[] bar = ((String) cmds.elementAt(1)).getBytes();
                    int k;
                    for (int j = 0; j < bar.length; j++) {
                        k = bar[j];
                        if (k < '0' || k > '7') {
                            foo = -1;
                            break;
                        }
                        foo <<= 3;
                        foo |= (k - '0');
                    }
                    if (foo == -1)
                        continue;
                } else {
                    try {
                        foo = Integer.parseInt((String) cmds.elementAt(1));
                    } catch (Exception e) {
                        continue;
                    }
                }
                try {
                    if (cmd.equals("chgrp")) {
                        c.chgrp(foo, path);
                    } else if (cmd.equals("chown")) {
                        c.chown(foo, path);
                    } else if (cmd.equals("chmod")) {
                        c.chmod(foo, path);
                    }
                } catch (SftpException e) {
                    logger.error("sftp exception: ", e);
                }
                continue;
            }
            if (cmd.equals("pwd") || cmd.equals("lpwd")) {
                str = (cmd.equals("pwd") ? "Remote" : "Local");
                str += " working directory: ";
                if (cmd.equals("pwd"))
                    str += c.pwd();
                else
                    str += c.lpwd();
                out.println(str);
                continue;
            }
            if (cmd.equals("ls") || cmd.equals("dir")) {
                String path = ".";
                if (cmds.size() == 2)
                    path = (String) cmds.elementAt(1);
                try {
                    java.util.Vector vv = c.ls(path);
                    if (vv != null) {
                        for (int ii = 0; ii < vv.size(); ii++) {
                            // out.println(vv.elementAt(ii).toString());
                            Object obj = vv.elementAt(ii);
                            if (obj instanceof com.jcraft.jsch.ChannelSftp.LsEntry) {
                                out.println(((com.jcraft.jsch.ChannelSftp.LsEntry) obj).getLongname());
                            }
                        }
                    }
                } catch (SftpException e) {
                    logger.error("sftp exception: ", e);
                }
                continue;
            }
            if (cmd.equals("lls") || cmd.equals("ldir")) {
                String path = ".";
                if (cmds.size() == 2)
                    path = (String) cmds.elementAt(1);
                try {
                    java.io.File file = new java.io.File(path);
                    if (!file.exists()) {
                        out.println(path + ": No such file or directory");
                        continue;
                    }
                    if (file.isDirectory()) {
                        String[] list = file.list();
                        for (int ii = 0; ii < list.length; ii++) {
                            out.println(list[ii]);
                        }
                        continue;
                    }
                    out.println(path);
                } catch (Exception e) {
                    logger.error("sftp exception: ", e);
                }
                continue;
            }
            if (cmd.equals("get") || cmd.equals("get-resume") || cmd.equals("get-append") || cmd.equals("put") || cmd.equals("put-resume") || cmd.equals("put-append")) {
                if (cmds.size() != 2 && cmds.size() != 3)
                    continue;
                String p1 = (String) cmds.elementAt(1);
                // String p2=p1;
                String p2 = ".";
                if (cmds.size() == 3)
                    p2 = (String) cmds.elementAt(2);
                try {
                    SftpProgressMonitor monitor = new MyProgressMonitor();
                    if (cmd.startsWith("get")) {
                        int mode = ChannelSftp.OVERWRITE;
                        if (cmd.equals("get-resume")) {
                            mode = ChannelSftp.RESUME;
                        } else if (cmd.equals("get-append")) {
                            mode = ChannelSftp.APPEND;
                        }
                        c.get(p1, p2, monitor, mode);
                    } else {
                        int mode = ChannelSftp.OVERWRITE;
                        if (cmd.equals("put-resume")) {
                            mode = ChannelSftp.RESUME;
                        } else if (cmd.equals("put-append")) {
                            mode = ChannelSftp.APPEND;
                        }
                        c.put(p1, p2, monitor, mode);
                    }
                } catch (SftpException e) {
                    logger.error("sftp exception: ", e);
                }
                continue;
            }
            if (cmd.equals("ln") || cmd.equals("symlink") || cmd.equals("rename")) {
                if (cmds.size() != 3)
                    continue;
                String p1 = (String) cmds.elementAt(1);
                String p2 = (String) cmds.elementAt(2);
                try {
                    if (cmd.equals("rename"))
                        c.rename(p1, p2);
                    else
                        c.symlink(p1, p2);
                } catch (SftpException e) {
                    logger.error("sftp exception: ", e);
                }
                continue;
            }
            if (cmd.equals("stat") || cmd.equals("lstat")) {
                if (cmds.size() != 2)
                    continue;
                String p1 = (String) cmds.elementAt(1);
                SftpATTRS attrs = null;
                try {
                    if (cmd.equals("stat"))
                        attrs = c.stat(p1);
                    else
                        attrs = c.lstat(p1);
                } catch (SftpException e) {
                    logger.error("sftp exception: ", e);
                }
                if (attrs != null) {
                    out.println(attrs);
                } else {
                }
                continue;
            }
            if (cmd.equals("readlink")) {
                if (cmds.size() != 2)
                    continue;
                String p1 = (String) cmds.elementAt(1);
                String filename = null;
                try {
                    filename = c.readlink(p1);
                    out.println(filename);
                } catch (SftpException e) {
                    logger.error("sftp exception: ", e);
                }
                continue;
            }
            if (cmd.equals("realpath")) {
                if (cmds.size() != 2)
                    continue;
                String p1 = (String) cmds.elementAt(1);
                String filename = null;
                try {
                    filename = c.realpath(p1);
                    out.println(filename);
                } catch (SftpException e) {
                    logger.error("sftp exception: ", e);
                }
                continue;
            }
            if (cmd.equals("version")) {
                out.println("SFTP protocol version " + c.version());
                continue;
            }
            if (cmd.equals("help") || cmd.equals("?")) {
                out.println(help);
                continue;
            }
            out.println("unimplemented command: " + cmd);
        }
        session.disconnect();
    } catch (Exception e) {
        logger.error("sftp exception: ", e);
    }
    System.exit(0);
}
Example 26
Project: scumd-master  File: CipherTest.java View source code
protected void runTest() throws Exception {
    JSch sch = new JSch();
    JSch.setConfig("cipher.s2c", "aes128-cbc,3des-cbc,blowfish-cbc,aes192-cbc,aes256-cbc,none");
    JSch.setConfig("cipher.c2s", "aes128-cbc,3des-cbc,blowfish-cbc,aes192-cbc,aes256-cbc,none");
    sch.setLogger(new Logger() {

        public boolean isEnabled(int i) {
            return true;
        }

        public void log(int i, String s) {
            System.out.println("Log(jsch," + i + "): " + s);
        }
    });
    com.jcraft.jsch.Session s = sch.getSession("smx", "localhost", port);
    s.setUserInfo(new UserInfo() {

        public String getPassphrase() {
            return null;
        }

        public String getPassword() {
            return "smx";
        }

        public boolean promptPassword(String message) {
            return true;
        }

        public boolean promptPassphrase(String message) {
            return false;
        }

        public boolean promptYesNo(String message) {
            return true;
        }

        public void showMessage(String message) {
        }
    });
    s.connect();
    com.jcraft.jsch.Channel c = s.openChannel("shell");
    c.connect();
    OutputStream os = c.getOutputStream();
    InputStream is = c.getInputStream();
    for (int i = 0; i < 10; i++) {
        os.write("this is my command\n".getBytes());
        os.flush();
        byte[] data = new byte[512];
        int len = is.read(data);
        String str = new String(data, 0, len);
        assertEquals("this is my command\n", str);
    }
    c.disconnect();
    s.disconnect();
}
Example 27
Project: sw360portal-master  File: FossologySshConnector.java View source code
protected void waitCompletion(Channel channel, long timeout) throws SW360Exception {
    long startTime = currentTimeMillis();
    while (!channel.isClosed() && (currentTimeMillis() - startTime < timeout)) {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            throw fail(e, "interrupted connection to Fossology");
        }
    }
    if (!channel.isClosed()) {
        throw fail("timeout while waiting for completion of connection to Fossology");
    }
}
Example 28
Project: Cattles-master  File: JschSCPTo.java View source code
private void doSingleFileTransfer(Session sshSession, File localFile, String dest, String option, SSHResult result, List<SSHMonitor> monitors) throws JSchException, IOException, SSHException {
    String command = "scp -t " + option + " " + dest;
    Channel channel = sshSession.openChannel("exec");
    try {
        ((ChannelExec) channel).setCommand(command);
        OutputStream out = channel.getOutputStream();
        InputStream in = channel.getInputStream();
        channel.connect();
        waitForAck(in);
        result.append("Beginning transfer " + localFile.getCanonicalPath() + "\n");
        sendFileToRemote(localFile, in, out, result, monitors);
    } finally {
        if (channel != null)
            channel.disconnect();
    }
}
Example 29
Project: CBCJVM-master  File: Ssh.java View source code
public void sendFile(String path, File toSend) throws IOException {
    // Start remote scp
    String command = "scp -p -t " + path;
    Channel channel = null;
    try {
        channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        OutputStream out = channel.getOutputStream();
        InputStream in = channel.getInputStream();
        channel.connect();
        int check = checkAck(in);
        if (check != 0) {
            throw new IOException("CheckAck failed when starting remote scp (" + check + ")");
        }
        // Send file properties
        long filesize = toSend.length();
        command = "C0644 " + filesize + " ";
        command += toSend.getName();
        command += "\n";
        System.out.print(command);
        out.write(command.getBytes());
        out.flush();
        check = checkAck(in);
        if (check != 0) {
            throw new IOException("CheckAck failed when sending file properties (" + check + ")");
        }
        // Send file
        FileInputStream fis = new FileInputStream(toSend);
        byte[] buf = new byte[1024];
        while (true) {
            int len = fis.read(buf, 0, buf.length);
            if (len <= 0)
                break;
            out.write(buf, 0, len);
        }
        fis.close();
        fis = null;
        buf[0] = 0;
        out.write(buf, 0, 1);
        out.flush();
        check = checkAck(in);
        if (check != 0) {
            throw new IOException("CheckAck failed when sending file data (" + check + ")");
        }
        // Cleanup
        out.close();
        channel.disconnect();
    } catch (JSchException e) {
        e.printStackTrace();
    }
}
Example 30
Project: ciscorouter-master  File: Scanner.java View source code
/**
     * Connects to the device and retrieves the configuration file from the 
     * device.
     * @return A ArrayList containing the output from the GET_ALL_CONFIG
     * command 
     */
private ArrayList<String> getConfigFile() throws Exception {
    JSch jsch = new JSch();
    InputStream in = null;
    Session session = jsch.getSession(host.getUser(), host.toString(), SSH_PORT);
    session.setPassword(host.getPass());
    //If this line isn't present, every host must be in known_hosts
    session.setConfig("StrictHostKeyChecking", "no");
    session.connect();
    Channel channel = session.openChannel("shell");
    in = channel.getInputStream();
    OutputStream outputStream = channel.getOutputStream();
    Expect expect = new ExpectBuilder().withOutput(outputStream).withInputs(channel.getInputStream(), channel.getExtInputStream()).build();
    channel.connect();
    if (host.usesEnable()) {
        expect.expect(contains(">"));
        expect.sendLine(ENABLE_SUPERUSER);
        expect.expect(contains(PASSWORD_PROMPT));
        expect.sendLine(host.getEnablePass());
    }
    //#
    expect.expect(contains("#"));
    //terminal length 0
    expect.sendLine(DISABLE_OUTPUT_BUFFERING);
    //#
    expect.expect(contains("#"));
    //show running-config full
    expect.sendLine(GET_ALL_CONFIG);
    //#
    String result = expect.expect(contains("#")).getBefore();
    channel.disconnect();
    session.disconnect();
    expect.close();
    String[] arrLines = result.split("\n");
    ArrayList<String> lines = new ArrayList<>(Arrays.asList(arrLines));
    return lines;
}
Example 31
Project: cmn-project-master  File: SSH.java View source code
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();
    }
}
Example 32
Project: DeployMan-master  File: SshClient.java View source code
private String runCommand(Session session, String command) throws IOException, JSchException {
    //$NON-NLS-1$
    Channel channel = session.openChannel("exec");
    ((ChannelExec) channel).setCommand(command);
    channel.connect();
    InputStream inputStream = channel.getInputStream();
    String result = IOUtils.toString(inputStream);
    IOUtils.closeQuietly(inputStream);
    channel.disconnect();
    return result;
}
Example 33
Project: deploymentobjects-master  File: JschDispatch.java View source code
@Override
public void dispatch(DispatchEvent event) {
    System.out.println("JSCH Dispatch recieved " + event);
    String allOutput = "";
    for (Host node : event.target.getHosts()) {
        try {
            session = jsch.getSession(userName, node.getHostname());
            jsch.addIdentity(System.getProperty("user.home") + "/.ssh/id_rsa");
            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(event.getContents());
            InputStream in = channel.getInputStream();
            InputStream ext = channel.getExtInputStream();
            channel.connect();
            byte[] tmp = new byte[1024];
            String output = "";
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0)
                        break;
                    output += new String(tmp, 0, i);
                }
                // TODO output and error streams are being combined.
                while (ext.available() > 0) {
                    int i = ext.read(tmp, 0, 1024);
                    if (i < 0)
                        break;
                    output += new String(tmp, 0, i);
                }
                // TODO This exit code should probably be better handled.  Think about how...
                if (channel.isClosed()) {
                    System.out.println("exit-status: " + channel.getExitStatus());
                    if (channel.getExitStatus() != 0) {
                        publisher.publish(DispatchEvent.fromEvent(event, DispatchEventType.JSCH_DISPATCH_NONZERO_EXIT).addOutput(output));
                    }
                    break;
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ee) {
                    publisher.publish(DispatchEvent.fromEvent(event, DispatchEventType.JSCH_DISPATCH_INTERRUPTED).addOutput(output));
                    break;
                }
            }
            channel.disconnect();
            session.disconnect();
            publisher.publish(DispatchEvent.fromEvent(event, DispatchEventType.JSCH_DISPATCH_HOST_COMPLETED).addOutput(output));
            allOutput += output;
        } catch (Exception e) {
            publisher.publish(DispatchEvent.fromEvent(event, DispatchEventType.JSCH_DISPATCH_FAILED).addOutput(e.toString()));
        }
    }
    publisher.publish(DispatchEvent.fromEvent(event, DispatchEventType.JSCH_DISPATCH_ALL_HOSTS_COMPLETED).addOutput(allOutput));
}
Example 34
Project: dtf-master  File: DeployDTF.java View source code
public static Properties getState(String component, String host, String user, String path, String rsakey, String passphrase) throws JSchException, SftpException, IOException {
    Properties props = new Properties();
    Session session = SSHUtil.connectToHost(host, user, rsakey, passphrase);
    Channel sChannel = session.openChannel("sftp");
    sChannel.connect();
    ChannelSftp csftp = (ChannelSftp) sChannel;
    if (path == null)
        path = csftp.getHome() + "/dtf";
    File tmp = new File(component + ".state");
    tmp.deleteOnExit();
    FileOutputStream fos = null;
    FileInputStream fis = null;
    try {
        fos = new FileOutputStream(tmp);
        csftp.get(path + "/state/" + component + ".state", fos);
        fos.close();
        fis = new FileInputStream(tmp);
        props.load(fis);
    } finally {
        if (fos != null)
            fos.close();
        if (fis != null)
            fis.close();
    }
    return props;
}
Example 35
Project: fscrawler-master  File: FileAbstractorSSH.java View source code
private ChannelSftp openSSHConnection(Server server) throws Exception {
    logger.debug("Opening SSH connection to {}@{}", server.getUsername(), server.getHostname());
    JSch jsch = new JSch();
    Session session = jsch.getSession(server.getUsername(), server.getHostname(), server.getPort());
    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    if (server.getPemPath() != null) {
        jsch.addIdentity(server.getPemPath());
    }
    session.setConfig(config);
    if (server.getPassword() != null) {
        session.setPassword(server.getPassword());
    }
    session.connect();
    //Open a new session for SFTP.
    Channel channel = session.openChannel("sftp");
    channel.connect();
    //checking SSH client connection.
    if (!channel.isConnected()) {
        logger.warn("Cannot connect with SSH to {}@{}", server.getUsername(), server.getHostname());
        throw new RuntimeException("Can not connect to " + server.getUsername() + "@" + server.getHostname());
    }
    logger.debug("SSH connection successful");
    return (ChannelSftp) channel;
}
Example 36
Project: hq-master  File: SSHCopy.java View source code
public void copy(File file, String remotePath, boolean showProgress) throws SSHRemoteException {
    Session session = null;
    Channel channel = null;
    try {
        session = openSession();
        channel = session.openChannel("exec");
        String command = "scp -p -t " + remotePath;
        ((ChannelExec) channel).setCommand(command);
        InputStream in = channel.getInputStream();
        OutputStream out = channel.getOutputStream();
        channel.connect();
        waitForAck(in);
        doSingleCopy(file, in, out, showProgress);
    } catch (JSchException e) {
        throw new SSHRemoteException("Error connecting to host: " + e, e);
    } catch (IOException e) {
        throw new SSHRemoteException("I/O error: " + e, e);
    } finally {
        if (channel != null) {
            channel.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
    }
}
Example 37
Project: jbosstools-integration-stack-tests-master  File: ShellManager.java View source code
/**
	 * Executes given command. Execution is synchronous - Method waits until reaction to given command is complete
	 * (InputStream is closed).
	 * 
	 * @param command
	 *            Command that is sent to the host for execution
	 * @return The host's reaction to given command
	 * 
	 * @throws JSchException
	 *             In case something is wrong with command execution
	 * @throws IOException
	 *             In case something is wrong with reading reaction to given command
	 */
public String execute(String command) throws JSchException, IOException {
    StringBuilder output = new StringBuilder(1000);
    log.debug("Openig channel ...");
    channel = session.openChannel("exec");
    ((ChannelExec) channel).setCommand(command);
    channel.setInputStream(null);
    ((ChannelExec) channel).setErrStream(System.err);
    InputStream in = channel.getInputStream();
    log.debug("Executig command '" + command + "'...");
    channel.connect();
    byte[] tmp = new byte[1024];
    while (true) {
        while (in.available() > 0) {
            int i = in.read(tmp, 0, 1024);
            if (i < 0)
                break;
            output.append(new String(tmp, 0, i));
        }
        if (channel.isClosed()) {
            if (in.available() > 0)
                continue;
            output.append("exit-status: " + channel.getExitStatus());
            break;
        }
        try {
            Thread.sleep(1000);
        } catch (Exception ee) {
        }
    }
    log.debug("Execution done!");
    channel.disconnect();
    log.debug("Channel is closed");
    return output.toString();
}
Example 38
Project: jenkins-cloud-plugin-master  File: OpenShiftComputerLauncher.java View source code
@Override
public void launch(SlaveComputer slaveComputer, TaskListener taskListener) throws IOException, InterruptedException {
    LOGGER.info("Launching slave...");
    OpenShiftComputer computer = (OpenShiftComputer) slaveComputer;
    // If the slave doesn't have a uuid, connect it
    if (computer.getNode().getUuid() == null) {
        // Don't delay DNS lookup since in this case, Jenkins has probably
        // just been restarted and the slave is still running
        computer.getNode().connect(true);
    }
    LOGGER.info("Checking availability of computer " + computer.getNode());
    String hostName = computer.getNode().getHostName();
    LOGGER.info("Checking SSH access to application " + hostName);
    try {
        final JSch jsch = new JSch();
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        // Add the private key location
        jsch.addIdentity(OpenShiftCloud.get().getPrivateKey().getAbsolutePath());
        // The user for the SSH connection is the application uuid
        String username = computer.getNode().getUuid();
        LOGGER.info("Connecting via SSH '" + username + "' '" + hostName + "' '" + OpenShiftCloud.get().getPrivateKey().getAbsolutePath() + "'");
        final Session sess = jsch.getSession(username, hostName, 22);
        sess.setConfig(config);
        sess.connect();
        LOGGER.info("Connected via SSH.");
        PrintStream logger = taskListener.getLogger();
        logger.println("Attempting to connect slave...");
        logger.println("Transferring slave.jar file...");
        // A command for the initial slave setup
        StringBuilder execCommand = new StringBuilder();
        execCommand.append("mkdir -p $OPENSHIFT_DATA_DIR/jenkins").append(" && cd $OPENSHIFT_DATA_DIR/jenkins").append(" && rm -f slave.jar").append(" && wget -q --no-check-certificate https://").append(getGearDNS(hostName)).append("/jnlpJars/slave.jar");
        String command = execCommand.toString();
        LOGGER.info("Exec " + command);
        // Open an execution channel that supports SSH agent forwarding
        Channel channel = sess.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        channel.connect();
        // Wait for the channel to close
        while (true) {
            if (channel.isClosed()) {
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception ee) {
            }
        }
        int result = channel.getExitStatus();
        if (result != 0) {
            LOGGER.warning("Download of slave.jar failed.  Return code = " + result);
            throw new IOException("Download of slave.jar failed.  Return code = " + result);
        }
        channel.disconnect();
        // Execute the slave.jar to establish a connection
        // Make sure to enable SSH agent forwarding
        logger.println("Executing slave jar to make connection...");
        final Channel slaveChannel = sess.openChannel("exec");
        String sshWrapperPath = "/usr/libexec/openshift/cartridges/jenkins/bin/git_ssh_wrapper.sh";
        ((ChannelExec) slaveChannel).setEnv("GIT_SSH", sshWrapperPath);
        ((ChannelExec) slaveChannel).setAgentForwarding(true);
        String jarCachePath = System.getenv("JENKINS_JAR_CACHE_PATH");
        if (jarCachePath == null) {
            jarCachePath = "$OPENSHIFT_DATA_DIR/.jenkins/cache/jars";
        }
        //jar-cache parameter needed for jenkins 1.540+
        ((ChannelExec) slaveChannel).setCommand("java -jar $OPENSHIFT_DATA_DIR/jenkins/slave.jar -jar-cache " + jarCachePath);
        InputStream serverOutput = slaveChannel.getInputStream();
        OutputStream clientInput = slaveChannel.getOutputStream();
        slaveChannel.connect();
        if (slaveChannel.isClosed()) {
            LOGGER.severe("Slave connection terminated early with exit = " + channel.getExitStatus());
        }
        computer.setChannel(serverOutput, clientInput, taskListener, new Listener() {

            public void onClosed(hudson.remoting.Channel channel, IOException cause) {
                slaveChannel.disconnect();
                sess.disconnect();
            }
        });
        LOGGER.info("Slave connected.");
        logger.flush();
    } catch (JSchException e) {
        e.printStackTrace();
        throw new IOException(e);
    }
}
Example 39
Project: jgrith-master  File: GridSshKey.java View source code
public static void main(String[] args) throws Exception {
    //		GridSshKey newKey = createDefaultGridsshkey("test".toCharArray(), "markus");
    //		
    //		if ( true ) {
    //			System.exit(1);
    //		}
    GridSshKey gsk = new GridSshKey();
    //		gsk.setPassword("test".toCharArray());
    System.out.println(gsk.exists());
    JSch jSch = new JSch();
    jSch.addIdentity(gsk.getKeyPath(), "test2");
    Session session = jSch.getSession("mbin029", "login.uoa.nesi.org.nz", 22);
    UserInfo ui = new UserInfo() {

        @Override
        public void showMessage(String message) {
            // TODO Auto-generated method stub
            System.out.println(message);
        }

        @Override
        public boolean promptYesNo(String message) {
            System.out.println(message);
            return true;
        }

        @Override
        public boolean promptPassword(String message) {
            // TODO Auto-generated method stub
            System.out.println(message);
            return false;
        }

        @Override
        public boolean promptPassphrase(String message) {
            // TODO Auto-generated method stub
            System.out.println(message);
            return false;
        }

        @Override
        public String getPassword() {
            // TODO Auto-generated method stub
            System.out.println("PASSWORD");
            return null;
        }

        @Override
        public String getPassphrase() {
            // TODO Auto-generated method stub
            System.out.println("GET PASSWORD");
            return null;
        }
    };
    session.setUserInfo(ui);
    session.connect();
    Channel channel = session.openChannel("sftp");
    ChannelSftp sftp = (ChannelSftp) channel;
    sftp.connect();
    final Vector files = sftp.ls(".");
    for (Object obj : files) {
    // Do stuff with files
    }
    sftp.disconnect();
    session.disconnect();
}
Example 40
Project: jucy-master  File: UploadFile.java View source code
public boolean upload(File sourceFolder, String targetFolder) {
    JSch jsch = new JSch();
    int port = 22;
    Session session = null;
    Channel channel = null;
    try {
        session = jsch.getSession(username, host, port);
        UserInfo ui = new UPFileUserInfo();
        session.setUserInfo(ui);
        session.connect();
        channel = session.openChannel("sftp");
        channel.connect();
        ChannelSftp c = (ChannelSftp) channel;
        long before = System.currentTimeMillis();
        long total = rekUpload(sourceFolder, targetFolder, c);
        long timeTotal = System.currentTimeMillis() - before;
        System.out.println(String.format("Totally uploaded: %.2f MiB in %2$tH:%2$tM:%2$tS", (double) total / (1024 * 1024), timeTotal));
        c.disconnect();
        return true;
    } catch (JSchException e) {
        e.printStackTrace();
    } catch (SftpException e) {
        e.printStackTrace();
    } finally {
        if (channel != null) {
            channel.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
    }
    return false;
}
Example 41
Project: judochop-master  File: Job.java View source code
private void executeSsh(SSHCommand command, Session session, ResponseInfo response) {
    Channel channel = null;
    String message;
    try {
        channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command.getCommand());
        channel.connect();
        BufferedReader reader = new BufferedReader(new InputStreamReader(channel.getInputStream()));
        while ((message = reader.readLine()) != null) {
            response.addMessage(message);
        }
        reader.close();
        reader = new BufferedReader(new InputStreamReader(((ChannelExec) channel).getErrStream()));
        while ((message = reader.readLine()) != null) {
            response.addErrorMessage(message);
        }
        reader.close();
    } catch (Exception e) {
        message = "Error while sending ssh command to " + value.getPublicIpAddress();
        LOG.warn(message, e);
        response.addErrorMessage(message);
    } finally {
        try {
            if (channel != null) {
                channel.disconnect();
            }
        } catch (Exception e) {
        }
    }
}
Example 42
Project: katta-master  File: SshUtil.java View source code
public static void scp(String keyPath, String sourcePath, String targetHostName, String targetFileName) throws IOException {
    try {
        File keyFile = new File(keyPath);
        JSch jsch = new JSch();
        jsch.addIdentity(keyFile.getAbsolutePath());
        Session session = jsch.getSession("root", targetHostName, 22);
        UserInfo ui = new SshUser();
        session.setUserInfo(ui);
        session.connect();
        String command = "scp -p -t  " + targetFileName;
        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();
        if (checkAck(in) != 0) {
            throw new RuntimeException("Failed to scp key file");
        }
        // send "C0644 filesize filename", where filename should not include
        // '/'
        long filesize = (new File(sourcePath)).length();
        command = "C0644 " + filesize + " ";
        if (sourcePath.lastIndexOf('/') > 0) {
            command += sourcePath.substring(sourcePath.lastIndexOf('/') + 1);
        } else {
            command += sourcePath;
        }
        command += "\n";
        out.write(command.getBytes());
        out.flush();
        if (checkAck(in) != 0) {
            // throws an exception now.
            throw new RuntimeException("Fatal Error scp key file");
        }
        // send a content of lfile
        FileInputStream fis = new FileInputStream(sourcePath);
        byte[] buf = new byte[1024];
        while (true) {
            int len = fis.read(buf, 0, buf.length);
            if (len <= 0)
                break;
            // out.flush();
            out.write(buf, 0, len);
        }
        fis.close();
        fis = null;
        // send '\0'
        buf[0] = 0;
        out.write(buf, 0, 1);
        out.flush();
        if (checkAck(in) != 0) {
            throw new RuntimeException("Failed to scp  file");
        }
        out.close();
        channel.disconnect();
        session.disconnect();
    } catch (JSchException e) {
        throw new IOException("Unable to copy key file to host: ", e);
    }
}
Example 43
Project: SocialDataImporter-master  File: SshExecutor.java View source code
public void executeCmd(String aCommand) throws SdiException {
    if (mySession == null) {
        throw new SdiException("SSH session not initialized.", SdiException.EXIT_CODE_SSH_ERROR);
    }
    if (!mySession.isConnected()) {
        throw new SdiException("SSH session not connected.", SdiException.EXIT_CODE_SSH_ERROR);
    }
    Channel channel = null;
    try {
        channel = mySession.openChannel("exec");
        myLog.debug("executing SSH command " + aCommand);
        ((ChannelExec) channel).setCommand(aCommand);
        ByteArrayOutputStream osOut = new ByteArrayOutputStream();
        ByteArrayOutputStream osErr = new ByteArrayOutputStream();
        try {
            channel.setInputStream(null);
            channel.setOutputStream(osOut, true);
            ((ChannelExec) channel).setErrStream(osErr, true);
            myLog.debug("connecting the channel");
            channel.connect();
            while (true) {
                if (channel.isClosed()) {
                    break;
                }
                try {
                    myLog.debug("going to sleep 50 ms");
                    Thread.sleep(50);
                } catch (Exception ee) {
                }
            }
        } finally {
            String out = new String(osOut.toByteArray());
            if (StringUtils.hasText(out)) {
                myLog.info("Captured SSH out:\n" + out);
            }
            // if StringUtils.hasText( out )
            String err = new String(osErr.toByteArray());
            if (StringUtils.hasText(err)) {
                myLog.warn("Captured SSH err:\n" + err);
            }
        // if StringUtils.hasText( out )
        }
    } catch (Throwable t) {
        throw new SdiException("SSH session not connected.", t, SdiException.EXIT_CODE_SSH_ERROR);
    } finally {
        if (channel != null) {
            int exitStatus = channel.getExitStatus();
            myLog.debug("SSH exit status: " + exitStatus);
            myLog.debug("disconnecting the channel");
            channel.disconnect();
            if (exitStatus != 0) {
                throw new SdiException("SSH not successful. SSH-Exitstatus: " + exitStatus, SdiException.EXIT_CODE_SSH_ERROR);
            }
        // if exitStatus
        }
    // if channel != null
    }
}
Example 44
Project: structr-master  File: SSHTest.java View source code
/**
	 * Creates an FTP client, a backend user and logs this user in.
	 *
	 * @param username
	 * @return
	 */
protected ChannelSftp setupSftpClient(final String username, final String password) {
    try (final Tx tx = app.tx()) {
        ftpUser = createFTPUser(username, password);
        tx.success();
    } catch (FrameworkException fex) {
        logger.error("Unable to create SFTP user", fex);
    }
    JSch jsch = new JSch();
    try {
        final Session session = jsch.getSession(username, host, sshPort);
        session.setConfig("StrictHostKeyChecking", "no");
        session.setPassword(password);
        session.connect(1000);
        final Channel channel = session.openChannel("sftp");
        channel.connect(1000);
        return (ChannelSftp) channel;
    } catch (JSchException ex) {
        ex.printStackTrace();
    }
    return null;
}
Example 45
Project: cats-master  File: FtpSearchUtil.java View source code
/**
     * 
     * @param host
     * @param username
     * @param password
     * @param directory
     * @param filename
     * @param expression
     * @return
     * @throws IOException
     */
public static Integer countHitsByRegex(String host, String username, String password, String directory, String filename, String expression) throws IOException {
    if (!(isValidInput(host, username, password, directory, filename, expression))) {
        throw new IllegalArgumentException("Cannot perform FTP search. Make sure all inputs are valid");
    }
    int hits = 0;
    JSch jsch = new JSch();
    Session session = null;
    FileReader fileReader = null;
    BufferedReader bufferedReader = null;
    try {
        session = jsch.getSession(username, host);
        session.setConfig(getHostConfiguration());
        session.setPassword(password);
        session.connect();
        LOGGER.info("Session starting [" + host + "]");
        Channel channel = session.openChannel(TYPE_SFTP);
        channel.connect();
        LOGGER.info("Connected  [" + host + "]");
        ChannelSftp sftpChannel = (ChannelSftp) channel;
        sftpChannel.cd(directory);
        LOGGER.info("Directory changed  [" + directory + "]");
        InputStream is = sftpChannel.get(filename);
        LOGGER.info("Starting read [" + filename + "]");
        Pattern pattern = Pattern.compile(expression);
        bufferedReader = new BufferedReader(new InputStreamReader(is));
        String line = "";
        while ((line = bufferedReader.readLine()) != null) {
            if (pattern.matcher(line).find()) {
                hits++;
            }
        }
        sftpChannel.exit();
        session.disconnect();
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    } finally {
        try {
            if (fileReader != null) {
                fileReader.close();
            }
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }
    return hits;
}
Example 46
Project: coprhd-controller-master  File: VNXFileSshApi.java View source code
/**
     * Executes a command on the VNX File CLI.
     * 
     * @param command command to execute on the VNX File CLI.
     * @param request payload for the command
     * @return result of executing the command.
     */
public XMLApiResult executeSsh(String command, String request) {
    XMLApiResult result = new XMLApiResult();
    if ((_host == null) || (_userName == null) || (_password == null)) {
        _log.error("Invalid connection parameter");
        result.setCommandFailed();
        return result;
    }
    String cmd = "export NAS_DB=/nas;" + command + " " + request;
    _log.info("executeSsh: cmd: " + cmd);
    InputStream in = null;
    Session session = null;
    Channel channel = null;
    try {
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        JSch jsch = new JSch();
        session = jsch.getSession(_userName, _host, DEFAULT_PORT);
        session.setPassword(_password);
        session.setConfig(config);
        session.connect();
        channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(cmd);
        channel.setInputStream(null);
        in = channel.getInputStream();
        channel.connect();
        byte[] tmp = new byte[BUFFER_SIZE];
        StringBuilder cmdResults = new StringBuilder();
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, BUFFER_SIZE);
                if (i < 0) {
                    break;
                }
                cmdResults.append(new String(tmp, 0, i));
            }
            if (channel.isClosed()) {
                _log.info("Ssh exit status: " + channel.getExitStatus());
                result.setMessage(cmdResults.toString());
                // Set the command result status.
                if (channel.getExitStatus() == 0) {
                    StringTokenizer st = new StringTokenizer(cmdResults.toString());
                    if (st.hasMoreTokens()) {
                        // data mover name
                        st.nextToken();
                    }
                    if (!command.equalsIgnoreCase(SERVER_USER_CMD)) {
                        if (st.hasMoreTokens()) {
                            st.nextToken();
                        }
                    }
                    String res = "";
                    if (st.hasMoreTokens()) {
                        // contains status or result.
                        res = st.nextToken();
                    }
                    if (res.equalsIgnoreCase("done")) {
                        result.setCommandSuccess();
                    } else if (res.equalsIgnoreCase("error")) {
                        result.setCommandFailed();
                    } else {
                        result.setCommandSuccess();
                    }
                } else {
                    result.setCommandFailed();
                }
                break;
            }
            try {
                Thread.sleep(_respDelay);
            } catch (InterruptedException e) {
                _log.error("VNX File executeSsh Communication thread interrupted for command: " + cmd, e);
            }
        }
        _log.info("executeSsh: Done");
    } catch (Exception e) {
        _log.error("VNX File executeSsh connection failed while attempting to execute: " + cmd, e);
        result.setCommandFailed();
        result.setMessage(e.getMessage());
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ignored) {
                _log.error("Exception occured while closing input stream due to ", ignored);
            }
        }
        if (channel != null) {
            channel.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
    }
    return result;
}
Example 47
Project: Far-On-Droid-master  File: SftpAPI.java View source code
public void connect(String server, int port, String user, String password, boolean isLoginByPrivateKey, byte[] privateKey) throws InAppAuthException {
    JSch jsch = new JSch();
    Session session;
    try {
        session = jsch.getSession(user, server, port);
    } catch (JSchException e) {
        e.printStackTrace();
        throw new InAppAuthException(App.sInstance.getString(R.string.error_sftp_connection_error));
    }
    session.setPassword(password);
    Properties prop = new Properties();
    prop.put("StrictHostKeyChecking", "no");
    session.setConfig(prop);
    Channel channel;
    try {
        session.connect();
        channel = session.openChannel("sftp");
        channel.connect();
    } catch (JSchException e) {
        throw new InAppAuthException(App.sInstance.getString(R.string.error_sftp_connection_error));
    }
    mSftpChannel = (ChannelSftp) channel;
    String charset = App.sInstance.getSettings().getSftpCharset(server);
    if (charset != null) {
        setCharsetEncoding(charset);
    }
}
Example 48
Project: gft-master  File: Ssh.java View source code
public static ExecResult exec(SshHost host, Ssh.Credentials cred, String command) {
    logger.info("Calling {} with command [{}]", host, command);
    FileOutputStream fos = null;
    try {
        JSch jsch = new JSch();
        if (host.known_hosts != null)
            jsch.setKnownHosts(host.known_hosts);
        if (cred.keyfile != null) {
            logger.debug("Using keyfile {}", cred.keyfile);
            jsch.addIdentity(cred.keyfile);
        }
        Session session = jsch.getSession(cred.user, host.host, 22);
        // username and password will be given via UserInfo interface.
        session.setUserInfo(cred);
        session.connect();
        // exec 'scp -f rfile' remotely
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        ((ChannelExec) channel).setAgentForwarding(true);
        ByteArrayOutputStream err = new ByteArrayOutputStream();
        ((ChannelExec) channel).setErrStream(err);
        channel.setInputStream(null);
        InputStream in = channel.getInputStream();
        channel.connect();
        StringBuilder result = new StringBuilder();
        byte[] tmp = new byte[1024];
        int i;
        do {
            i = in.read(tmp, 0, 1024);
            if (i > 0)
                result.append(new String(tmp, 0, i));
        } while (i >= 0);
        int count = 0;
        while (!channel.isClosed()) {
            if (count >= 50)
                throw new RuntimeException("SSH Channel was not closed after " + count + " waiting attempts");
            logger.info("Sleeping some time because channel is not yet closed, attempt " + count++);
            try {
                Thread.sleep(200);
            } catch (Exception ee) {
            }
        }
        int exitvalue = channel.getExitStatus();
        //channel.disconnect();
        session.disconnect();
        if (logger.isWarnEnabled()) {
            if (exitvalue != 0)
                logger.warn("Call to {} returned exitvalue " + exitvalue, host);
            if (err.size() > 0)
                logger.warn("Call to {} returned stderr {}", host, err.toString());
            if (logger.isInfoEnabled())
                logger.info("Call to {} returned stdout [{}]", host, result);
        }
        return new ExecResult(exitvalue, result.toString(), err.toString());
    } catch (IOException e) {
        throw new RetryableException(e);
    } catch (JSchException e) {
        if (e.getCause() instanceof IOException)
            throw new RetryableException(e);
        else
            throw new RuntimeException(e);
    } finally {
        try {
            if (fos != null)
                fos.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
Example 49
Project: Hydrograph-master  File: SCPUtility.java View source code
/**
	 * 
	 * 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();
}
Example 50
Project: JFTClient-master  File: Connection.java View source code
public synchronized void sendCommand(String command) {
    List<Text> output = new ArrayList<>();
    output.add(JFTText.getRemoteHost(remoteHost));
    output.add(JFTText.textBlack(command));
    try {
        Channel channel = this.session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        channel.setInputStream(null);
        OutputStream out = new PipedOutputStream();
        channel.setOutputStream(out);
        OutputStream outErr = new PipedOutputStream();
        ((ChannelExec) channel).setErrStream(outErr);
        PipedInputStream pout = new PipedInputStream((PipedOutputStream) out);
        PipedInputStream poutErr = new PipedInputStream((PipedOutputStream) outErr);
        channel.connect(timeout);
        try (BufferedReader consoleOutput = new BufferedReader(new InputStreamReader(pout, Charset.defaultCharset()))) {
            String s;
            while ((s = consoleOutput.readLine()) != null) {
                output.add(JFTText.textBlack("\n" + s));
            }
        }
        try (BufferedReader consoleErr = new BufferedReader(new InputStreamReader(poutErr, Charset.defaultCharset()))) {
            String s;
            while ((s = consoleErr.readLine()) != null) {
                output.add(JFTText.textRed("\n" + s));
            }
        }
        channel.disconnect();
    } catch (IOExceptionJSchException |  e) {
        logger.error("failed to send command: {}", command, e);
    }
    OutputPanel.getInstance().printlnOutputLater(output);
}
Example 51
Project: Kylin-master  File: SSHClient.java View source code
public void scpFileToRemote(String localFile, String remoteTargetDirectory) throws Exception {
    FileInputStream fis = null;
    try {
        logger.info("SCP file " + localFile + " to " + remoteTargetDirectory);
        Session session = newJSchSession();
        session.connect();
        boolean ptimestamp = false;
        // exec 'scp -t rfile' remotely
        String command = "scp " + (ptimestamp ? "-p" : "") + " -t " + remoteTargetDirectory;
        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();
        if (checkAck(in) != 0) {
            System.exit(0);
        }
        File _lfile = new File(localFile);
        if (ptimestamp) {
            command = "T " + (_lfile.lastModified() / 1000) + " 0";
            // The access time should be sent here,
            // but it is not accessible with JavaAPI ;-<
            command += (" " + (_lfile.lastModified() / 1000) + " 0\n");
            out.write(command.getBytes());
            out.flush();
            if (checkAck(in) != 0) {
                throw new Exception("Error in checkAck()");
            }
        }
        // send "C0644 filesize filename", where filename should not include '/'
        long filesize = _lfile.length();
        command = "C0644 " + filesize + " ";
        if (localFile.lastIndexOf("/") > 0) {
            command += localFile.substring(localFile.lastIndexOf("/") + 1);
        } else if (localFile.lastIndexOf(File.separator) > 0) {
            command += localFile.substring(localFile.lastIndexOf(File.separator) + 1);
        } else {
            command += localFile;
        }
        command += "\n";
        out.write(command.getBytes());
        out.flush();
        if (checkAck(in) != 0) {
            throw new Exception("Error in checkAck()");
        }
        // send a content of lfile
        fis = new FileInputStream(localFile);
        byte[] buf = new byte[1024];
        while (true) {
            int len = fis.read(buf, 0, buf.length);
            if (len <= 0)
                break;
            // out.flush();
            out.write(buf, 0, len);
        }
        fis.close();
        fis = null;
        // send '\0'
        buf[0] = 0;
        out.write(buf, 0, 1);
        out.flush();
        if (checkAck(in) != 0) {
            throw new Exception("Error in checkAck()");
        }
        out.close();
        channel.disconnect();
        session.disconnect();
    } catch (Exception e) {
        throw e;
    } finally {
        IOUtils.closeQuietly(fis);
    }
}
Example 52
Project: openbel-framework-experimental  File: SftpProtocolHandler.java View source code
/**
     * {@inheritDoc}
     */
@Override
public File downloadResource(final String url, final String path) throws ResourceDownloadError {
    JSch jsch = new JSch();
    String[] sftpPath = url.substring(7).split("\\@");
    final String[] userCreds = sftpPath[0].split("\\:");
    try {
        String host;
        int port = ProtocolHandlerConstants.DEFAULT_SSH_PORT;
        String filePath = sftpPath[1].substring(sftpPath[1].indexOf('/'));
        String[] location = sftpPath[1].split("\\/");
        if (location[0].contains(":")) {
            String[] hostPort = location[0].split("\\:");
            host = hostPort[0];
            port = Integer.parseInt(hostPort[1]);
        } else {
            host = location[0];
        }
        if (userCreds == null || userCreds.length == 0) {
            throw new UnsupportedOperationException("Non-specified user in sftp URL not supported yet.");
        }
        Session session = jsch.getSession(userCreds[0], host, port);
        //don't validate against a known_hosts file
        session.setConfig("StrictHostKeyChecking", "no");
        session.setConfig("PreferredAuthentications", "password,gssapi-with-mic,publickey,keyboard-interactive");
        if (userCreds.length == 1) {
            session.setUserInfo(ui);
        } else {
            session.setPassword(userCreds[1]);
        }
        session.connect();
        Channel channel = session.openChannel("sftp");
        channel.connect();
        ChannelSftp c = (ChannelSftp) channel;
        File downloadFile = new File(path);
        FileOutputStream tempFileOutputStream = new FileOutputStream(downloadFile);
        IOUtils.copy(c.get(filePath), tempFileOutputStream);
        channel.disconnect();
        session.disconnect();
        return downloadFile;
    } catch (Exception e) {
        final String msg = "Error downloading namespace";
        throw new ResourceDownloadError(url, msg, e);
    }
}
Example 53
Project: parallec-master  File: SshProvider.java View source code
/**
     * Session connect generate channel.
     *
     * @param session
     *            the session
     * @return the channel
     * @throws JSchException
     *             the j sch exception
     */
public Channel sessionConnectGenerateChannel(Session session) throws JSchException {
    // set timeout
    session.connect(sshMeta.getSshConnectionTimeoutMillis());
    ChannelExec channel = (ChannelExec) session.openChannel("exec");
    channel.setCommand(sshMeta.getCommandLine());
    // if run as super user, assuming the input stream expecting a password
    if (sshMeta.isRunAsSuperUser()) {
        try {
            channel.setInputStream(null, true);
            OutputStream out = channel.getOutputStream();
            channel.setOutputStream(System.out, true);
            channel.setExtOutputStream(System.err, true);
            channel.setPty(true);
            channel.connect();
            out.write((sshMeta.getPassword() + "\n").getBytes());
            out.flush();
        } catch (IOException e) {
            logger.error("error in sessionConnectGenerateChannel for super user", e);
        }
    } else {
        channel.setInputStream(null);
        channel.connect();
    }
    return channel;
}
Example 54
Project: Scarlet-Nebula-master  File: SSHCommandConnection.java View source code
public Connection getJSchTerminalConnection() throws JSchException, IOException {
    final Channel channel = session.openChannel("shell");
    final OutputStream out = channel.getOutputStream();
    final InputStream in = channel.getInputStream();
    channel.connect();
    final OutputStream fout = out;
    final InputStream fin = in;
    final Channel fchannel = channel;
    final Connection connection = new Connection() {

        @Override
        public InputStream getInputStream() {
            return fin;
        }

        @Override
        public OutputStream getOutputStream() {
            return fout;
        }

        @Override
        public void requestResize(final Term term) {
            if (fchannel instanceof ChannelShell) {
                final int c = term.getColumnCount();
                final int r = term.getRowCount();
                ((ChannelShell) fchannel).setPtySize(c, r, c * term.getCharWidth(), r * term.getCharHeight());
            }
        }

        @Override
        public void close() {
            fchannel.disconnect();
        }
    };
    return connection;
}
Example 55
Project: Thngm-master  File: SFTPTransport.java View source code
/* (non-Javadoc)
     * @see net.sf.thingamablog.transport.PublishTransport#connect()
     */
public boolean connect() {
    failMsg = "";
    if (isConnected) {
        failMsg = "Already connected";
        return false;
    }
    try {
        JSch jsch = new JSch();
        Session session = jsch.getSession(getUserName(), getAddress(), getPort());
        // password will be given via UserInfo interface.
        UserInfo ui = new MyUserInfo(getPassword());
        session.setUserInfo(ui);
        logger.info("Connecting to SFTP");
        session.connect();
        logger.info("Logged in to SFTP");
        Channel channel = session.openChannel("sftp");
        channel.connect();
        sftp = (ChannelSftp) channel;
        isConnected = true;
        return true;
    } catch (Exception ex) {
        failMsg = "Error logging in to " + getAddress();
        failMsg += "\n" + ex.getMessage();
        logger.log(Level.WARNING, failMsg, ex);
        ex.printStackTrace();
    }
    return false;
}
Example 56
Project: twister.github.io-master  File: RunnerRepository.java View source code
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();
    }
}
Example 57
Project: user-master  File: Job.java View source code
private void executeSsh(SSHCommand command, Session session, ResponseInfo response) {
    Channel channel = null;
    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()));
        while ((message = inputReader.readLine()) != null) {
            response.addMessage(message);
            LOG.info("SSH command response: {}", message);
        }
        while ((message = errorReader.readLine()) != null) {
            response.addMessage(message);
            LOG.info("Error in ssh command: {}", message);
        }
        inputReader.close();
        errorReader.close();
    } catch (Exception e) {
        message = "Error while sending ssh command to " + value.getPublicIpAddress();
        LOG.warn(message, e);
        response.addErrorMessage(message);
    } finally {
        try {
            if (channel != null) {
                channel.disconnect();
            }
        } catch (Exception e) {
        }
    }
}
Example 58
Project: usergrid-master  File: Job.java View source code
private void executeSsh(SSHCommand command, Session session, ResponseInfo response) {
    Channel channel = null;
    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()));
        while ((message = inputReader.readLine()) != null) {
            response.addMessage(message);
            LOG.info("SSH command response: {}", message);
        }
        while ((message = errorReader.readLine()) != null) {
            response.addMessage(message);
            LOG.info("Error in ssh command: {}", message);
        }
        inputReader.close();
        errorReader.close();
    } catch (Exception e) {
        message = "Error while sending ssh command to " + value.getPublicIpAddress();
        LOG.warn(message, e);
        response.addErrorMessage(message);
    } finally {
        try {
            if (channel != null) {
                channel.disconnect();
            }
        } catch (Exception e) {
        }
    }
}
Example 59
Project: vertx-shell-master  File: SSHServerTest.java View source code
@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();
}
Example 60
Project: all-inhonmodman-master  File: CalculateJarDifferences.java View source code
/**
     * This method should only be run when a new version of the Manager will be released. It tries to make the process more automatic.
     * Currently:
     * - Writes in the Version file in LOCAL DISK (Dropbox folder, so Dropbox must be running!)
     * - Uploads the file to the correct folder tree in the SourceForge project, creating all needed folder on the way.
     */
public static void main(String[] args) throws ZipException, IOException, JSchException {
    /*
         * IMPORTANT
         * 
         * Before releasing a new version of the Manager, please, follow these instructions:
         * 0 - Update the Changelog.txt and Version.txt files
         * 1 - Check if the older version is fully compatible with this one after an update. managerOptions.xml shall not be lost by any reasons.
         * 2 - Check if the file paths below are correct.
         * 3 - Clean and build the project, then Package-for-store the Manager.jar
         * 4 - Goto Sourceforge.net and update the LABEL and the OS supported for the new Manager file.
         * 5 - Update in the HoN forums page (changelog, topic title and version in first line)
         */
    // First step is to get the version we want to release.
    String targetVersion = ManagerOptions.getInstance().getVersion();
    // Get the old jar
    File oldJarVersion = new File("C:\\Users\\Shirkit\\Dropbox\\HonModManager\\Dropbox\\Public\\versions\\Manager.jar");
    // And the newly generated one
    File newJarVersion = new File("store\\Manager.jar");
    // Target output for where the differences will be generated
    String verionsFile = "C:\\Users\\Shirkit\\Dropbox\\HonModManager\\Dropbox\\Public\\versions.txt";
    File rootVersionsFolder = new File("C:\\Users\\Shirkit\\Dropbox\\HonModManager\\Dropbox\\Public\\versions\\");
    File output = new File(rootVersionsFolder, targetVersion + ".jar");
    System.out.println("Version to be released=" + targetVersion);
    System.out.println("Old version file=" + oldJarVersion.getAbsolutePath());
    System.out.println("New version file=" + newJarVersion.getAbsolutePath());
    System.out.println();
    if (calculate(oldJarVersion, newJarVersion, output.getAbsolutePath())) {
        System.out.println("Output file generated.\nPath=" + output.getAbsolutePath() + "\nSize=" + output.length() / 1024 + "KB");
        // Read the current versions file and store it for later
        FileInputStream fis = new FileInputStream(verionsFile);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        copyInputStream(fis, baos);
        String s = baos.toString();
        fis.close();
        baos.close();
        System.out.println(s);
        if (!s.trim().isEmpty()) {
            if (s.contains("\n")) {
                System.out.println("Older version=" + s.substring(0, s.indexOf("\n")));
            } else {
                System.out.println("Older version=" + s);
            }
            s = targetVersion + "\n" + s;
        } else {
            System.out.println("First version!");
            s = targetVersion;
        }
        if (JOptionPane.showConfirmDialog(null, "Confirm upload?", "Confirmation", JOptionPane.YES_NO_OPTION) != 0) {
            System.exit(0);
        }
        // Write new versions file with the new released version
        FileWriter fw = new FileWriter(verionsFile);
        fw.write(s);
        fw.flush();
        fw.close();
        System.out.println("Versions file written with sucess!");
        fis = new FileInputStream(newJarVersion);
        FileOutputStream fos = new FileOutputStream(rootVersionsFolder + File.separator + "Manager.jar");
        copyInputStream(fis, fos);
        fis.close();
        fos.close();
        System.out.println("Manager.jar file written!");
        System.out.println();
    } else {
        System.err.println("No differences file. Output file not generated.");
        System.exit(0);
    }
    JSch jsch = new JSch();
    Session session = null;
    try {
        System.out.println("Connecting to SF");
        session = jsch.getSession(JOptionPane.showInputDialog("SourceForge Username") + ",all-inhonmodman", "frs.sourceforge.net", 22);
        session.setConfig("StrictHostKeyChecking", "no");
        session.setPassword(JOptionPane.showInputDialog("SourceForge Password"));
        session.connect();
        Channel channel = session.openChannel("sftp");
        channel.connect();
        ChannelSftp sftpChannel = (ChannelSftp) channel;
        System.out.println("Connected!");
        String root = "/home/frs/project/a/al/all-inhonmodman";
        sftpChannel.cd(root);
        StringTokenizer versionTokens = new StringTokenizer(targetVersion, " ");
        boolean flag = true;
        while (versionTokens.hasMoreTokens()) {
            String s = versionTokens.nextToken();
            if (!cdExists(sftpChannel, s)) {
                sftpChannel.mkdir(s);
                flag = false;
            }
            sftpChannel.cd(s);
        }
        if (flag) {
            System.err.println("Version already exists!");
            sftpChannel.exit();
            session.disconnect();
            System.exit(0);
        }
        System.out.println("Uploading file");
        OutputStream out = sftpChannel.put("Manager.jar");
        FileInputStream fis = new FileInputStream(newJarVersion);
        copyInputStream(fis, out);
        out.close();
        fis.close();
        System.out.println("Upload complete");
        sftpChannel.exit();
        session.disconnect();
        System.out.println("SUCESS!");
    } catch (JSchException e) {
        e.printStackTrace();
    } catch (SftpException e) {
        e.printStackTrace();
    }
    System.exit(0);
}
Example 61
Project: apache_ant-master  File: ScpToMessage.java View source code
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();
        }
    }
}
Example 62
Project: CommandHelper-master  File: SSHWrapper.java View source code
private static void SCPTo(File lfile, String rfile, Session session) throws JSchException, IOException {
    boolean ptimestamp = true;
    // exec 'scp -t rfile' remotely
    String command = "scp " + (ptimestamp ? "-p" : "") + " -t " + rfile;
    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();
    checkAck(in);
    if (ptimestamp) {
        command = "T " + (lfile.lastModified() / 1000) + " 0";
        // The access time should be sent here,
        // but it is not accessible with JavaAPI ;-<
        command += (" " + (lfile.lastModified() / 1000) + " 0\n");
        out.write(command.getBytes());
        out.flush();
        checkAck(in);
    }
    // send "C0644 filesize filename", where filename should not include '/'
    long filesize = lfile.length();
    command = "C0644 " + filesize + " ";
    if (lfile.getPath().lastIndexOf('/') > 0) {
        command += lfile.getPath().substring(lfile.getPath().lastIndexOf('/') + 1);
    } else {
        command += lfile;
    }
    command += "\n";
    out.write(command.getBytes());
    out.flush();
    checkAck(in);
    // send a content of lfile
    FileInputStream fis = new FileInputStream(lfile);
    byte[] buf = new byte[1024];
    while (true) {
        int len = fis.read(buf, 0, buf.length);
        if (len <= 0) {
            break;
        }
        //out.flush();
        out.write(buf, 0, len);
    }
    fis.close();
    fis = null;
    // send '\0'
    buf[0] = 0;
    out.write(buf, 0, 1);
    out.flush();
    checkAck(in);
    out.close();
    channel.disconnect();
}
Example 63
Project: dronekit-android-master  File: SshConnection.java View source code
public String execute(String command) throws IOException {
    if (TextUtils.isEmpty(command))
        return null;
    Session session = null;
    Channel execChannel = null;
    try {
        session = getSession();
        execChannel = session.openChannel(EXEC_CHANNEL_TYPE);
        ((ChannelExec) execChannel).setCommand(command);
        execChannel.setInputStream(null);
        final InputStream in = execChannel.getInputStream();
        execChannel.connect(CONNECTION_TIMEOUT);
        final int bufferSize = 1024;
        final StringBuilder response = new StringBuilder();
        final byte[] buffer = new byte[bufferSize];
        while (true) {
            while (in.available() > 0) {
                int dataSize = in.read(buffer, 0, bufferSize);
                if (dataSize < 0)
                    break;
                response.append(new String(buffer, 0, dataSize));
            }
            if (execChannel.isClosed()) {
                if (in.available() > 0)
                    continue;
                Timber.d("SSH command exit status: " + execChannel.getExitStatus());
                break;
            }
        }
        return response.toString();
    } catch (JSchException e) {
        throw new IOException(e);
    } finally {
        if (execChannel != null && execChannel.isConnected())
            execChannel.disconnect();
        if (session != null && session.isConnected())
            session.disconnect();
    }
}
Example 64
Project: eu.geclipse.core-master  File: SSHConnection.java View source code
/**
   * Execute a command on the remote host and returns the output.
   * 
   * @param command The command to be executed on the remote host.
   * @param stdin
   * @return Returns the output of the executed command if executed
   *         successfully, if no output of the successfully executed command
   *         <code>null</code> is returned.
   *         
   * @throws ProblemException If the command is not successfully executed.
   */
public String execCommand(final String command, final InputStream stdin) throws ProblemException {
    String line;
    Channel channel = null;
    InputStream stdout = null;
    InputStream stderr = null;
    //$NON-NLS-1$
    String result = "";
    //$NON-NLS-1$
    String errResult = "";
    int exitStatus = -1;
    BufferedReader stdoutReader = null;
    BufferedReader stderrReader = null;
    // We throw exception if we don't have a session
    if (!this.isSessionActive()) {
        IProblem problem;
        problem = ReportingPlugin.getReportingService().getProblem(ICoreProblems.NET_CONNECTION_FAILED, null, null, Activator.PLUGIN_ID);
        ISolution solution;
        solution = ReportingPlugin.getReportingService().getSolution(ICoreSolutions.NET_CHECK_INTERNET_CONNECTION, null);
        problem.addSolution(solution);
        throw new ProblemException(problem);
    }
    try {
        //$NON-NLS-1$
        channel = this.session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        channel.setInputStream(stdin);
        stdout = channel.getInputStream();
        stderr = channel.getExtInputStream();
        channel.connect();
        stdoutReader = new BufferedReader(new InputStreamReader(stdout));
        stderrReader = new BufferedReader(new InputStreamReader(stderr));
        // Make sure that the command is executed before we exit
        while (!channel.isClosed()) {
            line = stdoutReader.readLine();
            while (null != line) {
                result = result + line + '\n';
                line = stdoutReader.readLine();
            }
            line = stderrReader.readLine();
            while (null != line) {
                errResult = errResult + line + '\n';
                line = stderrReader.readLine();
            }
            try {
                Thread.sleep(1000);
            } catch (Exception ee) {
            }
        }
        // Read what is left after the channel is closed
        line = stdoutReader.readLine();
        while (null != line) {
            result = result + line + '\n';
            line = stdoutReader.readLine();
        }
        line = stderrReader.readLine();
        while (null != line) {
            errResult = errResult + line + '\n';
            line = stderrReader.readLine();
        }
        exitStatus = channel.getExitStatus();
        channel.disconnect();
    } catch (JSchException jschExc) {
        IProblem problem;
        problem = ReportingPlugin.getReportingService().getProblem(ICoreProblems.NET_CONNECTION_FAILED, null, jschExc, Activator.PLUGIN_ID);
        ISolution solution;
        solution = ReportingPlugin.getReportingService().getSolution(ICoreSolutions.NET_CHECK_INTERNET_CONNECTION, null);
        problem.addSolution(solution);
        solution = ReportingPlugin.getReportingService().getSolution(IBatchSolutions.CHECK_USERNAME_AND_PASSWORD, null);
        problem.addSolution(solution);
        solution = ReportingPlugin.getReportingService().getSolution(ICoreSolutions.NET_CHECK_FIREWALL, null);
        problem.addSolution(solution);
        throw new ProblemException(problem);
    } catch (IOException ioExc) {
        IProblem problem;
        problem = ReportingPlugin.getReportingService().getProblem(IBatchProblems.CONNECTION_IO_ERROR, null, ioExc, Activator.PLUGIN_ID);
        ISolution solution = ReportingPlugin.getReportingService().getSolution(ICoreSolutions.NET_CHECK_INTERNET_CONNECTION, null);
        problem.addSolution(solution);
        throw new ProblemException(problem);
    } finally {
        if (null != stdoutReader) {
            try {
                stdoutReader.close();
            } catch (IOException e) {
            }
        }
        if (null != stderrReader) {
            try {
                stderrReader.close();
            } catch (IOException e) {
            }
        }
    }
    // Was the command executed successfully
    if ((0 != exitStatus || 0 < errResult.length()) && 0 == result.length()) {
        if (0 < errResult.length()) {
            IProblem problem;
            problem = ReportingPlugin.getReportingService().getProblem(IBatchProblems.COMMAND_FAILED, errResult, null, Activator.PLUGIN_ID);
            throw new ProblemException(problem);
        }
        IProblem problem;
        problem = ReportingPlugin.getReportingService().getProblem(IBatchProblems.COMMAND_FAILED, null, null, Activator.PLUGIN_ID);
        throw new ProblemException(problem);
    }
    // If no output
    if (0 == result.length())
        result = null;
    return result;
}
Example 65
Project: org.eclipse.koneki.ldt-master  File: SshProcess.java View source code
/**
	 * try to kill the process with the PID equal to the value of the .PID file contained in pidContainerFolder
	 */
public static void killProcess(Session session, String pidContainerFolder) throws DebugException {
    try {
        // create a new channel
        //$NON-NLS-1$
        Channel channel = session.openChannel("exec");
        if (!(channel instanceof ChannelExec))
            throw new //$NON-NLS-1$
            JSchException(//$NON-NLS-1$
            "Unable to create exec channel");
        ChannelExec killChannel = (ChannelExec) channel;
        // create kill command
        String killCommand = createKillCommand(pidContainerFolder);
        killChannel.setCommand(killCommand);
        // execute command
        killChannel.connect();
        // wait the end of command execution
        int // in ms
        timeout = // in ms
        5000;
        int // in ms
        period = // in ms
        100;
        // counter
        int i = 0;
        while (!channel.isClosed() && i * period < timeout) {
            try {
                Thread.sleep(period);
            // CHECKSTYLE:OFF
            } catch (InterruptedException e) {
            } finally {
                i++;
            }
        }
    // CHECKSTYLE:OFF
    } catch (Exception e) {
        throw new DebugException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "An exception occurred when trying to stop the application.", e));
    }
}
Example 66
Project: SecureShareLib-master  File: SSHSiteController.java View source code
//        public static boolean scpTo(String filePath, String target, final String password, SiteController controller) {
public static boolean scpTo(Context context, String filePath, String username, final String password, String host, String remoteFile, SiteController controller, boolean useTor, Context mContext) {
    //            if (arg.length != 2) {
    //                System.err.println("usage: java ScpTo file1 user@remotehost:file2");
    //                System.exit(-1);
    //            }
    FileInputStream fis = null;
    try {
        //                String user = target.substring(0, target.indexOf('@'));
        //                target = target.substring(target.indexOf('@') + 1);
        //                String host = target.substring(0, target.indexOf(':'));
        //                String remoteFile = target.substring(target.indexOf(':') + 1);
        JSch jsch = new JSch();
        Session session = jsch.getSession(username, host, 22);
        // FIXME disabling host ssh checking for now  
        session.setConfig("StrictHostKeyChecking", "no");
        if (torCheck(useTor, mContext)) {
            session.setProxy(new ProxySOCKS4(ORBOT_HOST, ORBOT_SOCKS_PORT));
        }
        // username and password will be given via UserInfo interface.
        UserInfo ui = new UserInfo() {

            @Override
            public String getPassphrase() {
                // TODO Auto-generated method stub
                return password;
            }

            @Override
            public String getPassword() {
                // TODO Auto-generated method stub
                return password;
            }

            @Override
            public boolean promptPassphrase(String arg0) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean promptPassword(String arg0) {
                // TODO Auto-generated method stub
                return true;
            }

            @Override
            public boolean promptYesNo(String arg0) {
                // TODO Auto-generated method stub
                return true;
            }

            @Override
            public void showMessage(String arg0) {
            // TODO Auto-generated method stub
            }
        };
        //new MyUserInfo();
        session.setUserInfo(ui);
        session.connect();
        boolean ptimestamp = true;
        // exec 'scp -t rfile' remotely
        String command = "scp " + (ptimestamp ? "-p" : "") + " -t " + 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();
        if (checkAck(in) != 0) {
            // FIXME report the error
            return false;
        }
        File _lfile = new File(filePath);
        if (ptimestamp) {
            command = "T " + (_lfile.lastModified() / 1000) + " 0";
            // The access time should be sent here,
            // but it is not accessible with JavaAPI ;-<
            command += (" " + (_lfile.lastModified() / 1000) + " 0\n");
            out.write(command.getBytes());
            out.flush();
            if (checkAck(in) != 0) {
                // FIXME report the error
                return false;
            }
        }
        // send "C0644 filesize filename", where filename should not
        // include '/'
        long filesize = _lfile.length();
        command = "C0644 " + filesize + " ";
        if (filePath.lastIndexOf('/') > 0) {
            command += filePath.substring(filePath.lastIndexOf('/') + 1);
        } else {
            command += filePath;
        }
        command += "\n";
        out.write(command.getBytes());
        out.flush();
        if (checkAck(in) != 0) {
            // FIXME report the error
            return false;
        }
        // send a content of lfile
        fis = new FileInputStream(filePath);
        byte[] buf = new byte[1024];
        int bytesTransfered = 0;
        float progress = 0;
        int lastProgressRounded = -1;
        int progressRounded = 0;
        while (true) {
            int len = fis.read(buf, 0, buf.length);
            if (len <= 0) {
                break;
            }
            bytesTransfered += len;
            progress = ((float) bytesTransfered) / ((float) _lfile.length());
            // rate limit the progress to single percent
            progressRounded = Math.round(progress * 100);
            if (progressRounded != lastProgressRounded) {
                controller.jobProgress(progress, context.getString(R.string.ssh_upload_in_progress));
            }
            lastProgressRounded = progressRounded;
            // out.flush();
            out.write(buf, 0, len);
        }
        fis.close();
        fis = null;
        // send '\0'
        buf[0] = 0;
        out.write(buf, 0, 1);
        out.flush();
        if (checkAck(in) != 0) {
            // FIXME report the error
            return false;
        }
        out.close();
        channel.disconnect();
        session.disconnect();
        return true;
    } catch (Exception e) {
        System.out.println(e);
        try {
            if (fis != null)
                fis.close();
        } catch (Exception ee) {
        }
    }
    return false;
}
Example 67
Project: vco-powershel-plugin-master  File: SSH3Session.java View source code
public int getFile(String remoteFile, String localFile) {
    int result = 0;
    FileOutputStream fos = null;
    Channel channel = null;
    if (remoteFile == null) {
        throw new NullPointerException("Remote file cannot be 'null'");
    }
    if (localFile == null) {
        throw new NullPointerException("Local file cannot be 'null'");
    }
    // check if authorized to write the file
    File dir;
    if (new File(localFile).isDirectory()) {
        dir = new File(localFile);
    } else {
        dir = new File(localFile).getParentFile();
    }
    if (FileHandlerAccessRightsFactory.getDefaultFileHandlerAccessRights().hasRights(dir, FileHandlerAccessRights.Rights.write) == false) {
        throw new RuntimeException("Permission denied on directory '" + dir.getAbsolutePath() + "' , write not allowed");
    }
    try {
        String prefix = null;
        if (new File(localFile).isDirectory()) {
            prefix = localFile + File.separator;
        }
        Session session = getSession();
        // exec 'scp -f rfile' remotely
        String command = "scp -f " + remoteFile;
        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();
        while (true) {
            int c = checkAck(in);
            if (c != 'C') {
                result = 0;
                break;
            }
            // read '0644 '
            in.read(buf, 0, 5);
            long filesize = 0L;
            while (true) {
                if (in.read(buf, 0, 1) < 0) {
                    // error
                    break;
                }
                if (buf[0] == ' ')
                    break;
                filesize = filesize * 10L + (long) (buf[0] - '0');
            }
            String file = null;
            for (int i = 0; ; i++) {
                in.read(buf, i, 1);
                if (buf[i] == (byte) 0x0a) {
                    file = new String(buf, 0, i);
                    break;
                }
            }
            // System.out.println("filesize="+filesize+", file="+file);
            // send '\0'
            buf[0] = 0;
            out.write(buf, 0, 1);
            out.flush();
            // read a content of lfile
            fos = new FileOutputStream(prefix == null ? localFile : prefix + file);
            int foo;
            while (true) {
                if (buf.length < filesize)
                    foo = buf.length;
                else
                    foo = (int) filesize;
                foo = in.read(buf, 0, foo);
                if (foo < 0) {
                    // error
                    break;
                }
                fos.write(buf, 0, foo);
                filesize -= foo;
                if (filesize == 0L)
                    break;
            }
            fos.close();
            fos = null;
            int ret = checkAck(in);
            if (ret != 0) {
                return ret;
            }
            // send '\0'
            buf[0] = 0;
            out.write(buf, 0, 1);
            out.flush();
        }
    } catch (Exception e) {
        m_error = e.getMessage();
        result = -1;
    } finally {
        try {
            if (channel != null) {
                channel.disconnect();
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        try {
            if (fos != null) {
                fos.close();
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    // disconnect();
    }
    return result;
}
Example 68
Project: yacy_search_server-master  File: yacySeedUploadScp.java View source code
public static String put(final String host, final int port, final File localFile, final String remoteName, final String account, final String password) throws Exception {
    Session session = null;
    try {
        // Creating a new secure channel object
        final JSch jsch = new JSch();
        // setting hostname, username, userpassword
        session = jsch.getSession(account, host, port);
        session.setPassword(password);
        /*
             * Setting the StrictHostKeyChecking to ignore unknown
             * hosts because of a missing known_hosts file ...
             */
        final java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        /*
             * we need this user interaction interface to support
             * the interactive-keyboard mode
             */
        final UserInfo ui = new SchUserInfo(password);
        session.setUserInfo(ui);
        // trying to connect ...
        session.connect();
        String command = "scp -p -t " + remoteName;
        final Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        // get I/O streams for remote scp
        final OutputStream out = channel.getOutputStream();
        final InputStream in = channel.getInputStream();
        channel.connect();
        checkAck(in);
        // send "C0644 filesize filename", where filename should not include '/'
        final int filesize = (int) (localFile).length();
        command = "C0644 " + filesize + " ";
        if (localFile.toString().lastIndexOf('/') > 0) {
            command += localFile.toString().substring(localFile.toString().lastIndexOf('/') + 1);
        } else {
            command += localFile.toString();
        }
        command += "\n";
        out.write(UTF8.getBytes(command));
        out.flush();
        checkAck(in);
        // send a content of lfile
        final byte[] buf = new byte[1024];
        BufferedInputStream bufferedIn = null;
        try {
            bufferedIn = new BufferedInputStream(new FileInputStream(localFile));
            while (true) {
                final int len = bufferedIn.read(buf, 0, buf.length);
                if (len <= 0)
                    break;
                out.write(buf, 0, len);
                out.flush();
            }
        } finally {
            if (bufferedIn != null)
                try {
                    bufferedIn.close();
                } catch (final Exception e) {
                }
        }
        // send '\0'
        buf[0] = 0;
        out.write(buf, 0, 1);
        out.flush();
        checkAck(in);
        return "SCP: File uploaded successfully.";
    } catch (final Exception e) {
        throw new Exception("SCP: File uploading failed: " + e.getMessage());
    } finally {
        if ((session != null) && (session.isConnected()))
            session.disconnect();
    }
}
Example 69
Project: egit-freenet-master  File: TransportSftp.java View source code
ChannelSftp newSftp() throws TransportException {
    initSession();
    final int tms = getTimeout() > 0 ? getTimeout() * 1000 : 0;
    try {
        final Channel channel = sock.openChannel("sftp");
        channel.connect(tms);
        return (ChannelSftp) channel;
    } catch (JSchException je) {
        throw new TransportException(uri, je.getMessage(), je);
    }
}
Example 70
Project: gerrit-events-master  File: SshConnectionImpl.java View source code
/**
        * Execute an ssh command on the server.
        * After the command is sent the used channel is disconnected.
        *
        * @param command the command to execute.
        * @return a String containing the output from the command.
         * @throws SshException if so.
         */
@Override
public synchronized String executeCommand(String command) throws SshException {
    if (!isConnected()) {
        throw new IllegalStateException("Not connected!");
    }
    Channel channel = null;
    try {
        logger.debug("Opening channel");
        channel = connectSession.openChannel(CMD_EXEC);
        ((ChannelExec) channel).setCommand(command);
        ByteArrayOutputStream errOut = new ByteArrayOutputStream();
        channel.setExtOutputStream(errOut);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(channel.getInputStream()));
        logger.debug("connecting channel.");
        channel.connect();
        // Seems like Gerrit does not like when you disconnect directly after the command has been sent.
        // For instance, we have seen effects of mails not being sent out. This is the reason for
        // receiving all the incoming data.
        String incomingLine = null;
        StringBuilder commandOutput = new StringBuilder();
        while ((incomingLine = bufferedReader.readLine()) != null) {
            commandOutput.append(incomingLine);
            commandOutput.append('\n');
            logger.trace("Incoming line: {}", incomingLine);
        }
        logger.trace("Closing reader.");
        bufferedReader.close();
        // Exit code is only available if channel is closed, so wait a bit for it.
        // Channel.disconnect(), however, must not have been called yet.
        // See http://stackoverflow.com/questions/3154940/jsch-error-return-codes-not-consistent.
        waitForChannelClosure(channel, CLOSURE_WAIT_TIMEOUT);
        int exitCode = channel.getExitStatus();
        if (exitCode > 0) {
            String error = errOut.toString();
            if (error != null && error.trim().length() > 0) {
                throw new SshException(error.trim() + " (" + String.valueOf(exitCode) + ")");
            } else {
                throw new SshException(String.valueOf(exitCode));
            }
        }
        return commandOutput.toString();
    } catch (SshException ex) {
        throw ex;
    } catch (JSchException ex) {
        throw new SshException(ex);
    } catch (IOException ex) {
        throw new SshException(ex);
    } finally {
        if (channel != null) {
            logger.trace("disconnecting channel.");
            channel.disconnect();
        }
    }
}
Example 71
Project: jgit-master  File: TransportSftp.java View source code
ChannelSftp newSftp() throws TransportException {
    final int tms = getTimeout() > 0 ? getTimeout() * 1000 : 0;
    try {
        // @TODO: Fix so that this operation is generic and casting to
        // JschSession is no longer necessary.
        final Channel channel = ((JschSession) getSession()).getSftpChannel();
        channel.connect(tms);
        return (ChannelSftp) channel;
    } catch (JSchException je) {
        throw new TransportException(uri, je.getMessage(), je);
    }
}
Example 72
Project: openDBcopy-master  File: ScpTo.java View source code
/**
     * DOCUMENT ME!
     *
     * @param logger DOCUMENT ME!
     * @param host DOCUMENT ME!
     * @param port DOCUMENT ME!
     * @param userName DOCUMENT ME!
     * @param password DOCUMENT ME!
     * @param sourceFile DOCUMENT ME!
     * @param remotePath DOCUMENT ME!
     *
     * @throws IOException DOCUMENT ME!
     * @throws JSchException DOCUMENT ME!
     * @throws PluginException DOCUMENT ME!
     */
private static void secureCopyFile(Logger logger, String host, int port, String userName, String password, File sourceFile, String remotePath) throws IOException, JSchException, PluginException {
    JSch jsch = new JSch();
    Session session = jsch.getSession(userName, host, port);
    session.setHost(host);
    session.setUserName(userName);
    session.setPassword(password);
    session.connect();
    // exec 'scp -t rfile' remotely
    String command = "scp -t " + remotePath;
    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[] tmp = new byte[1];
    if (checkAck(in) != 0) {
        throw new PluginException("Acknowledgment error");
    }
    // send "C0644 filesize filename", where filename should not include '/'
    int filesize = (int) (sourceFile).length();
    command = "C0644 " + filesize + " ";
    command += sourceFile.getName();
    command += "\n";
    out.write(command.getBytes());
    out.flush();
    if (checkAck(in) != 0) {
        throw new PluginException("Acknowledgment error");
    }
    // send a content of sourceFile
    FileInputStream fis = new FileInputStream(sourceFile);
    byte[] buf = new byte[1024];
    while (true) {
        int len = fis.read(buf, 0, buf.length);
        if (len <= 0) {
            break;
        }
        out.write(buf, 0, len);
        out.flush();
    }
    // send '\0'
    buf[0] = 0;
    out.write(buf, 0, 1);
    out.flush();
    if (checkAck(in) != 0) {
        throw new PluginException("Acknowledgment error");
    }
    logger.info("copied local file " + sourceFile.getAbsolutePath() + " to " + host + remotePath);
}
Example 73
Project: pentaho-kettle-master  File: SFTPClient.java View source code
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);
    }
}
Example 74
Project: plugin-undo-master  File: TransportSftp.java View source code
ChannelSftp newSftp() throws TransportException {
    final int tms = getTimeout() > 0 ? getTimeout() * 1000 : 0;
    try {
        // @TODO: Fix so that this operation is generic and casting to
        // JschSession is no longer necessary.
        final com.jcraft.jsch.Channel channel = ((JschSession) getSession()).getSftpChannel();
        channel.connect(tms);
        return (ChannelSftp) channel;
    } catch (JSchException je) {
        throw new TransportException(uri, je.getMessage(), je);
    }
}
Example 75
Project: remote-console-master  File: SshRemoteConsole.java View source code
/**
     * Executes a command on the remote server, via a ssh channel.
     *
     * Captures stdout in the result, while stderr is only logged
     *
     * @param command The unix command to execute
     * @param failOnExitNotZero throw an exception if the unix command does not
     * return zero (0)
     * @param disconnectAfterMillis disconnect after a periods (this is usefull
     * when starting deamons)
     * @param disconnectAfterContent disconnect after this string has appeard
     * in output (this is usefull when starting deamons), can be used in
     * combination
     * @return a CommandResult entity with the output and errorcode.
     * @throws IOException on communication errors
     * @throws IllegalStateException if the exit code check is on
     * @todo Cleanup and split up into several methods
     */
public CommandResult executeCommandResult(String command, boolean failOnExitNotZero, long disconnectAfterMillis, String disconnectAfterContent, Writer liveOutput) throws IOException {
    try {
        CommandResult result = new CommandResult();
        SshRemoteConsole.log.debug("Executing > " + command);
        boolean connect = session == null || !session.isConnected();
        if (connect) {
            connect();
        }
        try {
            // shell
            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);
            if (enablePty) {
                ((ChannelExec) channel).setPty(true);
            }
            InputStream error = ((ChannelExec) channel).getErrStream();
            // channel.setOutputStream(System.err);
            InputStream in = channel.getInputStream();
            channel.connect();
            long start = System.currentTimeMillis();
            boolean contentReached = true;
            if (disconnectAfterContent != null && !disconnectAfterContent.equals("")) {
                contentReached = false;
            }
            StringBuilder output = new StringBuilder();
            StringBuilder errorOutput = new StringBuilder();
            try {
                byte[] inTmp = new byte[1024];
                byte[] errorTmp = new byte[1024];
                while (true) {
                    while (in.available() > 0) {
                        int i = in.read(inTmp, 0, 1024);
                        if (i < 0) {
                            break;
                        }
                        output(new String(inTmp, 0, i), liveOutput, output);
                        log.trace(new String(inTmp, 0, i));
                    }
                    while (error.available() > 0) {
                        int i = error.read(errorTmp, 0, 1024);
                        if (i < 0) {
                            break;
                        }
                        if (output.toString().length() < MAX_CONTENT_LENGTH) {
                            errorOutput.append(new String(errorTmp, 0, i));
                        }
                        log.debug("ERROR: " + new String(errorTmp, 0, i));
                    }
                    if (channel.isClosed()) {
                        result.setExitCode(channel.getExitStatus());
                        if (failOnExitNotZero && channel.getExitStatus() != 0) {
                            log.debug("exit-status: " + channel.getExitStatus());
                            throw new IllegalStateException("Exitstatus was: " + channel.getExitStatus() + " output: " + output.toString() + " error-output: " + errorOutput.toString());
                        }
                        break;
                    }
                    if (disconnectAfterMillis > 0 && contentReached) {
                        long now = System.currentTimeMillis();
                        if (now - start > disconnectAfterMillis) {
                            log.trace("exiting before command is finished after: " + ((now - start) / 1000) + " seconds.");
                            break;
                        }
                    }
                    // TODO fix possible flaw that clashes with MAX_CONTENT_LENGTH
                    if (!contentReached && (output.toString().contains(disconnectAfterContent) || errorOutput.toString().contains(disconnectAfterContent))) {
                        contentReached = true;
                        start = System.currentTimeMillis();
                        if (disconnectAfterMillis == 0) {
                            break;
                        }
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ex) {
                        log.warn("Interrupted in sleep", ex);
                    }
                }
            } finally {
                channel.disconnect();
            }
            result.setOutput(output.toString());
            result.setErrorOutput(errorOutput.toString());
        } finally {
            if (connect) {
                disconnect();
            }
        }
        return result;
    } catch (JSchException ex) {
        IOException ioe = new IOException(ex.getMessage());
        ioe.initCause(ex);
        throw ioe;
    }
}
Example 76
Project: tools_gerrit-master  File: PushReplication.java View source code
private void replicateProject(final URIish replicateURI, final String head) {
    SshSessionFactory sshFactory = SshSessionFactory.getInstance();
    Session sshSession;
    String projectPath = QuotedString.BOURNE.quote(replicateURI.getPath());
    if (!usingSSH(replicateURI)) {
        log.warn("Cannot create new project on remote site since the connection " + "method is not SSH: " + replicateURI.toString());
        return;
    }
    OutputStream errStream = createErrStream();
    String cmd = "mkdir -p " + projectPath + "&& cd " + projectPath + "&& git init --bare" + "&& git symbolic-ref HEAD " + QuotedString.BOURNE.quote(head);
    try {
        sshSession = sshFactory.getSession(replicateURI.getUser(), replicateURI.getPass(), replicateURI.getHost(), replicateURI.getPort(), FS.DETECTED);
        sshSession.connect();
        Channel channel = sshSession.openChannel("exec");
        ((ChannelExec) channel).setCommand(cmd);
        channel.setInputStream(null);
        ((ChannelExec) channel).setErrStream(errStream);
        channel.connect();
        while (!channel.isClosed()) {
            try {
                final int delay = 50;
                Thread.sleep(delay);
            } catch (InterruptedException e) {
            }
        }
        channel.disconnect();
        sshSession.disconnect();
    } catch (JSchException e) {
        log.error("Communication error when trying to replicate to: " + replicateURI.toString() + "\n" + "Error reported: " + e.getMessage() + "\n" + "Error in communication: " + errStream.toString());
    }
}
Example 77
Project: totalads-master  File: SSHConnector.java View source code
/**
     * Executes a command
     *
     * @param command
     *            Command to execute
     *
     */
private void executeCommand(String command) throws TotalADSNetException {
    Channel channel = null;
    String msg = null;
    try {
        //$NON-NLS-1$
        channel = fSession.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        ((ChannelExec) channel).setErrStream(System.err);
        try (InputStream in = channel.getInputStream();
            OutputStream out = channel.getOutputStream()) {
            channel.connect();
            displayStream(in, channel);
        }
    } catch (IOException e) {
        fOutStream.addOutputEvent(Messages.SSHConnector_Error + e.getMessage());
        fOutStream.addNewLine();
        msg = e.getMessage();
    } catch (JSchException e) {
        fOutStream.addOutputEvent(Messages.SSHConnector_Error + e.getMessage());
        fOutStream.addNewLine();
        msg = e.getMessage();
    } finally {
        if (channel != null) {
            channel.disconnect();
        }
    }
    if (msg != null) {
        // Don't continue further
        throw new TotalADSNetException(msg);
    }
}
Example 78
Project: voltdb-master  File: SSHTools.java View source code
/*
     * The code from here to the end of the file is code that integrates with an external
     * SSH library (JSCH, http://www.jcraft.com/jsch/).  If you wish to replaces this
     * library, these are the methods that need to be re-worked.
     */
public String cmdSSH(String user, String password, String key, String host, String command) {
    StringBuilder result = new StringBuilder(2048);
    try {
        JSch jsch = new JSch();
        // Set the private key
        if (null != key)
            jsch.addIdentity(key);
        Session session = jsch.getSession(user, host, 22);
        session.setTimeout(5000);
        // To avoid the UnknownHostKey issue
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        if (password != null && !password.trim().isEmpty()) {
            session.setPassword(password);
        }
        session.connect();
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        // Direct stderr output of command
        InputStream err = ((ChannelExec) channel).getErrStream();
        InputStreamReader errStrRdr = new InputStreamReader(err, "UTF-8");
        Reader errStrBufRdr = new BufferedReader(errStrRdr);
        // Direct stdout output of command
        InputStream out = channel.getInputStream();
        InputStreamReader outStrRdr = new InputStreamReader(out, "UTF-8");
        Reader outStrBufRdr = new BufferedReader(outStrRdr);
        StringBuffer stdout = new StringBuffer();
        StringBuffer stderr = new StringBuffer();
        // timeout after 5 seconds
        channel.connect(5000);
        while (true) {
            if (channel.isClosed()) {
                break;
            }
            // Read from both streams here so that they are not blocked,
            // if they are blocked because the buffer is full, channel.isClosed() will never
            // be true.
            int ch;
            while (outStrBufRdr.ready() && (ch = outStrBufRdr.read()) > -1) {
                stdout.append((char) ch);
            }
            while (errStrBufRdr.ready() && (ch = errStrBufRdr.read()) > -1) {
                stderr.append((char) ch);
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException ie) {
            }
        }
        // In case there's still some more stuff in the buffers, read them
        int ch;
        while ((ch = outStrBufRdr.read()) > -1) {
            stdout.append((char) ch);
        }
        while ((ch = errStrBufRdr.read()) > -1) {
            stderr.append((char) ch);
        }
        // After the command is executed, gather the results (both stdin and stderr).
        result.append(stdout.toString());
        result.append(stderr.toString());
        // Shutdown the connection
        channel.disconnect();
        session.disconnect();
    } catch (Throwable e) {
        e.printStackTrace();
    }
    return result.toString();
}
Example 79
Project: ant-ivy-master  File: Scp.java View source code
private void sendFile(Channel channel, String localFile, String remoteName, String mode) throws IOException, RemoteScpException {
    byte[] buffer = new byte[BUFFER_SIZE];
    OutputStream os = new BufferedOutputStream(channel.getOutputStream(), SEND_FILE_BUFFER_LENGTH);
    InputStream is = new BufferedInputStream(channel.getInputStream(), SEND_BYTES_BUFFER_LENGTH);
    try {
        if (channel.isConnected()) {
            channel.start();
        } else {
            channel.connect();
        }
    } catch (JSchException e1) {
        throw (IOException) new IOException("Channel connection problems").initCause(e1);
    }
    readResponse(is);
    File f = new File(localFile);
    long remain = f.length();
    String cMode = mode;
    if (cMode == null) {
        cMode = "0600";
    }
    String cline = "C" + cMode + " " + remain + " " + remoteName + "\n";
    os.write(cline.getBytes());
    os.flush();
    readResponse(is);
    FileInputStream fis = null;
    try {
        fis = new FileInputStream(f);
        while (remain > 0) {
            int trans;
            if (remain > buffer.length) {
                trans = buffer.length;
            } else {
                trans = (int) remain;
            }
            if (fis.read(buffer, 0, trans) != trans) {
                throw new IOException("Cannot read enough from local file " + localFile);
            }
            os.write(buffer, 0, trans);
            remain -= trans;
        }
        fis.close();
    } catch (IOException e) {
        if (fis != null) {
            fis.close();
        }
        throw (e);
    }
    os.write(0);
    os.flush();
    readResponse(is);
    os.write("E\n".getBytes());
    os.flush();
}
Example 80
Project: camel-jsch-master  File: ScpOperations.java View source code
@SuppressWarnings("unchecked")
@Override
public boolean retrieveFile(String name, Exchange exchange) throws GenericFileOperationFailedException {
    OutputStream outputStream = null;
    RemoteFile<ScpFile> remoteFile = exchange.getIn().getBody(RemoteFile.class);
    try {
        // exec 'scp -f rfile' remotely
        String command = "scp -f " + remoteFile.getAbsoluteFilePath();
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        // get I/O streams for remote scp
        OutputStream out = channel.getOutputStream();
        InputStream inputStream = channel.getInputStream();
        channel.connect();
        byte[] buf = new byte[1024];
        // send '\0'
        buf[0] = 0;
        out.write(buf, 0, 1);
        out.flush();
        while (true) {
            int c = checkAck(inputStream);
            if (c != 'C') {
                break;
            }
            // read '0644 '
            inputStream.read(buf, 0, 5);
            long filesize = 0L;
            while (true) {
                if (inputStream.read(buf, 0, 1) < 0) {
                    // error
                    break;
                }
                if (buf[0] == ' ') {
                    break;
                }
                filesize = filesize * 10L + buf[0] - '0';
            }
            for (int i = 0; ; i++) {
                inputStream.read(buf, i, 1);
                if (buf[i] == (byte) 0x0a) {
                    break;
                }
            }
            // send '\0'
            buf[0] = 0;
            out.write(buf, 0, 1);
            out.flush();
            // read content
            outputStream = new ByteArrayOutputStream();
            int foo;
            while (true) {
                if (buf.length < filesize) {
                    foo = buf.length;
                } else {
                    foo = (int) filesize;
                }
                foo = inputStream.read(buf, 0, foo);
                if (foo < 0) {
                    // error
                    break;
                }
                outputStream.write(buf, 0, foo);
                filesize -= foo;
                if (filesize == 0L) {
                    break;
                }
            }
            if (checkAck(inputStream) != 0) {
                LOG.warn("Issues while retrieving the file. Will try again in the next poll.");
                return false;
            }
            // send '\0'
            buf[0] = 0;
            out.write(buf, 0, 1);
            out.flush();
            exchange.getIn().setBody(outputStream);
            return true;
        }
    } catch (Exception e) {
        LOG.warn("Issues while retrieving the file. Will try again in the next poll. Exception: ", e);
    }
    return false;
}
Example 81
Project: jopenray-master  File: SshAdapter.java View source code
public void start(ThinClient thinClient, Session session) {
    this.client = thinClient;
    int port = 22;
    try {
        UserInfo ui = new UserInfo() {

            @Override
            public String getPassphrase() {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public String getPassword() {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public boolean promptPassphrase(String message) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean promptPassword(String message) {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean promptYesNo(String message) {
                return true;
            }

            @Override
            public void showMessage(String message) {
            // TODO Auto-generated method stub
            }
        };
        jschsession = JSchSession.getSession(session.getLogin(), session.getPassword(), session.getServer(), port, ui, proxy);
        java.util.Properties config = new java.util.Properties();
        config.put("compression.s2c", "none");
        config.put("compression.c2s", "none");
        jschsession.getSession().setConfig(config);
        jschsession.getSession().rekey();
        Channel channel = null;
        OutputStream out = null;
        InputStream in = null;
        channel = jschsession.getSession().openChannel("shell");
        out = channel.getOutputStream();
        in = channel.getInputStream();
        channel.connect();
        final OutputStream fout = out;
        final InputStream fin = in;
        final Channel fchannel = channel;
        connection = new Connection() {

            public InputStream getInputStream() {
                return fin;
            }

            public OutputStream getOutputStream() {
                return fout;
            }

            public void requestResize(Term term) {
                if (fchannel instanceof ChannelShell) {
                    int c = term.getColumnCount();
                    int r = term.getRowCount();
                    ((ChannelShell) fchannel).setPtySize(c, r, c * term.getCharWidth(), r * term.getCharHeight());
                }
            }

            public void close() {
                fchannel.disconnect();
            }
        };
        setSize(thinClient.getScreenWidth(), thinClient.getScreenHeight());
        start(connection);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 82
Project: kraken-master  File: CoreScript.java View source code
private void scpFrom(String[] args) {
    // scp from
    FileOutputStream fos = null;
    try {
        String user = args[0].substring(0, args[0].indexOf('@'));
        args[0] = args[0].substring(args[0].indexOf('@') + 1);
        String host = args[0].substring(0, args[0].indexOf(':'));
        String rfile = args[0].substring(args[0].indexOf(':') + 1);
        String lfile = args[1];
        String prefix = null;
        if (new File(lfile).isDirectory()) {
            prefix = lfile + File.separator;
        }
        JSch jsch = new JSch();
        Session session = jsch.getSession(user, host, 22);
        session.setUserInfo(new MyUserInfo());
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();
        String command = "scp -f " + rfile;
        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();
        while (true) {
            int c = checkAck(in);
            if (c != 'C') {
                break;
            }
            // read '0644 '
            in.read(buf, 0, 5);
            long filesize = 0L;
            while (true) {
                if (in.read(buf, 0, 1) < 0) {
                    // error
                    break;
                }
                if (buf[0] == ' ')
                    break;
                filesize = filesize * 10L + (long) (buf[0] - '0');
            }
            String file = null;
            for (int i = 0; ; i++) {
                in.read(buf, i, 1);
                if (buf[i] == (byte) 0x0a) {
                    file = new String(buf, 0, i);
                    break;
                }
            }
            // send '\0'
            buf[0] = 0;
            out.write(buf, 0, 1);
            out.flush();
            // read a content of lfile
            fos = new FileOutputStream(prefix == null ? lfile : prefix + file);
            int foo;
            while (true) {
                if (buf.length < filesize)
                    foo = buf.length;
                else
                    foo = (int) filesize;
                foo = in.read(buf, 0, foo);
                if (foo < 0) {
                    // error
                    break;
                }
                fos.write(buf, 0, foo);
                filesize -= foo;
                if (filesize == 0L)
                    break;
            }
            fos.close();
            fos = null;
            if (checkAck(in) != 0) {
                throw new IllegalStateException();
            }
            // send '\0'
            buf[0] = 0;
            out.write(buf, 0, 1);
            out.flush();
        }
        session.disconnect();
    } catch (Exception e) {
        context.println(e.getMessage());
        try {
            if (fos != null)
                fos.close();
        } catch (Exception ee) {
        }
    }
}
Example 83
Project: mini-git-server-master  File: PushReplication.java View source code
private void replicateProject(final URIish replicateURI, final String head) {
    SshSessionFactory sshFactory = SshSessionFactory.getInstance();
    Session sshSession;
    String projectPath = QuotedString.BOURNE.quote(replicateURI.getPath());
    if (!usingSSH(replicateURI)) {
        log.warn("Cannot create new project on remote site since the connection " + "method is not SSH: " + replicateURI.toString());
        return;
    }
    OutputStream errStream = createErrStream();
    String cmd = "mkdir -p " + projectPath + "&& cd " + projectPath + "&& git init --bare" + "&& git symbolic-ref HEAD " + QuotedString.BOURNE.quote(head);
    try {
        sshSession = sshFactory.getSession(replicateURI.getUser(), replicateURI.getPass(), replicateURI.getHost(), replicateURI.getPort(), null, FS.DETECTED);
        sshSession.connect();
        Channel channel = sshSession.openChannel("exec");
        ((ChannelExec) channel).setCommand(cmd);
        channel.setInputStream(null);
        ((ChannelExec) channel).setErrStream(errStream);
        channel.connect();
        while (!channel.isClosed()) {
            try {
                final int delay = 50;
                Thread.sleep(delay);
            } catch (InterruptedException e) {
            }
        }
        channel.disconnect();
        sshSession.disconnect();
    } catch (JSchException e) {
        log.error("Communication error when trying to replicate to: " + replicateURI.toString() + "\n" + "Error reported: " + e.getMessage() + "\n" + "Error in communication: " + errStream.toString());
    }
}
Example 84
Project: pacifista-master  File: Remote.java View source code
public void send(InputStream fileIn, long fileSize, String remotePath, String remoteFileName, String mode) throws IOException {
    String command = "scp  -t " + remotePath;
    Channel channel = null;
    try {
        channel = this.session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        OutputStream out = channel.getOutputStream();
        InputStream in = channel.getInputStream();
        channel.connect();
        checkAck(in);
        mode = null == mode ? "C0644" : mode;
        command = mode + " " + fileSize + " ";
        command += remoteFileName;
        command += "\n";
        out.write(command.getBytes());
        out.flush();
        checkAck(in);
        IOUtil.copy(fileIn, out);
        fileIn.close();
        out.write(new byte[1]);
        out.flush();
        checkAck(in);
        out.close();
        channel.disconnect();
    } catch (JSchException e) {
        throw new IOException(e);
    } finally {
        if (channel != null) {
            channel.disconnect();
        }
    }
}
Example 85
Project: PTP-master  File: Connection.java View source code
/**
	 * Remove a channel from the pool, leaving the slot available for another
	 * channel.
	 * 
	 * @param channel
	 */
protected void releaseChannel(Channel channel) {
    /*
		 * The channel may or may not be in the connection pool, depending how
		 * it was created. Ant any case, always disconnect the channel.
		 */
    channel.disconnect();
    ConnectionSlot slot = channelToConnectioPool.remove(channel);
    if (slot != null) {
        slot.numberUsedChannels--;
    }
}
Example 86
Project: sof-master  File: SofManager.java View source code
public static boolean existOnHost(EnvironmentSession session, String path) {
    String output = "";
    String cmd = "if ls " + path + "; then echo 0; else echo -1; fi";
    //System.out.println("Start check "+path+ " "+cmd);
    try {
        Channel channel;
        channel = session.getSession().openChannel("exec");
        ((ChannelExec) channel).setCommand(cmd);
        InputStream in = channel.getInputStream();
        //((ChannelExec) channel).setErrStream(System.err);
        channel.connect();
        byte[] b = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(b, 0, 1024);
                if (i < 0)
                    break;
                output += new String(b, 0, i).trim();
            }
            if (channel.isClosed()) {
                if (in.available() > 0)
                    continue;
                break;
            }
        }
        channel.disconnect();
        return !output.contains("-1");
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}
Example 87
Project: SRDBS-master  File: Sftp.java View source code
public static int upload(String file, long fID, String rPath) {
    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    int ftpFileNo = 0;
    long fid = fID;
    long fsize;
    try {
        JSch jsch = new JSch();
        session = jsch.getSession(Global.c1UserName, Global.c1IPAddress, Global.c1Port);
        session.setPassword(Global.c1Password);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        channel = session.openChannel("sftp");
        channel.connect();
        channelSftp = (ChannelSftp) channel;
        channelSftp.mkdir(Global.c1Remotepath + "/" + rPath);
        channelSftp.cd(Global.c1Remotepath + "/" + rPath);
        fileCount = cloud1.size();
        for (int i = cloud1.size() - 1; i >= 0; i--) {
            ftpFileNo = cloud1.get(i);
            File f = new File(file + Split.createSuffix(ftpFileNo));
            backplogger.info("File name :" + f);
            FileInputStream F1 = new FileInputStream(f);
            // Isanka
            channelSftp.put(F1, f.getName(), new SystemOutProgressMonitor_new());
            //filename = "cloud1 :-" + f.getName() + "file no :-" + ftpFileNo + "byte count :-" + cloud1.get(i).byteValue() ;
            //   currentFileNunber = fileCount - cloud1.get(i) + 1;
            currentFileNunber = fileCount - cloud1.size() + 1;
            filename = "cloud1 ";
            filenametotal = "Uploaded Packets:- " + currentFileNunber + "/" + +fileCount;
            if (currentFileNunber > fileCount) {
                currentFileNunber = currentFileNunber - fileCount;
            }
            backplogger.info("IP : " + Global.c1IPAddress + ", " + Global.c1Port + ", " + Global.c1UserName + ", " + ", " + file + " upload to " + Global.c1Remotepath + "/" + rPath);
            backplogger.info("Send the file.");
            cloud1.remove(i);
            backplogger.info(cloud1);
            String temp[] = f.toString().split("\\\\");
            DbConnect dbconnect = new DbConnect();
            fsize = dbconnect.pSize(fid, f.getName());
            dbconnect.saveUploadSPFiles(fid, temp[temp.length - 1], rPath, 1);
            dbconnect.SaveCloud1(fid, temp[temp.length - 1], Global.c1Remotepath + "/" + rPath, fsize);
            F1.close();
        }
        channelSftp.disconnect();
        session.disconnect();
        // sending the message.
        sendUploadDetails(fid, Global.c1IPAddress, Global.c1MessagePort);
        return 0;
    } catch (Exception ex) {
        backplogger.error("Ftp upload error on IP : " + Global.c1IPAddress + ":" + Global.c1Port + " more details :" + ex);
        backplogger.info("Retring to upload");
        long startTime = System.currentTimeMillis();
        while ((System.currentTimeMillis() - startTime) < 30000) {
            if (count1 < 3) {
                boolean server = ping(Global.c1IPAddress, Global.c1Port);
                if (server == true) {
                    backplogger.info("upload again");
                    backplogger.info(count1);
                    count1++;
                    upload(file, fid, rPath);
                    break;
                }
            }
        }
        failUploadSave(fid, 1, cloud1, file, rPath);
        return 10;
    }
}
Example 88
Project: termd-master  File: KeyReExchangeTest.java View source code
@Test
public void testReExchangeFromJschClient() throws Exception {
    Assume.assumeTrue("DH Group Exchange not supported", SecurityUtils.isDHGroupExchangeSupported());
    setUp(0L, 0L, 0L);
    JSch.setConfig("kex", BuiltinDHFactories.Constants.DIFFIE_HELLMAN_GROUP_EXCHANGE_SHA1);
    JSch sch = new JSch();
    com.jcraft.jsch.Session s = sch.getSession(getCurrentTestName(), TEST_LOCALHOST, port);
    try {
        s.setUserInfo(new SimpleUserInfo(getCurrentTestName()));
        s.connect();
        com.jcraft.jsch.Channel c = s.openChannel(Channel.CHANNEL_SHELL);
        c.connect();
        try (OutputStream os = c.getOutputStream();
            InputStream is = c.getInputStream()) {
            String expected = "this is my command\n";
            byte[] bytes = expected.getBytes(StandardCharsets.UTF_8);
            byte[] data = new byte[bytes.length + Long.SIZE];
            for (int i = 1; i <= 10; i++) {
                os.write(bytes);
                os.flush();
                int len = is.read(data);
                String str = new String(data, 0, len);
                assertEquals("Mismatched data at iteration " + i, expected, str);
                outputDebugMessage("Request re-key #%d", i);
                s.rekey();
            }
        } finally {
            c.disconnect();
        }
    } finally {
        s.disconnect();
    }
}
Example 89
Project: vhm-master  File: SshConnectionCache.java View source code
private void cleanup() {
    if (channel == null) {
        return;
    }
    channel.disconnect();
    synchronized (cache) {
        Set<Channel> channels = channelMap.get(session);
        if (channels != null) {
            channels.remove(channel);
            if (channels.isEmpty() && !cache.containsValue(session)) {
                channelMap.remove(session);
                _log.fine("Disconnecting session during RemoteProcess cleanup for " + session.getUserName() + "@" + session.getHost());
                session.disconnect();
            }
        }
    }
    channel = null;
    if (stdin != null) {
        try {
            stdin.close();
        } catch (IOException e) {
        }
    }
    if (stdout != null) {
        try {
            stdout.close();
        } catch (IOException e) {
        }
    }
    if (stderr != null) {
        try {
            stderr.close();
        } catch (IOException e) {
        }
    }
}
Example 90
Project: WwDocker-master  File: Remote.java View source code
private static int execCommand(Session session, String command) throws JSchException {
    int exitCode = -1;
    Channel channel = session.openChannel("exec");
    ((ChannelExec) channel).setCommand(command);
    logger.trace("Remote exection of command: [".concat(session.getHost()).concat("]: ").concat(command));
    String fullOut = new String();
    try {
        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;
                fullOut = fullOut.concat(new String(tmp, 0, i));
                fullOut = Utils.logOutput(fullOut);
            }
            if (channel.isClosed()) {
                if (in.available() > 0)
                    continue;
                exitCode = channel.getExitStatus();
                Utils.logOutput(fullOut + System.lineSeparator());
                logger.info("Exit code: " + exitCode);
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception ee) {
            }
        }
    } catch (IOException e) {
        throw new JSchException("IOException during ssh action: " + command, e);
    }
    channel.disconnect();
    return exitCode;
}
Example 91
Project: openshift-java-client-master  File: ApplicationResource.java View source code
/**
	 *
	 * @param command
	 * @return
	 * @throws OpenShiftSSHOperationException
	 */
protected List<String> sshExecCmd(final String command, final SshStreams sshStream) throws OpenShiftSSHOperationException {
    final Session session = getSSHSession();
    if (session == null) {
        throw new OpenShiftSSHOperationException("No SSH session available for application ''{0}''", this.getName());
    }
    Channel channel = null;
    try {
        session.openChannel("exec");
        channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        channel.connect();
        return sshStream.getLines(channel);
    } catch (JSchException e) {
        throw new OpenShiftSSHOperationException(e, "Failed to execute remote ssh command \"{0}\"", this.getName());
    } catch (IOException e) {
        throw new OpenShiftSSHOperationException(e, "Failed to execute remote ssh command \"{0}\"", this.getName());
    } finally {
        if (channel != null && channel.isConnected()) {
            channel.disconnect();
        }
    }
}
Example 92
Project: ecore-master  File: DockerContainerManager.java View source code
public void connect(final String host, final String privateKey, final String command) {
    try {
        Session session = null;
        final String user = "docker";
        final File tempDir = this.createTempDir("knowHosts");
        String _plus = (tempDir + "/hosts");
        final File test = new File(_plus);
        boolean _exists = test.exists();
        boolean _not = (!_exists);
        if (_not) {
            test.createNewFile();
        }
        try {
            final JSch jsc = new JSch();
            jsc.setKnownHosts("/dev/null");
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            jsc.setKnownHosts("/dev/null");
            jsc.addIdentity(privateKey);
            DockerContainerManager.LOGGER.info("Identity added ..");
            final String exCommand = ((("sudo sh -c " + "\"") + command) + "\"");
            DockerContainerManager.LOGGER.info(exCommand);
            Session _session = jsc.getSession(user, host, 22);
            session = _session;
            DockerContainerManager.LOGGER.info("Session created ..");
            session.setConfig(config);
            DockerContainerManager.LOGGER.info("Session config ..");
            session.connect();
            DockerContainerManager.LOGGER.info("Session connected ..");
            final Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(exCommand);
            ((ChannelExec) channel).setErrStream(System.err);
            channel.connect();
        } catch (final Throwable _t) {
            if (_t instanceof JSchException) {
                final JSchException e = (JSchException) _t;
                String _string = e.toString();
                DockerContainerManager.LOGGER.info(_string);
            } else {
                throw Exceptions.sneakyThrow(_t);
            }
        }
        session.disconnect();
    } catch (Throwable _e) {
        throw Exceptions.sneakyThrow(_e);
    }
}
Example 93
Project: EC2Box-master  File: SchSession.java View source code
public Channel getChannel() {
    return channel;
}
Example 94
Project: KeyBox-master  File: SchSession.java View source code
public Channel getChannel() {
    return channel;
}
Example 95
Project: quahive-master  File: SftpTestFilesDownloader.java View source code
private ChannelSftp sftpConnection() throws JSchException {
    // MyUserInfo implements
    UserInfo ui = new NoGUIUserInfo();
    session.setUserInfo(ui);
    session.connect();
    Channel channel = session.openChannel("sftp");
    ChannelSftp sftp = (ChannelSftp) channel;
    sftp.connect();
    return sftp;
}
Example 96
Project: extension-aws-master  File: SftpUtil.java View source code
protected Channel openSftpChannel() throws JSchException {
    if (this.channel == null) {
        this.channel = openSession().openChannel("sftp");
        channel.connect();
        ChannelSftp c = (ChannelSftp) channel;
    }
    return this.channel;
}
Example 97
Project: gobblin-master  File: SftpLightWeightFileSystem.java View source code
/**
   * Null safe disconnect
   */
private static void safeDisconnect(Channel channel) {
    if (channel != null) {
        channel.disconnect();
    }
}
Example 98
Project: sshwrap-master  File: SSHConnection.java View source code
public Channel openChannel(final ChannelType type) throws SSHWrapException {
    checkConnected();
    try {
        final Channel channel = session.openChannel(type.channelName());
        return channel;
    } catch (final JSchException e) {
        throw new SSHWrapException("Failed to open channel: %s\nReason: %s", e, type, e.getMessage());
    }
}