Java Code Examples for com.jcraft.jsch.session#setUserInfo()

The following examples show how to use com.jcraft.jsch.session#setUserInfo() . 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: RemoteLauncherCommands.java    From gemfirexd-oss with Apache License 2.0 8 votes vote down vote up
/**
 * Connect to a remote host via SSH and execute a command.
 * 
 * @param host
 *          Host to connect to
 * @param user
 *          User to login with
 * @param password
 *          Password for the user
 * @param command
 *          Command to execute
 * @return The result of the command execution
 */
private Result executeSshCommand(final String host, final String user,
    final String password, final String command) {
  
  StringBuilder result = new StringBuilder();
  
  try {
    JSch jsch = new JSch();
    Session session = jsch.getSession(user, host, 22);
    session.setUserInfo(createUserInfo(password));
    session.connect(5000);

    ChannelExec channel = (ChannelExec) session.openChannel("exec");
    channel.setCommand(command);
    channel.setInputStream(null);
    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;
        result.append(new String(tmp, 0, i));
      }
      if (channel.isClosed()) {
        break;
      }
    }
    channel.disconnect();
    session.disconnect();
  } catch (Exception jex) {
    return createResult(Result.Status.ERROR, jex.getMessage());
  }
 
  return createResult(Result.Status.OK, result.toString());
}
 
Example 2
Source File: MultiUserSshSessionFactory.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
private Session createSession(CredentialsProvider credentialsProvider,
                              FS fs, String user, final String pass, String host, int port,
                              final OpenSshConfig.Host hc) throws JSchException {
    final Session session = createSession(credentialsProvider, hc, user, host, port, fs);
    // We retry already in getSession() method. JSch must not retry
    // on its own.
    session.setConfig("MaxAuthTries", "1"); //$NON-NLS-1$ //$NON-NLS-2$
    if (pass != null)
        session.setPassword(pass);
    final String strictHostKeyCheckingPolicy = hc
            .getStrictHostKeyChecking();
    if (strictHostKeyCheckingPolicy != null)
        session.setConfig("StrictHostKeyChecking", //$NON-NLS-1$
                strictHostKeyCheckingPolicy);
    final String pauth = hc.getPreferredAuthentications();
    if (pauth != null)
        session.setConfig("PreferredAuthentications", pauth); //$NON-NLS-1$
    if (credentialsProvider != null && !(credentialsProvider instanceof PrivateKeyCredentialsProvider)
            && (!hc.isBatchMode() || !credentialsProvider.isInteractive())) {
        session.setUserInfo(new CredentialsProviderUserInfo(session,
                credentialsProvider));
    }
    configure(hc, session);
    return session;
}
 
Example 3
Source File: EmbeddedSSHClient.java    From embeddedlinux-jvmdebugger-intellij with Apache License 2.0 7 votes vote down vote up
/**
 * Gets SSH Client
 *
 * @return
 */
@SneakyThrows(JSchException.class)
public Session get() {
    JSch jsch = new JSch();
    UserInfo userInfo;
    Session session = jsch.getSession(username, hostname, port);
    if (useKey) {
        jsch.addIdentity(key);
        userInfo = new EmbeddedUserInfoInteractive();
    } else {
        session.setPassword(password);
        session.setConfig("StrictHostKeyChecking", "no");
        userInfo = EmbeddedUserInfo.builder().password(password).build();
    }
    session.setUserInfo(userInfo);
    session.setConfig("HashKnownHosts", "yes");
    session.setTimeout(10000);
    session.connect();
    return session;
}
 
Example 4
Source File: JschUtil.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Verify password.
 *
 * @param user the user
 * @param encryptedPasswrd the encrypted passwrd
 * @return true, if successful
 * @throws Exception the exception
 */
//TODO: Require to make sure we are not using localhost
public static boolean verifyPassword(String user, String encryptedPasswrd) throws Exception {
	JSch jsch = new JSch();
	Session session = null;
	java.util.Properties conf = new java.util.Properties();
	session = jsch.getSession(user, "localhost", RemotingConstants.TWENTY_TWO);
	UserInfo info = new JumbuneUserInfo(StringUtil.getPlain(encryptedPasswrd));
	session.setUserInfo(info);
	conf.put(STRICT_HOST_KEY_CHECKING, "no");
	session.setConfig(conf);
//	LOGGER.debug("Session Established, for user ["+user+"]");
	boolean isConnected = false;
	if(session!=null){
		session.connect();
		isConnected = session.isConnected();
		LOGGER.debug("Session Connected, for user ["+user+"]");
		session.disconnect();
	}
	return isConnected;
}
 
