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

The following examples show how to use com.jcraft.jsch.session#isConnected() . 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: MultiThread.java    From EasyXMS with Apache License 2.0 6 votes vote down vote up
/**
 * 使用已经连接的会话开始多线程
 * @param session_pool 会话池
 */
public void startMultiThread(HashMap<String, Session> session_pool){

    int host_num = session_pool.size();
    CountDownLatch wait_thread_run_end = new CountDownLatch(host_num);
    ExecCommand.setCountDownLatch(wait_thread_run_end); //设置线程同步计数器的数目

    //初始化用于存放线程的列表
    ArrayList<Thread> threadArrayList = new ArrayList<Thread>();
    ExecCommand.setIs_use_session_pool(1);
    for (String ip : session_pool.keySet()){
        Session session = session_pool.get(ip);
        if (session.isConnected()){
            threadArrayList.add(new Thread(new ExecCommand(ip,session)));
        } else {
            HelpPrompt.printIPSessionAlreadyDisconnect(ip);
        }
    }
    threadControl(threadArrayList, wait_thread_run_end);
}
 
Example 2
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 3
Source File: SshUtil.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Executes SSH behavior.
 * @param sshAccessInfo SSH Access information
 * @param behavior SSH behavior
 * @param <R> Return type of SSH behavior
 * @return return of SSH behavior
 * @throws WorkflowException workflow exception
 */
public static <R> R exec(SshAccessInfo sshAccessInfo, SshBehavior<R> behavior)
        throws WorkflowException {

    check(sshAccessInfo != null, "Invalid sshAccessInfo");
    Session session = connect(sshAccessInfo);
    if (session == null || !session.isConnected()) {
        log.error("Failed to get session for ssh:{}", sshAccessInfo);
        throw new WorkflowException("Failed to get session for ssh:" + sshAccessInfo);
    }

    try {
        return behavior.apply(session);
    } finally {
        disconnect(session);
    }
}
 
Example 4
Source File: SshCache.java    From ant-ivy with Apache License 2.0 6 votes vote down vote up
/**
 * Sets a session to a given combined key into the cache If an old session object already
 * exists, close and remove it
 *
 * @param user
 *            of the session
 * @param host
 *            of the session
 * @param port
 *            of the session
 * @param newSession
 *            Session to save
 */
private void setSession(String user, String host, int port, Session newSession) {
    Entry entry = uriCacheMap.get(createCacheKey(user, host, port));
    Session oldSession = null;
    if (entry != null) {
        oldSession = entry.getSession();
    }
    if (oldSession != null && !oldSession.equals(newSession) && oldSession.isConnected()) {
        entry.releaseChannelSftp();
        String oldhost = oldSession.getHost();
        Message.verbose(":: SSH :: closing ssh connection from " + oldhost + "...");
        oldSession.disconnect();
        Message.verbose(":: SSH :: ssh connection closed from " + oldhost);
    }
    if (newSession == null && entry != null) {
        uriCacheMap.remove(createCacheKey(user, host, port));
        if (entry.getSession() != null) {
            sessionCacheMap.remove(entry.getSession());
        }
    } else {
        Entry newEntry = new Entry(newSession, user, host, port);
        uriCacheMap.put(createCacheKey(user, host, port), newEntry);
        sessionCacheMap.put(newSession, newEntry);
    }
}
 
Example 5
Source File: SSHHandlerTarget.java    From embeddedlinux-jvmdebugger-intellij with Apache License 2.0 6 votes vote down vote up
/**
 * Authenticates and connects to remote target via ssh protocol
 * @param session
 * @return
 */
@SneakyThrows({RuntimeConfigurationException.class})
private Session connect(Session session) {
    if (!session.isConnected()) {
        session = EmbeddedSSHClient.builder()
                .username(params.getUsername())
                .password(params.getPassword())
                .hostname(params.getHostname())
                .port(params.getSshPort())
                .build().get();
        if (!session.isConnected()) {
            setErrorOnUI(EmbeddedLinuxJVMBundle.getString("ssh.remote.error"));
            throw new RuntimeConfigurationException(EmbeddedLinuxJVMBundle.getString("ssh.remote.error"));
        } else {
            return session;
        }
    }
    return session;
}
 
