com.jcraft.jsch.UserInfo Java Examples

The following examples show how to use com.jcraft.jsch.UserInfo. 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: 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 #2
Source File: SFTPEnvironmentTest.java    From sftp-fs with Apache License 2.0 6 votes vote down vote up
@Test
public void testInitializeSessionFull() throws IOException, JSchException {
    SFTPEnvironment env = new SFTPEnvironment();
    initializeFully(env);

    Session session = mock(Session.class);
    env.initialize(session);

    verify(session).setProxy((Proxy) env.get("proxy"));
    verify(session).setUserInfo((UserInfo) env.get("userInfo"));
    verify(session).setPassword(new String((char[]) env.get("password")));
    verify(session).setConfig((Properties) env.get("config"));
    verify(session).setSocketFactory((SocketFactory) env.get("socketFactory"));
    verify(session).setTimeout((int) env.get("timeOut"));
    verify(session).setClientVersion((String) env.get("clientVersion"));
    verify(session).setHostKeyAlias((String) env.get("hostKeyAlias"));
    verify(session).setServerAliveInterval((int) env.get("serverAliveInterval"));
    verify(session).setServerAliveCountMax((int) env.get("serverAliveCountMax"));
    verifyNoMoreInteractions(session);
}
 
Example #3
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 #4
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 #5
Source File: SessionFactory.java    From jsch-extension with MIT License 5 votes vote down vote up
protected SessionFactoryBuilder( JSch jsch, String username, String hostname, int port, Proxy proxy, Map<String, String> config, UserInfo userInfo ) {
    this.jsch = jsch;
    this.username = username;
    this.hostname = hostname;
    this.port = port;
    this.proxy = proxy;
    this.config = config;
    this.userInfo = userInfo;
}
 
Example #6
Source File: SftpClient.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void add( HostKey hostkey, UserInfo ui ) {

    Set<byte[]> keys = knownHostsMap.get(hostkey.getHost());
    if (keys == null) {
        keys = new HashSet<>();
    }
    keys.add(hostkey.getKey().getBytes());
    knownHostsMap.put(hostkey.getHost(), keys);

}
 
Example #7
Source File: HMSshSession.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Constructor.
 * 
 * @param host host for the session.
 * @param user the user.
 * @param pwd the password.
 * @throws Exception
 */
public HMSshSession( String host, int port, String user, String pwd ) throws Exception {
    session = jsch.getSession(user, host, port);
    UserInfo ui = new HMUserInfo(pwd);
    session.setUserInfo(ui);
    session.setPassword(ui.getPassword().getBytes());
    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);

    try {
        String doProxy = SshUtilities.getPreference(HM_PREF_PROXYCHECK, "false");
        if (Boolean.parseBoolean(doProxy)) {
            String proxyHost = SshUtilities.getPreference(HM_PREF_PROXYHOST, "");
            String proxyPort = SshUtilities.getPreference(HM_PREF_PROXYPORT, "");
            String proxyUser = SshUtilities.getPreference(HM_PREF_PROXYUSER, "");
            String proxyPwd = SshUtilities.getPreference(HM_PREF_PROXYPWD, "");

            int proxPort = Integer.parseInt(proxyPort);
            ProxyHTTP proxyHTTP = new ProxyHTTP(proxyHost, proxPort);
            if (proxyUser.length() > 0 && proxyPwd.length() > 0) {
                proxyHTTP.setUserPasswd(proxyUser, proxyPwd);
            }
            session.setProxy(proxyHTTP);
        }
    } catch (Exception e) {
        Logger.INSTANCE.insertError("HMSshSession", "Error setting proxy", e);
    }

    session.connect(3000);
}
 
