Java Code Examples for com.jcraft.jsch.Session#connect()

The following examples show how to use com.jcraft.jsch.Session#connect() . 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 vote down vote up
@Test
public void testExternalAuthProviderFails(TestContext context) throws Exception {
  AtomicInteger count = new AtomicInteger();
  authProvider = (authInfo, resultHandler) -> {
    count.incrementAndGet();
    resultHandler.handle(Future.failedFuture("not authenticated"));
  };
  termHandler = term -> {
    context.fail();
  };
  startShell(new SSHTermOptions().setPort(5000).setHost("localhost").setKeyPairOptions(
    new JksOptions().setPath("src/test/resources/server-keystore.jks").setPassword("wibble")));
  Session session = createSession("paulo", "anothersecret", false);
  try {
    session.connect();
    context.fail("Was not expected to login");
  } catch (JSchException e) {
    assertEquals("Auth cancel", e.getMessage());
  }
  context.assertEquals(1, count.get());
}
 
Example 2
Source File: SSHServerTest.java    From vertx-shell with Apache License 2.0 6 votes vote down vote up
private void testClose(TestContext context, Consumer<Term> closer) throws Exception {
  Async async = context.async();
  termHandler = term -> {
    term.closeHandler(v -> {
      async.complete();
    });
    closer.accept(term);
  };
  startShell();
  Session session = createSession("paulo", "secret", false);
  session.connect();
  Channel channel = session.openChannel("shell");
  channel.connect();
  while (channel.isClosed()) {
    Thread.sleep(10);
  }
}
 
Example 3
Source File: TeamCity.java    From at.info-knowledge-base with MIT License 6 votes vote down vote up
public TeamCity openSSHTunnel() throws Exception {
    Properties properties = new Properties();
    properties.load(new FileInputStream("src/test/resources/ssh.tunnel.properties"));

    JSch jsch = new JSch();
    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    Session session = jsch.getSession(properties.getProperty("login"), properties.getProperty("host"));
    session.setPassword(properties.getProperty("password"));
    session.setPortForwardingL(Integer.parseInt(properties.getProperty("lport")),
            properties.getProperty("remote.host"),
            Integer.parseInt(properties.getProperty("rport")));
    session.setConfig(config);
    try {
        session.connect((int) TimeUnit.SECONDS.toMillis(10));
    } catch (Exception e) {/**/}
    return this;
}
 
Example 4
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 5
Source File: SSHServerTest.java    From vertx-shell with Apache License 2.0 6 votes vote down vote up
@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 6
Source File: SSHServerTest.java    From vertx-shell with Apache License 2.0 6 votes vote down vote up
@Test
public void testDifferentCharset(TestContext context) throws Exception {
  termHandler = term -> {
    term.write("\u20AC");
    term.close();
  };
  startShell(new SSHTermOptions().setDefaultCharset("ISO_8859_1").setPort(5000).setHost("localhost").setKeyPairOptions(
    new JksOptions().setPath("src/test/resources/server-keystore.jks").setPassword("wibble")).
    setAuthOptions(new JsonObject()
      .put("provider", "shiro")
      .put("type", "PROPERTIES")
      .put("config",
        new JsonObject().put("properties_path", "classpath:test-auth.properties"))));
  Session session = createSession("paulo", "secret", false);
  session.connect();
  Channel channel = session.openChannel("shell");
  channel.connect();
  InputStream in = channel.getInputStream();
  int b = in.read();
  context.assertEquals(63, b);
}
 
Example 7
Source File: PortForwardingTest.java    From termd with Apache License 2.0 5 votes vote down vote up
protected Session createSession() throws JSchException {
    JSch sch = new JSch();
    Session session = sch.getSession(getCurrentTestName(), TEST_LOCALHOST, sshPort);
    session.setUserInfo(new SimpleUserInfo(getCurrentTestName()));
    session.connect();
    return session;
}
 