Example 6
Source File: SSHConnectionValidator.java    From embeddedlinux-jvmdebugger-intellij with Apache License 2.0 6 votes vote down vote up
/**
 * Can connect to remote target
 *
 * @return status
 */
public SSHConnectionState checkSSHConnection() {
    try {
        EmbeddedSSHClient sshClient = EmbeddedSSHClient
                .builder()
                .port(port)
                .username(username)
                .password(password)
                .hostname(ip)
                .key(key)
                .useKey(useKey)
                .build();
        Session session = sshClient.get();
        return new SSHConnectionValidator.SSHConnectionState(session.isConnected(), null);
    } catch (Exception e) {
        return new SSHConnectionValidator.SSHConnectionState(false, e.getMessage());
    }
}
 
Example 7
Source File: JSchChannelsSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Session findFreeSession() {
    for (Entry<Session, AtomicInteger> entry : sessions.entrySet()) {
        Session s = entry.getKey();
        AtomicInteger availableChannels = entry.getValue();
        if (s.isConnected() && availableChannels.get() > 0) {
            log.log(Level.FINE, "availableChannels == {0}", new Object[]{availableChannels.get()}); // NOI18N
            int remains = availableChannels.decrementAndGet();
            log.log(Level.FINE, "Reuse session [{0}]. {1} channels remain...", new Object[]{System.identityHashCode(s), remains}); // NOI18N
            return s;
        }
    }

    return null;
}
 
Example 8
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 9
Source File: CacheUtils.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
/**
 * Get an opened SSH session from cache (Operation Orchestration session).
 *
 * @param sessionResource The session resource.
 * @return the SFTP Copier
 */
public static SFTPCopier getFromCache(SessionResource<Map<String, SFTPConnection>> sessionResource, String sessionId) {
    Session savedSession = CacheUtils.getSftpSession(sessionResource, sessionId);
    if (savedSession != null && savedSession.isConnected()) {
        Channel savedChannel = CacheUtils.getSftpChannel(sessionResource, sessionId);
        return new SFTPCopier(savedSession,savedChannel);
    }
    return null;
}
 
Example 10
Source File: KeyedPooledJschChannelFactory.java    From jwala with Apache License 2.0 5 votes vote down vote up
@Override
public Channel create(final ChannelSessionKey key) throws Exception {
    Session session;
    synchronized (sessionMap) {
        session = sessionMap.get(key);
        if (session == null || !session.isConnected()) {
            session = prepareSession(key.remoteSystemConnection);
            session.connect();
            sessionMap.put(key, session);
            LOGGER.debug("session {} created and connected!", key);
        }
    }
    return session.openChannel(key.channelType.getChannelType());
}
 
Example 11
Source File: JSchChannelsSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public String getConfig(String key) {
    for (Session s : sessions.keySet()) {
        if (s.isConnected()) {
            return s.getConfig(key);
        }
    }
    return null;
}
 
Example 12
Source File: JSchChannelsSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void delPortForwardingL(int lport) throws JSchException {
    portForwarding.removePortForwardingInfoL(lport);
    for (Session s : sessions.keySet()) {
        if (s.isConnected()) {
            s.delPortForwardingL(lport);
        }
    }
}
 
Example 13
Source File: JSchChannelsSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void delPortForwardingR(int rport) throws JSchException {
    portForwarding.removePortForwardingInfoR(rport);
    for (Session s : sessions.keySet()) {
        if (s.isConnected()) {
            s.delPortForwardingR(rport);
        }
    }
}
 
Example 14
Source File: CacheUtils.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
/**
 * Get an opened SSH session from cache (Operation Orchestration session).
 *
 * @param sessionResource The session resource.
 * @return the SSH service
 */