Example #8
Source File: PooledSFTPConnection.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Session getSession(JSch jsch, String username, UserInfo password, Proxy[] proxies) throws IOException {
	assert (proxies != null) && (proxies.length > 0);
	
	Session session;
	try {
		if (authority.getPort() == 0) {
			session = jsch.getSession(username, authority.getHost());
		} else {
			session = jsch.getSession(username, authority.getHost(), authority.getPort() == -1 ? DEFAULT_PORT : authority.getPort());
		}

		// password will be given via UserInfo interface.
		session.setUserInfo(password);
		
		Exception exception = null;
		for (Proxy proxy: proxies) {
			if (proxy != null) {
				session.setProxy(proxy);
			}
			try {
				session.connect();
				return session;
			} catch (Exception e) {
				exception = e;
			}
		}
		
		throw exception;
	} catch (Exception e) {
		if (log.isDebugEnabled()) {
			ConnectionPool pool = ConnectionPool.getInstance();
			synchronized (pool) {
				log.debug(MessageFormat.format("Connection pool status: {0} idle, {1} active", pool.getNumIdle(), pool.getNumActive()));
			}
		}
		throw new IOException(e);
	}
}
 
Example #9
Source File: SshXpraConnector.java    From xpra-client with GNU General Public License v3.0 5 votes vote down vote up
public SshXpraConnector(XpraClient client, String host, String username, int port, UserInfo userInfo) {
	super(client);
	this.host = host;
	this.username = username;
	this.port = port;
	this.userInfo = userInfo;
	JSch.setConfig("compression_level", "0");
}
 
Example #10
Source File: PooledSFTPConnection.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Proxy[] getProxies() {
	String proxyString = authority.getProxyString();
	if (!StringUtils.isEmpty(proxyString)) {
		java.net.Proxy proxy = FileUtils.getProxy(authority.getProxyString());
		if ((proxy != null) && (proxy.type() != Type.DIRECT)) {
			URI proxyUri = URI.create(proxyString);
			String hostName = proxyUri.getHost();
			int port = proxyUri.getPort();
			String userInfo = proxyUri.getUserInfo();
			org.jetel.util.protocols.UserInfo proxyCredentials = null;
			if (userInfo != null) {
				proxyCredentials = new org.jetel.util.protocols.UserInfo(userInfo);
			}
			switch (proxy.type()) {
			case HTTP:
				ProxyHTTP proxyHttp = (port >= 0) ? new ProxyHTTP(hostName, port) : new ProxyHTTP(hostName);
				if (proxyCredentials != null) {
					proxyHttp.setUserPasswd(proxyCredentials.getUser(), proxyCredentials.getPassword());
				}
				return new Proxy[] {proxyHttp};
			case SOCKS:
				ProxySOCKS4 proxySocks4 = (port >= 0) ? new ProxySOCKS4(hostName, port) : new ProxySOCKS4(hostName);
				ProxySOCKS5 proxySocks5 = (port >= 0) ? new ProxySOCKS5(hostName, port) : new ProxySOCKS5(hostName);
				if (proxyCredentials != null) {
					proxySocks4.setUserPasswd(proxyCredentials.getUser(), proxyCredentials.getPassword());
					proxySocks5.setUserPasswd(proxyCredentials.getUser(), proxyCredentials.getPassword());
				}
				return new Proxy[] {proxySocks5, proxySocks4};
			case DIRECT:
				return new Proxy[1];
			}
		}
	}
	
	return new Proxy[1];
}
 
Example #11
Source File: KettleSftpFileSystemConfigBuilder.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
/**
 * Publicly expose a generic way to set parameters
 */
