Java Code Examples for com.jcraft.jsch.Channel#disconnect()

The following examples show how to use com.jcraft.jsch.Channel#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 7 votes vote down vote up
@Test
public void testWrite() throws Exception {
  termHandler = term -> {
    term.write("hello");
  };
  startShell();
  Session session = createSession("paulo", "secret", false);
  session.connect();
  Channel channel = session.openChannel("shell");
  channel.connect();
  Reader in = new InputStreamReader(channel.getInputStream());
  int count = 5;
  StringBuilder sb = new StringBuilder();
  while (count > 0) {
    int code = in.read();
    if (code == -1) {
      count = 0;
    } else {
      count--;
      sb.append((char) code);
    }
  }
  assertEquals("hello", sb.toString());
  channel.disconnect();
  session.disconnect();
}
 
Example 2
Source File: SFtpClientUtils.java    From bamboobsc with Apache License 2.0 7 votes vote down vote up
public static void rm(String user, String password, String addr, int port, List<String> fileName) throws JSchException, SftpException, Exception {
	
	if (fileName==null || fileName.size()<1) {
		return;
	}
	Session session = getSession(user, password, addr, port);				
	Channel channel = session.openChannel("sftp");
	channel.connect();
	ChannelSftp sftpChannel = (ChannelSftp) channel;		
	try {
		for (String f : fileName) {
			sftpChannel.rm(f);				
			logger.warn("success remove file from " + addr + " :" + fileName);				
		}
	} catch (Exception e) {
		e.printStackTrace();
		throw e;
	} finally {
		sftpChannel.exit();
		channel.disconnect();
		session.disconnect();				
	}		
}
 
Example 3
Source File: SFtpClientUtils.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
@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 4
Source File: SessionEstablisher.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * This method execute the given command over SSH
 * 
 * @param session
 * @param command
 *            Command to be executed
 * @throws JSchException
 * @throws IOException
 * @throws InterruptedException
 */
static String executeCommand(Session session, String command) throws JSchException, IOException {
	InputStream in = null;
	Channel channel = null;
	String msg = null;
	try {
		channel = session.openChannel("exec");
		((ChannelExec) channel).setCommand(command);
		channel.setInputStream(null);
		((ChannelExec) channel).setErrStream(System.err);
		in = channel.getInputStream();
		channel.connect();
		msg = validateCommandExecution(channel, in);
	} catch (InterruptedException e) {
		CONSOLE_LOGGER.error(e);
	} finally {
		if (in != null) {
			in.close();
		}
		if (channel != null) {
			channel.disconnect();
		}
	}
	return msg;
}
 
Example 5
Source File: SSHServerTest.java    From vertx-shell with Apache License 2.0 6 votes vote down vote up
@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 6
Source File: SshProxyTest.java    From jsch-extension with MIT License 5 votes vote down vote up
@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 7
Source File: SFTPSessionResource.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
@Override
public void release() {
    final Collection<SFTPConnection> sftpConnections = connectionMap.values();
    for (SFTPConnection sftpConnection : sftpConnections) {
        synchronized (sftpConnection) {
            Session session = sftpConnection.getSession();
            session.disconnect();
            Channel channel = sftpConnection.getChannel();
            if (channel != null) {
                channel.disconnect();
            }
        }
    }
    connectionMap = null;
}
 
Example 8
Source File: SSHSessionResource.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
@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 9
Source File: SshUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Launch a command on the remote host and exit once the command is done.
 * 
 * @param session the session to use.
 * @param command the command to launch.
 * @return the output of the command.
 * @throws JSchException
 * @throws IOException
 */
private static String launchACommand( Session session, String command ) throws JSchException, IOException {
    Channel channel = session.openChannel("exec");
    ((ChannelExec) channel).setCommand(command);
    channel.setInputStream(null);
    ((ChannelExec) channel).setErrStream(System.err);
    InputStream in = channel.getInputStream();
    channel.connect();
    StringBuilder sb = new StringBuilder();
    byte[] tmp = new byte[1024];
    while( true ) {
        while( in.available() > 0 ) {
            int i = in.read(tmp, 0, 1024);
            if (i < 0)
                break;
            sb.append(new String(tmp, 0, i));
        }
        if (channel.isClosed()) {
            if (in.available() > 0)
                continue;
            System.out.println("exitstatus: " + channel.getExitStatus());
            break;
        }
        try {
            Thread.sleep(1000);
        } catch (Exception ee) {
        }
    }
    channel.disconnect();
    String remoteResponseStr = sb.toString().trim();
    return remoteResponseStr;
}
 
