Package com.jcraft.jsch

Examples of com.jcraft.jsch.Session


            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();
        }
    }
View Full Code Here


        JSch jsch = new JSch();
        try {
            LOG.debug("Using '{}' for known hosts.", knownHostsFile);
            jsch.setKnownHosts(knownHostsFile);
            Session s = jsch.getSession("admin", "localhost", getPort());
            s.setConfig("StrictHostKeyChecking""ask");

            // TODO: by the current jsch (0.1.50) setting "HashKnownHosts" to "no" is a workaround
            // to make the tests run green, see also http://sourceforge.net/p/jsch/bugs/63/
            s.setConfig("HashKnownHosts""no");
            s.setUserInfo(new UserInfo() {
                @Override
                public String getPassphrase() {
                    return null;
                }
                @Override
                public String getPassword() {
                    return "admin";
                }
                @Override
                public boolean promptPassword(String message) {
                    return true;
                }
                @Override
                public boolean promptPassphrase(String message) {
                    return false;
                }
                @Override
                public boolean promptYesNo(String message) {
                    // accept host authenticity
                    return true;
                }
                @Override
                public void showMessage(String message) {
                }
            });
            // in the process of connecting, "[localhost]:<port>" is added to the knownHostsFile
            s.connect();
            s.disconnect();
        } catch (JSchException e) {
            LOG.info("Could not add [localhost] to known hosts", e);
        }
    }
View Full Code Here

        if (sftpConfig.getKnownHosts() != null) {
            LOG.debug("Using knownhosts information from byte array");
            jsch.setKnownHosts(new ByteArrayInputStream(sftpConfig.getKnownHosts()));
        }

        final Session session = jsch.getSession(configuration.getUsername(), configuration.getHost(), configuration.getPort());

        if (isNotEmpty(sftpConfig.getStrictHostKeyChecking())) {
            LOG.debug("Using StrickHostKeyChecking: {}", sftpConfig.getStrictHostKeyChecking());
            session.setConfig("StrictHostKeyChecking", sftpConfig.getStrictHostKeyChecking());
        }
       
        session.setServerAliveInterval(sftpConfig.getServerAliveInterval());
        session.setServerAliveCountMax(sftpConfig.getServerAliveCountMax());

        // compression
        if (sftpConfig.getCompression() > 0) {
            LOG.debug("Using compression: {}", sftpConfig.getCompression());
            session.setConfig("compression.s2c", "zlib@openssh.com,zlib,none");
            session.setConfig("compression.c2s", "zlib@openssh.com,zlib,none");
            session.setConfig("compression_level", Integer.toString(sftpConfig.getCompression()));
        }
       
        // set the PreferredAuthentications
        if (sftpConfig.getPreferredAuthentications() != null) {
            LOG.debug("Using PreferredAuthentications: {}", sftpConfig.getPreferredAuthentications());
            session.setConfig("PreferredAuthentications", sftpConfig.getPreferredAuthentications());
        }

        // set user information
        session.setUserInfo(new ExtendedUserInfo() {
            public String getPassphrase() {
                return null;
            }

            public String getPassword() {
                return configuration.getPassword();
            }

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

            public boolean promptPassphrase(String s) {
                return true;
            }

            public boolean promptYesNo(String s) {
                LOG.warn("Server asks for confirmation (yes|no): " + s + ". Camel will answer no.");
                // Return 'false' indicating modification of the hosts file is disabled.
                return false;
            }

            public void showMessage(String s) {
                LOG.trace("Message received from Server: " + s);
            }

            public String[] promptKeyboardInteractive(String destination, String name,
                                                      String instruction, String[] prompt, boolean[] echo) {
                // must return an empty array if password is null
                if (configuration.getPassword() == null) {
                    return new String[0];
                } else {
                    return new String[]{configuration.getPassword()};
                }
            }

        });
       
        // set proxy if configured
        if (proxy != null) {
            session.setProxy(proxy);
        }
       
        return session;
    }
View Full Code Here

public class WebSpherePortalIntegrationTest extends PrivateTB3Configuration {

    @BeforeClass
    public static void deployPortlet() throws JSchException, SftpException {
        Session session = openSession();

        uploadDemoApplication(session);

        sendCommand(session, "ant -f deploy.xml get-lock startup-and-deploy");

        session.disconnect();
    }
View Full Code Here

        channel.disconnect();
    }

    private static Session openSession() throws JSchException {
        JSch jsch = new JSch();
        Session session = jsch.getSession("integration",
                "websphereportal8.devnet.vaadin.com", 22);
        jsch.addIdentity("~/.ssh/id_dsa");
        session.setConfig("StrictHostKeyChecking", "no");

        session.connect();
        return session;
    }
View Full Code Here

        return session;
    }

    @AfterClass
    public static void teardown() throws JSchException {
        Session session = openSession();

        sendCommand(session, "ant -f deploy.xml release-lock");

        session.disconnect();
    }