@Override
public void setParameter( FileSystemOptions opts, String name, String value, String fullParameterName,
  String vfsUrl ) throws IOException {
  if ( !fullParameterName.startsWith( "vfs.sftp" ) ) {
    // This is not an SFTP parameter. Delegate to the generic handler
    super.setParameter( opts, name, value, fullParameterName, vfsUrl );
  } else {
    // Check for the presence of a host in the full variable name
    try {
      // Parse server name from vfsFilename
      FileNameParser sftpFilenameParser = SftpFileNameParser.getInstance();
      URLFileName file = (URLFileName) sftpFilenameParser.parseUri( null, null, vfsUrl );

      if ( !parameterContainsHost( fullParameterName ) || fullParameterName.endsWith( file.getHostName() ) ) {
        // Match special cases for parameter names
        if ( name.equalsIgnoreCase( "AuthKeyPassphrase" ) ) {
          setParam( opts, UserInfo.class.getName(), new PentahoUserInfo( value ) );
        } else if ( name.equals( "identity" ) ) {

          IdentityInfo[] identities = (IdentityInfo[]) this.getParam( opts, IDENTITY_KEY );

          if ( identities == null ) {
            identities = new IdentityInfo[] { new IdentityInfo( new File( value ) ) };
          } else {
            // Copy, in a Java 5 friendly manner, identities into a larger array
            IdentityInfo[] temp = new IdentityInfo[identities.length + 1];
            System.arraycopy( identities, 0, temp, 0, identities.length );
            identities = temp;

            identities[identities.length - 1] = new IdentityInfo( new File( value ) );
          }
          setParam( opts, IDENTITY_KEY, identities );
        } else {
          super.setParameter( opts, name, value, fullParameterName, vfsUrl );
        }
      } else {
        // No host match found
        log.logDebug( "No host match found for: " + fullParameterName );
      }
    } catch ( IOException e ) {
      log.logError( "Failed to set VFS parameter: [" + fullParameterName + "] " + value, e );
    }
  }
}
 
Example #12
Source File: DefaultSessionFactory.java    From jsch-extension with MIT License 4 votes vote down vote up
@Override
public UserInfo getUserInfo() {
    return userInfo;
}
 
Example #13
Source File: SshConnectionImpl.java    From gerrit-events with MIT License 4 votes vote down vote up
@Override
public void add(HostKey hostkey, UserInfo ui) {
}
 
Example #14
Source File: SftpFsHelper.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
/**
 * Opens up a connection to specified host using the username. Connects to the source using a private key without
 * prompting for a password. This method does not support connecting to a source using a password, only by private
 * key
 * @throws org.apache.gobblin.source.extractor.filebased.FileBasedHelperException
 */
@Override
public void connect() throws FileBasedHelperException {

  String privateKey = PasswordManager.getInstance(this.state)
      .readPassword(this.state.getProp(ConfigurationKeys.SOURCE_CONN_PRIVATE_KEY));
  String password = PasswordManager.getInstance(this.state)
      .readPassword(this.state.getProp(ConfigurationKeys.SOURCE_CONN_PASSWORD));
  String knownHosts = this.state.getProp(ConfigurationKeys.SOURCE_CONN_KNOWN_HOSTS);

  String userName = this.state.getProp(ConfigurationKeys.SOURCE_CONN_USERNAME);
  String hostName = this.state.getProp(ConfigurationKeys.SOURCE_CONN_HOST_NAME);
  int port = this.state.getPropAsInt(ConfigurationKeys.SOURCE_CONN_PORT, ConfigurationKeys.SOURCE_CONN_DEFAULT_PORT);

  String proxyHost = this.state.getProp(ConfigurationKeys.SOURCE_CONN_USE_PROXY_URL);
  int proxyPort = this.state.getPropAsInt(ConfigurationKeys.SOURCE_CONN_USE_PROXY_PORT, -1);

  JSch.setLogger(new JSchLogger());
  JSch jsch = new JSch();

  log.info("Attempting to connect to source via SFTP with" + " privateKey: " + privateKey + " knownHosts: "
      + knownHosts + " userName: " + userName + " hostName: " + hostName + " port: " + port + " proxyHost: "
      + proxyHost + " proxyPort: " + proxyPort);

  try {

    if (!Strings.isNullOrEmpty(privateKey)) {
      List<IdentityStrategy> identityStrategies = ImmutableList.of(new LocalFileIdentityStrategy(),
          new DistributedCacheIdentityStrategy(), new HDFSIdentityStrategy());

      for (IdentityStrategy identityStrategy : identityStrategies) {
        if (identityStrategy.setIdentity(privateKey, jsch)) {
          break;
        }
      }
    }

    this.session = jsch.getSession(userName, hostName, port);
    this.session.setConfig("PreferredAuthentications", "publickey,password");

    if (Strings.isNullOrEmpty(knownHosts)) {
      log.info("Known hosts path is not set, StrictHostKeyChecking will be turned off");
      this.session.setConfig("StrictHostKeyChecking", "no");
    } else {
      jsch.setKnownHosts(knownHosts);
    }

    if (!Strings.isNullOrEmpty(password)) {
      this.session.setPassword(password);
    }

    if (proxyHost != null && proxyPort >= 0) {
      this.session.setProxy(new ProxyHTTP(proxyHost, proxyPort));
    }

    UserInfo ui = new MyUserInfo();
    this.session.setUserInfo(ui);
    this.session.setDaemonThread(true);
    this.session.connect();

    log.info("Finished connecting to source");
  } catch (JSchException e) {
    if (this.session != null) {
      this.session.disconnect();
    }
    log.error(e.getMessage(), e);
    throw new FileBasedHelperException("Cannot connect to SFTP source", e);
  }
}
 