Example 10
Source File: SFtpClientUtils.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
/**
 * 抓遠端檔案然後存到本機 , 單筆
 * 
 * @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 11
Source File: SFtpClientUtils.java    From bamboobsc with Apache License 2.0 5 votes vote down vote up
/**
 * 抓遠端檔案然後存到本機 , 多筆
 * 
 * @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, 
		List<String> remoteFile, List<String> localFile) 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<remoteFile.size(); i++) {
			String rf=remoteFile.get(i);
			String lf=localFile.get(i);
			logger.info("get remote file: " + rf + " write to:" + lf );
			sftpChannel.get(rf, lf);
			File f=new File(lf);
			if (!f.exists()) {
				f=null;
				logger.error("get remote file:"+rf + " fail!");
				throw new Exception("get remote file:"+rf + " fail!");
			}
			f=null;
			logger.info("success write:" + lf);
		}
	} catch (Exception e) {
		e.printStackTrace();
		throw e;
	} finally {
		sftpChannel.exit();
		channel.disconnect();
		session.disconnect();				
	}
}
 
Example 12
Source File: SshUtilities.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Launch a command on the remote host and exit even if the command is not done (useful for launching daemons).
 * 
 * @param session the session to use.
 * @param command the command to launch.
 * @return the output of the command.
 * @throws JSchException
 * @throws IOException
 */
private static String launchACommandAndExit( Session session, String command ) throws JSchException, IOException {
    Channel channel = session.openChannel("exec");
    ((ChannelExec) channel).setCommand(command);
    channel.setInputStream(null);
    ((ChannelExec) channel).setErrStream(System.err);
    InputStream in = channel.getInputStream();
    channel.connect();
    StringBuilder sb = new StringBuilder();
    byte[] tmp = new byte[1024];
    while( true ) {
        while( in.available() > 0 ) {
            int i = in.read(tmp, 0, 1024);
            if (i < 0)
                break;
            sb.append(new String(tmp, 0, i));
        }
        if (channel.isClosed()) {
            if (in.available() > 0)
                continue;
            break;
        }
        try {
            if (sb.length() > 0) {
                break;
            }
            Thread.sleep(1000);
        } catch (Exception ee) {
        }
    }
    channel.disconnect();
    String remoteResponseStr = sb.toString().trim();
    return remoteResponseStr;
}
 
Example 13
Source File: SftpUtils.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
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 14
Source File: SSHShellTest.java    From vertx-shell with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeployServiceWithJDBCAuthOptions(TestContext context) throws Exception {
  List<String> SQL  = Arrays.asList(
      "create table user (username varchar(255), password varchar(255), password_salt varchar(255) );",
      "create table user_roles (username varchar(255), role varchar(255));",
      "create table roles_perms (role VARCHAR(255) NOT NULL, perm VARCHAR(255) NOT NULL);",
      "insert into user values ('tim', 'EC0D6302E35B7E792DF9DA4A5FE0DB3B90FCAB65A6215215771BF96D498A01DA8234769E1CE8269A105E9112F374FDAB2158E7DA58CDC1348A732351C38E12A0', 'C59EB438D1E24CACA2B1A48BC129348589D49303858E493FBE906A9158B7D5DC');"
  );
  Connection conn = DriverManager.getConnection(config().getString("url"));
  for (String sql : SQL) {
    conn.createStatement().execute(sql);
  }
  Async async = context.async();
  vertx.deployVerticle("service:io.vertx.ext.shell", new DeploymentOptions().setConfig(new JsonObject().put("sshOptions",
      new JsonObject().
          put("host", "localhost").
          put("port", 5000).
          put("keyPairOptions", new JsonObject().
              put("path", "src/test/resources/server-keystore.jks").
              put("password", "wibble")).
          put("authOptions", new JsonObject()
            .put("provider", "jdbc")
            .put("config",
              new JsonObject()
                  .put("url", "jdbc:hsqldb:mem:test?shutdown=true")
                  .put("driver_class", "org.hsqldb.jdbcDriver")))))
      , context.asyncAssertSuccess(v -> {
    async.complete();
  }));
  async.awaitSuccess(2000);
  Session session = createSession("tim", "sausages", false);
  session.connect();
  Channel channel = session.openChannel("shell");
  channel.connect();
  channel.disconnect();
  session.disconnect();
}
 