Example 5
Source File: SFTPOperationHandler.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
private Session getSession(JSch jsch, URI uri, com.jcraft.jsch.UserInfo userInfo) throws IOException {
		UserInfo user = UserInfo.fromURI(uri);
		Session session;
		try {
			if (uri.getPort() == 0) session = jsch.getSession(user.getUser(), uri.getHost());
			else session = jsch.getSession(user.getUser(), uri.getHost(), uri.getPort() == -1 ? 22 : uri.getPort());

			// password will be given via UserInfo interface.
			session.setUserInfo(userInfo);
			// TODO proxy support
//			if (proxy != null) {
//				proxy.setUserPasswd(user, passwd);
//				session.setProxy(proxy);
//			}
			session.connect();
			return session;
		} catch (Exception e) {
//			if (proxy4 != null) {
//				try {
//					session.connect();
//					return;
//				} catch (JSchException e1) {}
//			}
			throw new IOException(e);
		}
	}
 
Example 6
Source File: DefaultSessionFactory.java    From jsch-extension with MIT License 6 votes vote down vote up
@Override
public Session newSession() throws JSchException {
    Session session = jsch.getSession( username, hostname, port );
    if ( config != null ) {
        for ( String key : config.keySet() ) {
            session.setConfig( key, config.get( key ) );
        }
    }
    if ( proxy != null ) {
        session.setProxy( proxy );
    }
    if ( password != null ) {
        session.setPassword( password );
    }
    if ( userInfo != null ) {
        session.setUserInfo( userInfo );
    }
    return session;
}
 
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: SftpClient.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Session createSftpSession(JSch jsch, boolean withUserInfo) throws JSchException {
    LOGGER.fine("Creating new SFTP session...");
    String host = configuration.getHost();
    int port = configuration.getPort();
    int timeout = configuration.getTimeout() * 1000;
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.log(Level.FINE, "Will connect to {0} [timeout: {1} ms]", new Object[] {host, timeout});
    }
    int keepAliveInterval = configuration.getKeepAliveInterval() * 1000;
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.log(Level.FINE, "Keep-alive interval is {0} ms", keepAliveInterval);
    }
    String username = configuration.getUserName();
    String password = configuration.getPassword();
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.log(Level.FINE, "Login as {0}", username);
    }
    Session session = jsch.getSession(username, host, port);
    if (StringUtils.hasText(password)) {
        session.setPassword(password);
    }
    // proxy
    setProxy(session, host);
    if (withUserInfo) {
        LOGGER.fine("Setting user info...");
        session.setUserInfo(new SftpUserInfo(configuration));
    }
    session.setTimeout(timeout);
    // keep-alive
    if (keepAliveInterval > 0) {
        session.setServerAliveInterval(keepAliveInterval);
    }
    return session;
}
 
Example 9
Source File: RemoteLauncherCommands.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Connect to a remote host via SSH and execute a command.
 * 
 * @param host
 *          Host to connect to
 * @param user
 *          User to login with
 * @param password
 *          Password for the user
 * @param command
 *          Command to execute
 * @return The result of the command execution
 */
private Result executeSshCommand(final String host, final String user,
    final String password, final String command) {
  
  StringBuilder result = new StringBuilder();
  
  try {
    JSch jsch = new JSch();
    Session session = jsch.getSession(user, host, 22);
    session.setUserInfo(createUserInfo(password));
    session.connect(5000);

    ChannelExec channel = (ChannelExec) session.openChannel("exec");
    channel.setCommand(command);
    channel.setInputStream(null);
    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;
        result.append(new String(tmp, 0, i));
      }
      if (channel.isClosed()) {
        break;
      }
    }
    channel.disconnect();
    session.disconnect();
  } catch (Exception jex) {
    return createResult(Result.Status.ERROR, jex.getMessage());
  }
 
  return createResult(Result.Status.OK, result.toString());
}
 
Example 10
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 11
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 12
Source File: JGitConfigSessionFactory.java    From mOrgAnd with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void configure(OpenSshConfig.Host host, Session session) {
    session.setConfig("StrictHostKeyChecking", "no"); // TODO Find out how to enable strict host checking

    // TODO Delete me
    // String knownHostsLocation = "/sdcard/morg/known_hosts";
    // jSch.setKnownHosts(knownHostsLocation);

    CredentialsProvider provider = new JGitCredentialsProvider(username, password);
    session.setUserInfo(new CredentialsProviderUserInfo(session, provider));
}
 
Example 13
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 14
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 15
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;
}