View Full Code Here

            OutputStream output) throws JSchException, InterruptedException {
        assert context != null;
        assert commandLineTokens != null;
        assert environmentVariables != null;
        assert output != null;
        Session session = jsch.getSession(user, host);
        if (port != null) {
            session.setPort(port);
        }
        session.setConfig("StrictHostKeyChecking", "no");
        session.setServerAliveInterval((int) TimeUnit.SECONDS.toMillis(30));

        try {
            YSLOG.info("I00001", user, host, port, privateKey);
            long sessionStart = System.currentTimeMillis();
            session.connect((int) TimeUnit.SECONDS.toMillis(60));
            long sessionEnd = System.currentTimeMillis();
            YSLOG.info("I00002", user, host, port, privateKey, sessionEnd - sessionStart);

            int exitStatus;
            try {
                ChannelExec channel = (ChannelExec) session.openChannel("exec");
                channel.setCommand(buildCommand(commandLineTokens, environmentVariables));
                channel.setInputStream(new ByteArrayInputStream(new byte[0]), true);
                channel.setOutputStream(output, true);
                channel.setErrStream(output, true);

                YSLOG.info("I00003", user, host, port, privateKey, commandLineTokens.get(0));
                long channelStart = System.currentTimeMillis();
                channel.connect((int) TimeUnit.SECONDS.toMillis(60));
                long channelEnd = System.currentTimeMillis();
                YSLOG.info("I00004", user, host, port, privateKey, commandLineTokens.get(0), channelEnd - channelStart);

                try {
                    while (true) {
                        if (channel.isClosed()) {
                            break;
                        }
                        Thread.sleep(100);
                    }
                    exitStatus = channel.getExitStatus();
                } finally {
                    channel.disconnect();
                }
            } finally {
                session.disconnect();
            }
            YSLOG.info("I00005", user, host, port, privateKey, commandLineTokens.get(0), exitStatus);
            return exitStatus;
        } catch (JSchException e) {
            YSLOG.error(e, "E00001", user, host, port, privateKey);
View Full Code Here

    }

    private SshCommandActionResult processConnection(JSch jsch, SshCommandActionDefinition definition,
        String nodeAddress, String effectiveCommand) throws Exception
    {
        Session session = jsch.getSession(definition.getUsername(), nodeAddress, definition.getPort());

        session.setPassword(definition.getPassword());
        session.setTimeout(0);
        session.setDaemonThread(true);

        if (definition.getSshProperties() != null) {
            Properties sshConfiguration = new Properties();
            sshConfiguration.putAll(definition.getSshProperties());
            session.setConfig(sshConfiguration);
        }

        session.connect(definition.getConnectionTimeoutMs());
        try {
            return processSession(session, definition, effectiveCommand);
        } finally {
            session.disconnect();
        }
    }
View Full Code Here

        if (sftpConfig.getKnownHosts() != null) {
            LOG.debug("Using knownhosts information from byte array");
            jsch.setKnownHosts(new ByteArrayInputStream(sftpConfig.getKnownHosts()));
        }

        final Session session = jsch.getSession(configuration.getUsername(), configuration.getHost(), configuration.getPort());

        if (isNotEmpty(sftpConfig.getStrictHostKeyChecking())) {
            LOG.debug("Using StrickHostKeyChecking: {}", sftpConfig.getStrictHostKeyChecking());
            session.setConfig("StrictHostKeyChecking", sftpConfig.getStrictHostKeyChecking());
        }
       
        session.setServerAliveInterval(sftpConfig.getServerAliveInterval());
        session.setServerAliveCountMax(sftpConfig.getServerAliveCountMax());

        // compression
        if (sftpConfig.getCompression() > 0) {
            LOG.debug("Using compression: {}", sftpConfig.getCompression());
            session.setConfig("compression.s2c", "zlib@openssh.com, zlib, none");
            session.setConfig("compression.c2s", "zlib@openssh.com, zlib, none");
            session.setConfig("compression_level", Integer.toString(sftpConfig.getCompression()));
        }
       
        // set the PreferredAuthentications
        if (sftpConfig.getPreferredAuthentications() != null) {
            LOG.debug("Using PreferredAuthentications: {}", sftpConfig.getPreferredAuthentications());
            session.setConfig("PreferredAuthentications", sftpConfig.getPreferredAuthentications());
        }

        // set user information
        session.setUserInfo(new ExtendedUserInfo() {
            public String getPassphrase() {
                return null;
            }

            public String getPassword() {
                return configuration.getPassword();
            }

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

            public boolean promptPassphrase(String s) {
                return true;
            }

            public boolean promptYesNo(String s) {
                LOG.warn("Server asks for confirmation (yes|no): " + s + ". Camel will answer no.");
                // Return 'false' indicating modification of the hosts file is disabled.
                return false;
            }

            public void showMessage(String s) {
                LOG.trace("Message received from Server: " + s);
            }

            public String[] promptKeyboardInteractive(String destination, String name,
                                                      String instruction, String[] prompt, boolean[] echo) {
                // must return an empty array if password is null
                if (configuration.getPassword() == null) {
                    return new String[0];
                } else {
                    return new String[]{configuration.getPassword()};
                }
            }

        });
       
        // set proxy if configured
        if (proxy != null) {
            session.setProxy(proxy);
        }
       
        return session;
    }
View Full Code Here

        String dir = args[3];

        Properties props = new Properties();
        props.setProperty("StrictHostKeyChecking", "false");
        JSch jsch = new JSch();
        Session session = jsch.getSession(user, host, 22);
        session.setUserInfo(new UserInfo()
        {
            public String getPassphrase()
            {
                return null;
            }

            public String getPassword()
            {
                return null;
            }

            public boolean promptPassword(String string)
            {
                return false;
            }

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

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

            public void showMessage(String string)
            {
            }
        });
        session.setPassword(pass);
        session.connect();
        ChannelSftp chan = (ChannelSftp) session.openChannel("sftp");
        chan.connect();
        Vector<?> list = chan.ls(dir);
        Iterator<?> iterList = list.iterator();
        while (iterList.hasNext())
        {
            System.err.println(iterList.next());
        }
        System.err.println("done");
        chan.disconnect();
        session.disconnect();
    }
View Full Code Here

TOP

Related Classes of com.jcraft.jsch.Session

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.