Example 15
Source File: WebSSHServiceImpl.java    From mcg-helper with Apache License 2.0 5 votes vote down vote up
private void connectToSSH(SSHConnectInfo sshConnectInfo, WebSSHData webSSHData, ServerSource serverSource, Session webSocketSession, String httpSessionId) throws JSchException, IOException {
      Properties config = new Properties();
      config.put("StrictHostKeyChecking", "no");
      com.jcraft.jsch.Session session = sshConnectInfo.getjSch().getSession(serverSource.getUserName(), serverSource.getIp(), serverSource.getPort());
      session.setConfig(config);
UserInfo ui = null;
if(StringUtils.isEmpty(serverSource.getSecretKey())) {
	ui = new SSHUserInfo(serverSource.getPwd());
} else {
	ui = new SSHGoogleAuthUserInfo(serverSource.getSecretKey(), serverSource.getPwd());
}
session.setUserInfo(ui);
      session.connect(6000);
      
      
      Channel channel = session.openChannel("shell");
      ((ChannelShell)channel).setPtyType("vt100", webSSHData.getCols(), webSSHData.getRows(), webSSHData.getTerminalWidth(), webSSHData.getTerminalHeight());
      channel.connect(5000);
      sshConnectInfo.setChannel(channel);

      transToSSH(channel, Constants.LINUX_ENTER);

      InputStream inputStream = channel.getInputStream();
      try {
          byte[] buffer = new byte[1024];
          int i = 0;
          while ((i = inputStream.read(buffer)) != -1) {
              sendMessage(webSocketSession, Arrays.copyOfRange(buffer, 0, i), httpSessionId);
          }

      } finally {
          session.disconnect();
          channel.disconnect();
          if (inputStream != null) {
              inputStream.close();
          }
      }

  }
 
Example 16
Source File: SSHManager.java    From pacbot with Apache License 2.0 5 votes vote down vote up
public String sendCommand(String command) {
    StringBuilder outputBuffer = new StringBuilder();

    try {
        Channel channel = sesConnection.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
        InputStream commandOutput = channel.getInputStream();
        channel.connect();
        int readByte = commandOutput.read();

        while (readByte != 0xffffffff) {
            outputBuffer.append((char) readByte);
            readByte = commandOutput.read();
        }
        channel.disconnect();
    } catch (IOException ioX) {
        logWarning(ioX.getMessage());
        LOGGER.error("error while getting kernelversion from SSH", ioX);
        return null;
    } catch (JSchException jschX) {
        LOGGER.error(
                "error while getting kernelversion from JSchException SSH",
                jschX);
        logWarning(jschX.getMessage());
        return null;
    }

    return outputBuffer.toString();
}
 
Example 17
Source File: JschExecutor.java    From jumbune with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void closeChannel(Channel channel){
	if(channel!=null && channel.isConnected()){
		channel.disconnect();
	}
}
 
Example 18
Source File: SSHCommandExecutor.java    From journaldev with MIT License 4 votes vote down vote up
/**
 * @param args
 */