Example 8
Source File: SFTPUtils.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
public static Session createSession(final SFTPConfiguration conf, final JSch jsch) throws JSchException, IOException {
    if (conf == null || null == jsch) {
        throw new NullPointerException();
    }

    final Hashtable<String, String> newOptions = new Hashtable<>();

    Session session = jsch.getSession(conf.username, conf.hostname, conf.port);

    final String hostKeyVal = conf.hostkeyFile;

    if (null != hostKeyVal) {
        try {
            jsch.setKnownHosts(hostKeyVal);
        } catch (final IndexOutOfBoundsException iob) {
            throw new IOException("Unable to establish connection due to bad known hosts key file " + hostKeyVal, iob);
        }
    } else {
        newOptions.put("StrictHostKeyChecking", "no");
        session.setConfig(newOptions);
    }

    final String privateKeyVal = conf.privatekeyFile;
    if (null != privateKeyVal) {
        jsch.addIdentity(privateKeyVal, conf.privateKeypassphrase);
    }

    if (null != conf.password) {
        session.setPassword(conf.password);
    }

    session.setTimeout(conf.connectionTimeout); //set timeout for connection
    session.connect();
    session.setTimeout(conf.dataTimeout); //set timeout for data transfer

    return session;
}
 
Example 9
Source File: SshdShellAutoConfigurationAuthProviderTest.java    From sshd-shell-spring-boot with Apache License 2.0 5 votes vote down vote up
@Test(expected = JSchException.class)
public void testDaoFailedAuth() throws JSchException {
    JSch jsch = new JSch();
    Session session = jsch.getSession(props.getShell().getUsername(), props.getShell().getHost(),
            props.getShell().getPort());
    session.setPassword("wrong");
    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.connect();
}
 
Example 10
Source File: JSchUtils.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
/**
 * TODO: メソッドコメントを記述
 *
 * @param username
 * @param password
 * @param host
 * @param port
 * @return
 */
public static Session createSession(String username, String password, String host, int port) {
    try {
        JSch jsch = new JSch();
        Session session = jsch.getSession(username, host, port);
        session.setConfig("StrictHostKeyChecking", "no");
        session.setPassword(password);
        session.connect();
        return session;
    } catch (JSchException e) {
        throw new AutoException("ECOMMON-000302", username, host, port);
    }
}
 
Example 11
Source File: SFTPUtils.java    From axelor-open-suite with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 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 12
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 13
Source File: SshTunnelHandler.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Open a tunnel to the remote host.
 * 
 * @param remoteHost the host to connect to (where ssh will login).
 * @param remoteSshUser the ssh user.
 * @param remoteSshPwd the ssh password.
 * @param localPort the local port to use for the port forwarding (usually the same as the remote).
 * @param remotePort the remote port to use.
 * @return the tunnel manager, used also to disconnect when necessary.
 * @throws JSchException
 */
public static SshTunnelHandler openTunnel( String remoteHost, String remoteSshUser, String remoteSshPwd, int localPort,
        int remotePort ) throws JSchException {
    int port = 22;
    JSch jsch = new JSch();
    Session tunnelingSession = jsch.getSession(remoteSshUser, remoteHost, port);
    tunnelingSession.setPassword(remoteSshPwd);
    HMUserInfo lui = new HMUserInfo("");
    tunnelingSession.setUserInfo(lui);
    tunnelingSession.setConfig("StrictHostKeyChecking", "no");
    tunnelingSession.setPortForwardingL(localPort, "localhost", remotePort);
    tunnelingSession.connect();
    tunnelingSession.openChannel("direct-tcpip");
    return new SshTunnelHandler(tunnelingSession);
}
 
Example 14
Source File: ConnectionTest.java    From jsch-extension with MIT License 5 votes vote down vote up
private void testPasswordConnectionWithPassword( String password ) throws Exception {
    Session session = null;
    try {
        session = getPasswordAuthenticatingSessionFactory( password )
                .newSession();
        session.connect();
    }
    finally {
        if ( session != null ) {
            session.disconnect();
        }
    }
}
 