public static SSHService getFromCache(SessionResource<Map<String, SSHConnection>> sessionResource, String sessionId) {
    Session savedSession = CacheUtils.getSshSession(sessionResource, sessionId);
    if (savedSession != null && savedSession.isConnected()) {
        Channel savedChannel = CacheUtils.getSshChannel(sessionResource, sessionId);
        return new SSHServiceImpl(savedSession, savedChannel);
    }

    return null;
}
 
Example 15
Source File: JSchChannelsSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public int setPortForwardingL(int lport, String host, int rport) throws JSchException {
    portForwarding.addPortForwardingInfoL(lport, host, rport);
    for (Session s : sessions.keySet()) {
        if (s.isConnected()) {
            return s.setPortForwardingL(lport, host, rport);
        }
    }
    return -1;
}
 
Example 16
Source File: JSchChannelsSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public String getServerVersion() {
    for (Session s : sessions.keySet()) {
        if (s.isConnected()) {
            return s.getServerVersion();
        }
    }
    return null;
}
 
Example 17
Source File: JSchChannelsSupport.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public boolean isConnected() {
    // ConcurrentHashMap.keySet() never throws ConcurrentModificationException
    for (Session s : sessions.keySet()) {
        if (s.isConnected()) {
            return true;
        }
    }

    return false;
}
 
Example 18
Source File: MultiUserSshSessionFactory.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public synchronized RemoteSession getSession(URIish uri,
                                             CredentialsProvider credentialsProvider, FS fs, int tms)
        throws TransportException {

    String user = uri.getUser();
    final String pass = uri.getPass();
    String host = uri.getHost();
    int port = uri.getPort();

    try {
        if (config == null)
            config = OpenSshConfig.get(fs);

        final OpenSshConfig.Host hc = config.lookup(host);
        host = hc.getHostName();
        if (port <= 0)
            port = hc.getPort();
        if (user == null)
            user = hc.getUser();

        Session session = createSession(credentialsProvider, fs, user,
                pass, host, port, hc);

        int retries = 0;
        while (!session.isConnected()) {
            try {
                retries++;
                session.connect(tms);
            } catch (JSchException e) {
                session.disconnect();
                session = null;
                // Make sure our known_hosts is not outdated
                knownHosts(getJSch(credentialsProvider, hc, fs), fs);

                if (isAuthenticationCanceled(e)) {
                    throw e;
                } else if (isAuthenticationFailed(e)
                        && credentialsProvider != null) {
                    // if authentication failed maybe credentials changed at
                    // the remote end therefore reset credentials and retry
                    if (retries < 3) {
                        credentialsProvider.reset(uri);
                        session = createSession(credentialsProvider, fs,
                                user, pass, host, port, hc);
                    } else
                        throw e;
                } else if (retries >= hc.getConnectionAttempts()) {
                    throw e;
                } else {
                    try {
                        Thread.sleep(1000);
                        session = createSession(credentialsProvider, fs,
                                user, pass, host, port, hc);
                    } catch (InterruptedException e1) {
                        throw new TransportException(
                                JGitText.get().transportSSHRetryInterrupt,
                                e1);
                    }
                }
            }
        }

        return new JschSession(session, uri);

    } catch (JSchException je) {
        final Throwable c = je.getCause();
        if (c instanceof UnknownHostException)
            throw new TransportException(uri, JGitText.get().unknownHost);
        if (c instanceof ConnectException)
            throw new TransportException(uri, c.getMessage());
        throw new TransportException(uri, je.getMessage(), je);
    }

}
 
Example 19
Source File: SshUtil.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Closes a connection.
 *
 * @param session session ssh session
 */
public static void disconnect(Session session) {
    if (session.isConnected()) {
        session.disconnect();
    }
}
 
Example 20
Source File: JschExecutor.java    From jumbune with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void closeSession(Session session){
	if(session!=null && session.isConnected()){
		session.disconnect();
	}
}