public static void main(String[] args) {
    String host="test.journaldev.com";
    String user="my_user";
    String password="my_pwd";
    String command1="cd Apps;ls -ltr";
    try{
    	
    	java.util.Properties config = new java.util.Properties(); 
    	config.put("StrictHostKeyChecking", "no");
    	JSch jsch = new JSch();
    	Session session=jsch.getSession(user, host, 22);
    	session.setPassword(password);
    	session.setConfig(config);
    	session.connect();
    	System.out.println("Connected");
    	
    	Channel channel=session.openChannel("exec");
        ((ChannelExec)channel).setCommand(command1);
        channel.setInputStream(null);
        ((ChannelExec)channel).setErrStream(System.err);
        
        InputStream in=channel.getInputStream();
        channel.connect();
        byte[] tmp=new byte[1024];
        while(true){
          while(in.available()>0){
            int i=in.read(tmp, 0, 1024);
            if(i<0)break;
            System.out.print(new String(tmp, 0, i));
          }
          if(channel.isClosed()){
            System.out.println("exit-status: "+channel.getExitStatus());
            break;
          }
          try{Thread.sleep(1000);}catch(Exception ee){}
        }
        channel.disconnect();
        session.disconnect();
        System.out.println("DONE");
    }catch(Exception e){
    	e.printStackTrace();
    }

}
 
Example 19
Source File: SshExample.java    From ExpectIt with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws JSchException, IOException {
    JSch jSch = new JSch();
    Session session = jSch.getSession("new", "sdf.org");
    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.connect();
    Channel channel = session.openChannel("shell");
    channel.connect();

    Expect expect = new ExpectBuilder()
            .withOutput(channel.getOutputStream())
            .withInputs(channel.getInputStream(), channel.getExtInputStream())
            .withEchoInput(System.out)
            .withEchoOutput(System.err)
            .withInputFilters(removeColors(), removeNonPrintable())
            .withExceptionOnFailure()
            .build();
    try {
        expect.expect(contains("[RETURN]"));
        expect.sendLine();
        String ipAddress = expect.expect(regexp("Trying (.*)\\.\\.\\.")).group(1);
        System.out.println("Captured IP: " + ipAddress);
        expect.expect(contains("login:"));
        expect.sendLine("new");
        expect.expect(contains("(Y/N)"));
        expect.send("N");
        expect.expect(regexp(": $"));
        expect.send("\b");
        expect.expect(regexp("\\(y\\/n\\)"));
        expect.sendLine("y");
        expect.expect(contains("Would you like to sign the guestbook?"));
        expect.send("n");
        expect.expect(contains("[RETURN]"));
        expect.sendLine();
    } finally {
        expect.close();
        channel.disconnect();
        session.disconnect();
    }
}
 
Example 20
Source File: SSHShellUtil.java    From mcg-helper with Apache License 2.0 4 votes vote down vote up
public static String execute(String ip, int port, String userName, String password, String secretKey, String shell) throws JSchException, IOException {
		String response = null;
		JSch.setLogger(new ShellLogger());
		JSch jsch = new JSch();
		Session session = jsch.getSession(userName, ip, port);
		UserInfo ui = null;
		if(StringUtils.isEmpty(secretKey)) {
			ui = new SSHUserInfo(password);
		} else {
			ui = new SSHGoogleAuthUserInfo(secretKey, password);
		}
		session.setUserInfo(ui);
		session.connect(6000);

		Channel channel = session.openChannel("shell");
		PipedInputStream pipedInputStream = new PipedInputStream();
		PipedOutputStream pipedOutputStream = new PipedOutputStream();
		pipedOutputStream.connect(pipedInputStream);
		
		Thread thread = new Thread(new MonitorShellUser(channel, shell, pipedOutputStream));
		thread.start();
		
		channel.setInputStream(pipedInputStream);
		
		PipedOutputStream shellPipedOutputStream = new PipedOutputStream();
		PipedInputStream receiveStream = new PipedInputStream(); 
		shellPipedOutputStream.connect(receiveStream);
		
		channel.setOutputStream(shellPipedOutputStream);
		((ChannelShell)channel).setPtyType("vt100", 160, 24, 1000, 480);   // dumb
		//((ChannelShell)channel).setTerminalMode("binary".getBytes(Constants.CHARSET));
	//	((ChannelShell)channel).setEnv("LANG", "zh_CN.UTF-8");
		try {
			channel.connect();
			response = IOUtils.toString(receiveStream, "UTF-8");
		}finally {
//			if(channel.isClosed()) {
				pipedOutputStream.close();
				pipedInputStream.close();
				shellPipedOutputStream.close();
				receiveStream.close();
				channel.disconnect();
				session.disconnect();
			}
//		}
			
		return response;
	}