Example 15
Source File: JSchChannelsSupport.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private Session startNewSession(boolean acquireChannel) throws JSchException, InterruptedException {
    Session newSession = null;
    final AtomicBoolean cancelled = new AtomicBoolean(false);

    ConnectingProgressHandle.startHandle(env, new Cancellable() {
        @Override
        public boolean cancel() {
            cancelled.set(true);
            return true;
        }
    });

    try {
        while (!cancelled.get()) {
            try {
                newSession = jsch.getSession(env.getUser(), env.getHostAddress(), env.getSSHPort());
                int serverAliveInterval = Integer.getInteger("jsch.server.alive.interval", 0); // NOI18N
                if (serverAliveInterval > 0) {
                    newSession.setServerAliveInterval(serverAliveInterval);
                    int serverAliveCount = Integer.getInteger("jsch.server.alive.count", 5); // NOI18N
                    newSession.setServerAliveCountMax(serverAliveCount);
                }
                newSession.setUserInfo(userInfo);

                for (Entry<String, String> entry : jschSessionConfig.entrySet()) {
                    newSession.setConfig(entry.getKey(), entry.getValue());
                }
                Authentication auth = Authentication.getFor(env);
                final String preferredAuthKey = "PreferredAuthentications"; // NOI18N
                if (!jschSessionConfig.containsKey(preferredAuthKey)) {
                    String methods = auth.getAuthenticationMethods().toJschString();
                    if (methods != null) {
                        log.finest("Setting auth method list to " + methods); //NOI18N
                        newSession.setConfig(preferredAuthKey, methods);
                    }
                }
                if (USE_JZLIB) {
                    newSession.setConfig("compression.s2c", "[email protected],zlib,none"); // NOI18N
                    newSession.setConfig("compression.c2s", "[email protected],zlib,none"); // NOI18N
                    newSession.setConfig("compression_level", "9"); // NOI18N
                }

                if (RemoteStatistics.COLLECT_STATISTICS && RemoteStatistics.COLLECT_TRAFFIC) {
                    newSession.setSocketFactory(MeasurableSocketFactory.getInstance());
                }

                newSession.connect(auth.getTimeout()*1000);
                break;
            } catch (JSchException ex) {
                if (!UNIT_TEST_MODE) {
                    String msg = ex.getMessage();
                    if (msg == null) {
                        throw ex;
                    }
                    if (msg.startsWith("Auth fail") || msg.startsWith("SSH_MSG_DISCONNECT: 2")) { // NOI18N
                        PasswordManager.getInstance().clearPassword(env);
                    }
                } else {
                    throw ex;
                }
            } catch (CancellationException cex) {
                cancelled.set(true);
            }
        }

        if (cancelled.get()) {
            throw new InterruptedException("StartNewSession was cancelled ..."); // NOI18N
        }

        // In case of any port-forwarding previously set for this env
        // init the new session appropriately
        portForwarding.initSession(newSession);

        sessions.put(newSession, new AtomicInteger(JSCH_CHANNELS_PER_SESSION - (acquireChannel ? 1 : 0)));

        log.log(Level.FINE, "New session [{0}] started.", new Object[]{System.identityHashCode(newSession)}); // NOI18N
    } finally {
        ConnectingProgressHandle.stopHandle(env);
    }
    return newSession;
}
 
Example 16
Source File: SshCache.java    From ant-ivy with Apache License 2.0 4 votes vote down vote up
/**
 * Gets a session from the cache or establishes a new session if necessary
 *
 * @param host
 *            to connect to
 * @param port
 *            to use for session (-1 == use standard port)
 * @param username
 *            for the session to use
 * @param userPassword
 *            to use for authentication (optional)
 * @param pemFile
 *            File to use for public key authentication
 * @param pemPassword
 *            to use for accessing the pemFile (optional)
 * @param passFile
 *            to store credentials
 * @param allowedAgentUse
 *            Whether to communicate with an agent for authentication
 * @return session or null if not successful
 * @throws IOException if something goes wrong
 */
