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

The following examples show how to use com.jcraft.jsch.session#setTimeout() . 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: 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 3
Source File: TelemetryTools.java    From anx with Apache License 2.0 5 votes vote down vote up
List<String> execSSHCommand(String command) throws JSchException, IOException {
    JSch jSch = new JSch();

    Window loadingWindow = showLoadingWindow("SSH exec: " + command);

    Session session = jSch.getSession(view.username, view.host, 22);
    session.setDaemonThread(true);
    session.setTimeout(3600000);
    session.setServerAliveInterval(15000);
    session.setConfig("StrictHostKeyChecking", "no");
    session.setPassword(view.password);
    try {
        session.connect();

        Channel channel = session.openChannel("exec");
        ((ChannelExec)channel).setCommand(command);
        channel.setInputStream(null);
        InputStream input = channel.getInputStream();
        channel.connect();
        List<String> result = new BufferedReader(new InputStreamReader(input)).lines().collect(Collectors.toList());

        channel.disconnect();
        session.disconnect();
        return result;
    } finally {
        loadingWindow.close();
    }
}
 
Example 4
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 5
Source File: SshProxy.java    From ssh-proxy with Apache License 2.0 5 votes vote down vote up
public int connect(String sshTunnelHost, String host, int port, int localPort) {
	Assert.notNull(sshTunnelHost, "sshTunnelHost must not be null");
	Assert.notNull(host, "host must not be null");
	Assert.isTrue(port > 0, "illegal port: " + port);
	Assert.isTrue(localPort >= 0, "illegal local port: " + localPort);

	log.debug("tunneling to {}:{} via {}", host, port, sshTunnelHost);

	try {
		sshConfiguration.addIdentity(sshTunnelHost);

		SshProxyConfig proxyConfig = sshConfiguration.getProxyConfiguration(sshTunnelHost);
		if (proxyConfig == null) {
			return directConnect(sshTunnelHost, host, port, localPort);
		}

		int jumpPort = connect(proxyConfig);

		String hostUser = sshConfiguration.getHostUser(sshTunnelHost);
		String jumpHost = proxyConfig.getJumpHost();
		Session jumpHostSession = sshConfiguration.openSession(hostUser, jumpHost, jumpPort);
		String hostname = sshConfiguration.getHostName(sshTunnelHost);
		jumpHostSession.setHostKeyAlias(hostname);
		sshSessions.push(jumpHostSession);
		jumpHostSession.setTimeout(timeoutMillis);
		jumpHostSession.connect(timeoutMillis);

		log.debug("[{}] connected via {}@localhost:{}", sshTunnelHost, hostUser, jumpPort);

		return addLocalPortForwarding(sshTunnelHost, jumpHostSession, host, port, localPort);
	} catch (Exception e) {
		throw new SshProxyRuntimeException("Failed to create SSH tunnel to " + host + " via " + sshTunnelHost, e);
	}
}
 
Example 6
Source File: SshProxy.java    From ssh-proxy with Apache License 2.0 5 votes vote down vote up
private int directConnect(String jumpHost, String targetHost, int targetPort, int localPort) throws JSchException {
	Session jumpHostSession = sshConfiguration.openSession(jumpHost);
	sshSessions.add(jumpHostSession);
	jumpHostSession.setTimeout(timeoutMillis);
	try {
		jumpHostSession.connect(timeoutMillis);
	} catch (JSchException e) {
		log.debug("Failed to connect to {} via {}", targetHost, jumpHost, e);
		throw new SshProxyRuntimeException("Failed to connect to " + targetHost + " via " + jumpHost);
	}

	log.debug("[{}] connected", jumpHost);

	return addLocalPortForwarding(jumpHost, jumpHostSession, targetHost, targetPort, localPort);
}
 
Example 7
Source File: SFtpUtil.java    From Aria with Apache License 2.0 5 votes vote down vote up
/**
 * 创建jsch 的session
 *
 * @param threadId 线程id,默认0
 * @throws JSchException
 * @throws UnsupportedEncodingException
 */
public Session getSession(FtpUrlEntity entity, int threadId) throws JSchException,
    UnsupportedEncodingException {

  JSch jSch = new JSch();

  IdEntity idEntity = entity.idEntity;

  if (idEntity.prvKey != null) {
    if (idEntity.pubKey == null) {
      jSch.addIdentity(idEntity.prvKey,
          entity.password == null ? null : idEntity.prvPass.getBytes("UTF-8"));
    } else {
      jSch.addIdentity(idEntity.prvKey, idEntity.pubKey,
          entity.password == null ? null : idEntity.prvPass.getBytes("UTF-8"));
    }
  }

  setKnowHost(jSch, entity);

  Session session;
  if (TextUtils.isEmpty(entity.user)) {
    session = jSch.getSession(null, entity.hostName, Integer.parseInt(entity.port));
  } else {
    session = jSch.getSession(entity.user, entity.hostName, Integer.parseInt(entity.port));
  }
  if (!TextUtils.isEmpty(entity.password)) {
    session.setPassword(entity.password);
  }
  Properties config = new Properties();

  // 不检查公钥,需要在connect之前配置,但是不安全,no 模式会自动将配对信息写入know_host文件
  config.put("StrictHostKeyChecking", "no");
  session.setConfig(config);// 为Session对象设置properties
  session.setTimeout(5000);// 设置超时
  session.setIdentityRepository(jSch.getIdentityRepository());
  session.connect();
  SFtpSessionManager.getInstance().addSession(session, threadId);
  return session;
}
 
Example 8
Source File: JSchSshSession.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Connect to remote SSH endpoint specified by {@code url}.
 *
 * @throws JSchException if we fail to open the connection.
 */
JSchSshSession create(JSch jsch, URI uri) throws JSchException {
  RdeUploadUrl url = RdeUploadUrl.create(uri);
  logger.atInfo().log("Connecting to SSH endpoint: %s", url);
  Session session = jsch.getSession(
      url.getUser().orElse("domain-registry"),
      url.getHost(),
      url.getPort());
  if (url.getPass().isPresent()) {
    session.setPassword(url.getPass().get());
  }
  session.setTimeout((int) sshTimeout.getMillis());
  session.connect((int) sshTimeout.getMillis());
  return new JSchSshSession(session, url, (int) sshTimeout.getMillis());
}