Java Code Examples for com.jcraft.jsch.session#disconnect()
The following examples show how to use
com.jcraft.jsch.session#disconnect() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SSHServerTest.java From vertx-shell with Apache License 2.0 | 6 votes |
@Test public void testCloseHandler(TestContext context) throws Exception { Async async = context.async(); termHandler = term -> { term.closeHandler(v -> { async.complete(); }); }; startShell(); Session session = createSession("paulo", "secret", false); session.connect(); Channel channel = session.openChannel("shell"); channel.connect(); channel.disconnect(); session.disconnect(); }
Example 2
Source File: SFtpClientUtils.java From bamboobsc with Apache License 2.0 | 6 votes |
/** * 本地檔案放到遠端SFTP上 * * @param user * @param password * @param addr * @param port * @param localFile * @param remoteFile * @throws JSchException * @throws SftpException * @throws Exception */ public static void put(String user, String password, String addr, int port, List<String> localFile, List<String> remoteFile) throws JSchException, SftpException, Exception { Session session = getSession(user, password, addr, port); Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftpChannel = (ChannelSftp) channel; try { for (int i=0; i<localFile.size(); i++) { String rf=remoteFile.get(i); String lf=localFile.get(i); logger.info("put local file: " + lf + " write to " + addr + " :" + rf ); sftpChannel.put(lf, rf); logger.info("success write to " + addr + " :" + rf); } } catch (Exception e) { e.printStackTrace(); throw e; } finally { sftpChannel.exit(); channel.disconnect(); session.disconnect(); } }
Example 3
Source File: SSHServerTest.java From vertx-shell with Apache License 2.0 | 6 votes |
@Test public void testResizeHandler(TestContext context) throws Exception { Async async = context.async(); termHandler = term -> { term.resizehandler(v -> { context.assertEquals(20, term.width()); context.assertEquals(10, term.height()); async.complete(); }); }; startShell(); Session session = createSession("paulo", "secret", false); session.connect(); ChannelShell channel = (ChannelShell) session.openChannel("shell"); channel.connect(); OutputStream out = channel.getOutputStream(); channel.setPtySize(20, 10, 20 * 8, 10 * 8); out.flush(); channel.disconnect(); session.disconnect(); }
Example 4
Source File: SftpVerifierExtension.java From syndesis with Apache License 2.0 | 6 votes |
private static void verifyCredentials(ResultBuilder builder, Map<String, Object> parameters) { final String host = ConnectorOptions.extractOption(parameters, "host"); final Integer port = ConnectorOptions.extractOptionAndMap(parameters, "port", Integer::parseInt, 22); final String userName = ConnectorOptions.extractOption(parameters, "username"); final String password = ConnectorOptions.extractOption(parameters, "password", ""); JSch jsch = new JSch(); Session session = null; try { session = jsch.getSession(userName, host, port); session.setConfig("StrictHostKeyChecking", "no"); session.setPassword(password); session.connect(); } catch (JSchException e) { builder.error(ResultErrorBuilder .withCodeAndDescription(VerificationError.StandardCode.AUTHENTICATION, e.getMessage()).build()); } finally { if (session != null) { session.disconnect(); jsch = null; } } }
Example 5
Source File: SshProxy.java From ssh-proxy with Apache License 2.0 | 6 votes |
@Override public void close() { if (!sshSessions.isEmpty()) { log.debug("closing SSH sessions"); } while (!sshSessions.isEmpty()) { Session session = sshSessions.pop(); deletePortForwarding(session); try { session.disconnect(); } catch (Exception e) { log.error("Failed to disconnect SSH session", e); } } Assert.isTrue(portForwardings.isEmpty(), "port forwardings must be empty at this point"); }
Example 6
Source File: SFtpClientUtils.java From bamboobsc with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") public static Vector<LsEntry> getRemoteFileList(String user, String password, String addr, int port, String cwd) throws JSchException, SftpException, Exception { Session session = getSession(user, password, addr, port); Vector<LsEntry> lsVec=null; Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftpChannel = (ChannelSftp) channel; try { lsVec=(Vector<LsEntry>)sftpChannel.ls(cwd); //sftpChannel.lpwd() } catch (Exception e) { e.printStackTrace(); throw e; } finally { sftpChannel.exit(); channel.disconnect(); session.disconnect(); } return lsVec; }
Example 7
Source File: SshLocalhostNoEchoExample.java From ExpectIt with Apache License 2.0 | 5 votes |
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("stty -echo"); expect.expect(contains("$")); expect.sendLine("pwd"); System.out.println("pwd1:" + expect.expect(contains("\n")).getBefore()); expect.sendLine("exit"); } finally { expect.close(); channel.disconnect(); session.disconnect(); } }
Example 8
Source File: ConnectionTest.java From jsch-extension with MIT License | 5 votes |
private void testKeyboardInteractiveConnectionWithPassword( String password ) throws Exception { Session session = null; try { session = getKeyboardInteractiveAuthenticatingSessionFactory( password ) .newSession(); session.connect(); } finally { if ( session != null ) { session.disconnect(); } } }
Example 9
Source File: ATest.java From aws-ec2-ssh with MIT License | 5 votes |
protected final void probeSSH(final String host, final User user) { final Callable<Boolean> callable = () -> { final JSch jsch = new JSch(); final Session session = jsch.getSession(user.userName, host); jsch.addIdentity(user.userName, user.sshPrivateKeyBlob, null, null); jsch.setConfig("StrictHostKeyChecking", "no"); // for testing this should be fine. adding the host key seems to be only possible via a file which is not very useful here session.connect(10000); session.disconnect(); return true; }; Assert.assertTrue(this.retry(callable)); }
Example 10
Source File: JSchUtilsTest.java From primecloud-controller with GNU General Public License v2.0 | 5 votes |
@Test @Ignore public void testSftpPut() throws Exception { Session session = JSchUtils.createSession("user01", "passw0rd", "172.22.0.23"); ByteArrayInputStream input = new ByteArrayInputStream("abcde".getBytes()); JSchUtils.sftpPut(session, input, "/home/user01/test"); session.disconnect(); }
Example 11
Source File: SFtpClientUtils.java From bamboobsc with Apache License 2.0 | 5 votes |
/** * 抓遠端檔案然後存到本機 , 單筆 * * @param user * @param password * @param addr * @param port * @param remoteFile * @param localFile * @throws JSchException * @throws SftpException * @throws Exception */ public static void get(String user, String password, String addr, int port, String remoteFile, String localFile) throws JSchException, SftpException, Exception { Session session = getSession(user, password, addr, port); Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftpChannel = (ChannelSftp) channel; logger.info("get remote file: " + remoteFile + " write to:" + localFile ); try { sftpChannel.get(remoteFile, localFile); } catch (Exception e) { e.printStackTrace(); throw e; } finally { sftpChannel.exit(); channel.disconnect(); session.disconnect(); } File f=new File(localFile); if (!f.exists()) { f=null; logger.error("get remote file:"+remoteFile + " fail!"); throw new Exception("get remote file:"+remoteFile + " fail!"); } f=null; logger.info("success write:" + localFile); }
Example 12
Source File: SshProxyTest.java From jsch-extension with MIT License | 5 votes |
@Test public void testSshProxy() { Proxy proxy = null; Session session = null; Channel channel = null; try { SessionFactory proxySessionFactory = sessionFactory.newSessionFactoryBuilder() .setHostname( "localhost" ).setPort( SessionFactory.SSH_PORT ).build(); SessionFactory destinationSessionFactory = sessionFactory.newSessionFactoryBuilder() .setProxy( new SshProxy( proxySessionFactory ) ).build(); session = destinationSessionFactory.newSession(); session.connect(); channel = session.openChannel( "exec" ); ((ChannelExec)channel).setCommand( "echo " + expected ); InputStream inputStream = channel.getInputStream(); channel.connect(); // echo adds \n assertEquals( expected + "\n", IOUtils.copyToString( inputStream, UTF8 ) ); } catch ( Exception e ) { logger.error( "failed for proxy {}: {}", proxy, e ); logger.debug( "failed:", e ); fail( e.getMessage() ); } finally { if ( channel != null && channel.isConnected() ) { channel.disconnect(); } if ( session != null && session.isConnected() ) { session.disconnect(); } } }
Example 13
Source File: Scanner.java From ciscorouter with MIT License | 5 votes |
/** * 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()) //.withEchoOutput(System.out) //.withEchoInput(System.out) .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("#")); //# expect.sendLine(DISABLE_OUTPUT_BUFFERING); //terminal length 0 expect.expect(contains("#")); //# expect.sendLine(GET_ALL_CONFIG); //show running-config full 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 14
Source File: SFTPUtils.java From axelor-open-suite with GNU Affero General Public License v3.0 | 5 votes |
/** * Returns true if session is valid. * * @throws JSchException if session is already connected. */ public static boolean isValid(Session session) throws JSchException { boolean valid; session.connect(); valid = session.isConnected(); session.disconnect(); return valid; }
Example 15
Source File: PortForwardingTest.java From termd with Apache License 2.0 | 5 votes |
@Test public void testRemoteForwarding() throws Exception { Session session = createSession(); try { int forwardedPort = Utils.getFreePort(); session.setPortForwardingR(forwardedPort, TEST_LOCALHOST, echoPort); waitForForwardingRequest(TcpipForwardHandler.REQUEST, TimeUnit.SECONDS.toMillis(5L)); try (Socket s = new Socket(TEST_LOCALHOST, forwardedPort); OutputStream output = s.getOutputStream(); InputStream input = s.getInputStream()) { s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L)); String expected = getCurrentTestName(); byte[] bytes = expected.getBytes(StandardCharsets.UTF_8); output.write(bytes); output.flush(); byte[] buf = new byte[bytes.length + Long.SIZE]; int n = input.read(buf); String res = new String(buf, 0, n, StandardCharsets.UTF_8); assertEquals("Mismatched data", expected, res); } finally { session.delPortForwardingR(forwardedPort); } } finally { session.disconnect(); } }
Example 16
Source File: SSHSessionResource.java From cs-actions with Apache License 2.0 | 5 votes |
@Override public void release() { final Collection<SSHConnection> sshConnections = sshConnectionMap.values(); for (SSHConnection sshConnection : sshConnections) { synchronized (sshConnection) { Session session = sshConnection.getSession(); session.disconnect(); Channel channel = sshConnection.getChannel(); if (channel != null) { channel.disconnect(); } } } sshConnectionMap = null; }
Example 17
Source File: PortForwardingTest.java From termd with Apache License 2.0 | 5 votes |
@Test public void testLocalForwarding() throws Exception { Session session = createSession(); try { int forwardedPort = Utils.getFreePort(); session.setPortForwardingL(forwardedPort, TEST_LOCALHOST, echoPort); try (Socket s = new Socket(TEST_LOCALHOST, forwardedPort); OutputStream output = s.getOutputStream(); InputStream input = s.getInputStream()) { s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L)); String expected = getCurrentTestName(); byte[] bytes = expected.getBytes(StandardCharsets.UTF_8); output.write(bytes); output.flush(); byte[] buf = new byte[bytes.length + Long.SIZE]; int n = input.read(buf); String res = new String(buf, 0, n); assertEquals("Mismatched data", expected, res); } finally { session.delPortForwardingL(forwardedPort); } } finally { session.disconnect(); } }
Example 18
Source File: PortForwardingTest.java From termd with Apache License 2.0 | 4 votes |
@Test(timeout = 45000) public void testRemoteForwardingWithDisconnect() throws Exception { Session session = createSession(); try { // 1. Create a Port Forward int forwardedPort = Utils.getFreePort(); session.setPortForwardingR(forwardedPort, TEST_LOCALHOST, echoPort); waitForForwardingRequest(TcpipForwardHandler.REQUEST, TimeUnit.SECONDS.toMillis(5L)); // 2. Establish a connection through it try (Socket s = new Socket(TEST_LOCALHOST, forwardedPort)) { s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L)); // 3. Simulate the client going away rudelyDisconnectJschSession(session); // 4. Make sure the NIOprocessor is not stuck Thread.sleep(TimeUnit.SECONDS.toMillis(1L)); // from here, we need to check all the threads running and find a // "NioProcessor-" // that is stuck on a PortForward.dispose ThreadGroup root = Thread.currentThread().getThreadGroup().getParent(); while (root.getParent() != null) { root = root.getParent(); } for (int index = 0;; index++) { Collection<Thread> pending = findThreads(root, "NioProcessor-"); if (GenericUtils.size(pending) <= 0) { log.info("Finished after " + index + " iterations"); break; } try { Thread.sleep(TimeUnit.SECONDS.toMillis(1L)); } catch (InterruptedException e) { // ignored } } session.delPortForwardingR(forwardedPort); } } finally { session.disconnect(); } }
Example 19
Source File: JschExecutor.java From jumbune with GNU Lesser General Public License v3.0 | 4 votes |
public void closeSession(Session session){ if(session!=null && session.isConnected()){ session.disconnect(); } }
Example 20
Source File: RmtShellExecutor.java From LuckyFrameClient with GNU Affero General Public License v3.0 | 4 votes |
/** * ����JSch��ʵ��Զ������SHELL����ִ�� * * @param ip ����IP * @param user ������½�û��� * @param psw ������½���� * @param port ����ssh2��½�˿ڣ����ȡĬ��ֵ����-1 * @param command Shell���� cd /home/pospsettle/tomcat-7.0-7080/bin&&./restart.sh */ public static String sshShell(String ip, String user, String psw , int port, String command) { Session session = null; Channel channel = null; String result = "Status:true" + " ��������ִ�гɹ���"; try { JSch jsch = new JSch(); LogUtil.APP.info("���뵽����TOMCAT����..."); if (port <= 0) { //���ӷ�����������Ĭ�϶˿� LogUtil.APP.info("��������TOMCAT������IP��Ĭ�϶˿�..."); session = jsch.getSession(user, ip); } else { //����ָ���Ķ˿����ӷ����� LogUtil.APP.info("��������TOMCAT������IP���˿�..."); session = jsch.getSession(user, ip, port); LogUtil.APP.info("��������TOMCAT������IP���˿����!"); } //������������Ӳ��ϣ����׳��쳣 if (session == null) { LogUtil.APP.warn("����TOMCAT�����У����ӷ�����session is null"); throw new Exception("session is null"); } //���õ�½���������� session.setPassword(psw); //���õ�һ�ε�½��ʱ����ʾ����ѡֵ��(ask | yes | no) session.setConfig("StrictHostKeyChecking", "no"); //���õ�½��ʱʱ�� session.connect(30000); //����sftpͨ��ͨ�� channel = session.openChannel("shell"); channel.connect(1000); //��ȡ������������� InputStream instream = channel.getInputStream(); OutputStream outstream = channel.getOutputStream(); //������Ҫִ�е�SHELL�����Ҫ��\n��β����ʾ�س� LogUtil.APP.info("��������TOMCAT��������������!"); String shellCommand = command + " \n"; outstream.write(shellCommand.getBytes()); outstream.flush(); Thread.sleep(10000); //��ȡ����ִ�еĽ�� if (instream.available() > 0) { byte[] data = new byte[instream.available()]; int nLen = instream.read(data); if (nLen < 0) { LogUtil.APP.warn("����TOMCAT�����У���ȡ����ִ�н�������쳣��"); } //ת������������ӡ���� String temp = new String(data, 0, nLen, "iso8859-1"); LogUtil.APP.info("��ʼ��ӡ����TOMCAT����ִ�н��...{}", temp); } outstream.close(); instream.close(); } catch (Exception e) { result = "����TOMCAT�����У������쳣��"; LogUtil.APP.error("����TOMCAT�����У������쳣��", e); return result; } finally { if (null != session) { session.disconnect(); } if (null != channel) { channel.disconnect(); } } return result; }