public Session getSession(String host, int port, String username, String userPassword,
        File pemFile, String pemPassword, File passFile, boolean allowedAgentUse)
        throws IOException {
    Checks.checkNotNull(host, "host");
    Checks.checkNotNull(username, "user");
    Entry entry = getCacheEntry(username, host, port);
    Session session = null;
    if (entry != null) {
        session = entry.getSession();
    }
    if (session == null || !session.isConnected()) {
        Message.verbose(":: SSH :: connecting to " + host + "...");
        try {
            JSch jsch = new JSch();
            if (port != -1) {
                session = jsch.getSession(username, host, port);
            } else {
                session = jsch.getSession(username, host);
            }
            if (allowedAgentUse) {
                attemptAgentUse(jsch);
            }
            if (pemFile != null) {
                jsch.addIdentity(pemFile.getAbsolutePath(), pemPassword);
            }
            session.setUserInfo(new CfUserInfo(host, username, userPassword, pemFile,
                    pemPassword, passFile));
            session.setDaemonThread(true);

            Properties config = new Properties();
            config.setProperty("PreferredAuthentications",
                "publickey,keyboard-interactive,password");
            session.setConfig(config);

            session.connect();
            Message.verbose(":: SSH :: connected to " + host + "!");
            setSession(username, host, port, session);
        } catch (JSchException e) {
            if (passFile != null && passFile.exists()) {
                passFile.delete();
            }
            throw new IOException(e.getMessage(), e);
        }
    }
    return session;
}
 
Example 17
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;
	}
 
Example 18
Source File: GitRepo.java    From warnings-ng-plugin with MIT License 4 votes vote down vote up
/**
 * Zip bare repository, copy to Docker container using sftp, then unzip. The repo is now accessible over
 * "ssh://git@ip:port/home/git/gitRepo.git"
 *
 * @param host
 *         IP of Docker container
 * @param port
 *         SSH port of Docker container
 */
public void transferToDockerContainer(String host, int port) {
    try {
        Path zipPath = Files.createTempFile("git", "zip");
        File zippedRepo = zipPath.toFile();
        String zippedFilename = zipPath.getFileName().toString();
        ZipUtil.pack(new File(dir.getPath()), zippedRepo);

        Properties props = new Properties();
        props.put("StrictHostKeyChecking", "no");

        JSch jSch = new JSch();
        jSch.addIdentity(privateKey.getAbsolutePath());

        Session session = jSch.getSession("git", host, port);
        session.setConfig(props);
        session.connect();

        ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
        channel.connect();
        channel.cd("/home/git");
        channel.put(new FileInputStream(zippedRepo), zippedFilename);

        ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
        InputStream in = channelExec.getInputStream();
        channelExec.setCommand("unzip " + zippedFilename + " -d " + REPO_NAME);
        channelExec.connect();

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;
        int index = 0;
        while ((line = reader.readLine()) != null) {
            System.out.println(++index + " : " + line);
        }

        channelExec.disconnect();
        channel.disconnect();
        session.disconnect();
        // Files.delete(zipPath);
    }
    catch (IOException | JSchException | SftpException e) {
        throw new AssertionError("Can't transfer git repository to docker container", e);
    }
}
 
Example 19
Source File: JschUtil.java    From jumbune with GNU Lesser General Public License v3.0 3 votes vote down vote up
/**
 * Gets the channel with response.
 * 
 * @param session
 *            the session
 * @param command
 *            the command
 * @return the channel with response
 * @throws JSchException
 *             the j sch exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static Channel getChannelWithResponse(Session session, String command) throws JSchException, IOException {
	session.connect();
	Channel channel = session.openChannel("exec");
	if(command.contains("sudo")){
		((ChannelExec) channel).setPty(true);
	}
	((ChannelExec) channel).setCommand(command);
	((ChannelExec) channel).setErrStream(System.err);		
	return channel;
}
 
Example 20
Source File: JschUtil.java    From jumbune with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Gets the channel.
 * 
 * @param session
 *            the session
 * @param command
 *            the command
 * @return the channel
 * @throws JSchException
 *             the j sch exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static Channel getShellChannel(Session session) throws JSchException, IOException {
	session.connect();
	return session.openChannel("shell");
}