Example #15
Source File: SFTPEnvironmentTest.java    From sftp-fs with Apache License 2.0 4 votes vote down vote up
@Override
public void add(HostKey hostkey, UserInfo ui) {
    // does nothing
}
 
Example #16
Source File: TrustAllHostKeyRepository.java    From sftp-fs with Apache License 2.0 4 votes vote down vote up
@Override
public void add(HostKey hostkey, UserInfo ui) {
    // skip
}
 
Example #17
Source File: SessionHandler.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
public void setUserInfo(UserInfo userInfo) {
	session.setUserInfo(userInfo);
}
 
Example #18
Source File: LazyKnownHosts.java    From orion.server with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public void add(HostKey hostkey, UserInfo ui) {
	repo.add(hostkey, ui);
}
 
Example #19
Source File: GitWithAuth.java    From centraldogma with Apache License 2.0 4 votes vote down vote up
@Override
public void add(HostKey hostkey, UserInfo ui) {}
 
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;
	}
 
Example #21
Source File: SFTPEnvironment.java    From sftp-fs with Apache License 2.0 2 votes vote down vote up
/**
 * Stores the user info to use.
 *
 * @param userInfo The user info to use.
 * @return This object.
 */
public SFTPEnvironment withUserInfo(UserInfo userInfo) {
    put(USER_INFO, userInfo);
    return this;
}
 
Example #22
Source File: DefaultSessionFactory.java    From jsch-extension with MIT License 2 votes vote down vote up
/**
 * Sets the {@code UserInfo} for use with {@code keyboard-interactive}
 * authentication.  This may be useful, however, setting the password
 * with {@link #setPassword(String)} is likely sufficient.
 * 
 * @param userInfo
 * 
 * @see <a
 *      href="http://www.jcraft.com/jsch/examples/UserAuthKI.java.html">Keyboard
 *      Interactive Authentication Example</a>
 */
public void setUserInfo( UserInfo userInfo ) {
    this.userInfo = userInfo;
}
 
Example #23
Source File: SessionFactory.java    From jsch-extension with MIT License 2 votes vote down vote up
/**
 * Returns the userInfo that sessions built by this factory will connect
 * with.
 * 
 * @return The userInfo
 */
public UserInfo getUserInfo();
 
Example #24
Source File: SessionFactory.java    From jsch-extension with MIT License 2 votes vote down vote up
/**
 * Replaces the current userInfo with <code>userInfo</code>
 * 
 * @param userInfo
 *            The new userInfo
 * @return This builder
 */
public SessionFactoryBuilder setUserInfo( UserInfo userInfo ) {
    this.userInfo = userInfo;
    return this;
}
 
Example #25
Source File: SftpFileSystemConfigBuilder.java    From commons-vfs with Apache License 2.0 2 votes vote down vote up
/**
 * @param opts The FileSystem options.
 * @return The UserInfo.
 * @see #setUserInfo
 */
public UserInfo getUserInfo(final FileSystemOptions opts) {
    return (UserInfo) this.getParam(opts, UserInfo.class.getName());
}
 
Example #26
Source File: SftpFileSystemConfigBuilder.java    From commons-vfs with Apache License 2.0 2 votes vote down vote up
/**
 * Sets the Jsch UserInfo class to use.
 *
 * @param opts The FileSystem options.
 * @param info User information.
 */
public void setUserInfo(final FileSystemOptions opts, final UserInfo info) {
    this.setParam(opts, UserInfo.class.getName(), info);
}