Java Code Examples for com.jcraft.jsch.JSchException#getMessage()
The following examples show how to use
com.jcraft.jsch.JSchException#getMessage() .
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: SSHManager.java From pacbot with Apache License 2.0 | 6 votes |
private static void doCommonConstructorActions(String userName, String password, String connectionIP, String knownHostsFileName) { jschSSHChannel = new JSch(); try { jschSSHChannel.setKnownHosts(knownHostsFileName); } catch (JSchException jschX) { LOGGER.error(jschX.getMessage()); errorMessage = jschX.getMessage(); } strUserName = userName; strPassword = password; strConnectionIP = connectionIP; }
Example 2
Source File: SSHManager.java From pacbot with Apache License 2.0 | 6 votes |
public String connect() { String errorMessageStr = null; try { sesConnection = jschSSHChannel.getSession(strUserName, strConnectionIP, intConnectionPort); sesConnection.setPassword(strPassword); sesConnection.setConfig("StrictHostKeyChecking", "no"); // ANY PROXY SETTING [IF ANY] NEEDS TO BE ADDED HERE sesConnection.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password"); sesConnection.connect(intTimeOut); } catch (JSchException jschX) { LOGGER.error(jschX.getMessage()); errorMessageStr = jschX.getMessage(); } return errorMessageStr; }
Example 3
Source File: Scp.java From ant-ivy with Apache License 2.0 | 6 votes |
/** * Download a file from the remote server into an OutputStream * * @param remoteFile * Path and name of the remote file. * @param localTarget * OutputStream to store the data. * @throws IOException * in case of network problems * @throws RemoteScpException * in case of problems on the target system (connection ok) */ @SuppressWarnings("unused") public void get(String remoteFile, OutputStream localTarget) throws IOException, RemoteScpException { ChannelExec channel = null; if (remoteFile == null || localTarget == null) { throw new IllegalArgumentException("Null argument."); } String cmd = "scp -p -f " + remoteFile; try { channel = getExecChannel(); channel.setCommand(cmd); receiveStream(channel, remoteFile, localTarget); channel.disconnect(); } catch (JSchException e) { if (channel != null) { channel.disconnect(); } throw new IOException("Error during SCP transfer. " + e.getMessage(), e); } }
Example 4
Source File: Scp.java From ant-ivy with Apache License 2.0 | 6 votes |
/** * Initiates an SCP sequence but stops after getting fileinformation header * * @param remoteFile * to get information for * @return the file information got * @throws IOException * in case of network problems * @throws RemoteScpException * in case of problems on the target system (connection ok) */ public FileInfo getFileinfo(String remoteFile) throws IOException, RemoteScpException { ChannelExec channel = null; FileInfo fileInfo = null; if (remoteFile == null) { throw new IllegalArgumentException("Null argument."); } String cmd = "scp -p -f \"" + remoteFile + "\""; try { channel = getExecChannel(); channel.setCommand(cmd); fileInfo = receiveStream(channel, remoteFile, null); channel.disconnect(); } catch (JSchException e) { throw new IOException("Error during SCP transfer. " + e.getMessage(), e); } finally { if (channel != null) { channel.disconnect(); } } return fileInfo; }
Example 5
Source File: JGitSshSessionFactory.java From netbeans with Apache License 2.0 | 5 votes |
private boolean setupJSch (FS fs, String host, CredentialItem.StringType identityFile, URIish uri, boolean preferAgent) throws TransportException { boolean agentUsed; if (sshConfig == null) { sshConfig = OpenSshConfig.get(fs); } final OpenSshConfig.Host hc = sshConfig.lookup(host); try { JSch jsch = getJSch(hc, fs); agentUsed = setupJSchIdentityRepository(jsch, identityFile.getValue(), preferAgent); } catch (JSchException ex) { throw new TransportException(uri, ex.getMessage(), ex); } return agentUsed; }
Example 6
Source File: JschSupport.java From netbeans with Apache License 2.0 | 5 votes |
private synchronized static ChannelStreams start(final JSchWorker<ChannelStreams> worker, final ExecutionEnvironment env, final int attempts) throws IOException, JSchException, InterruptedException { int retry = attempts; while (retry-- > 0) { try { return worker.call(); } catch (JSchException ex) { String message = ex.getMessage(); Throwable cause = ex.getCause(); if (cause != null && cause instanceof NullPointerException) { // Jsch bug... retry? log.log(Level.INFO, "JSch exception opening channel to " + env + ". Retrying", ex); // NOI18N } else if ("java.io.InterruptedIOException".equals(message)) { // NOI18N log.log(Level.INFO, "JSch exception opening channel to " + env + ". Retrying in 0.5 seconds", ex); // NOI18N try { Thread.sleep(500); } catch (InterruptedException ex1) { Thread.currentThread().interrupt(); break; } } else if ("channel is not opened.".equals(message)) { // NOI18N log.log(Level.INFO, "JSch exception opening channel to " + env + ". Reconnecting and retrying", ex); // NOI18N // Now reconnect disconnects old session and creates new, so this might help ConnectionManagerAccessor.getDefault().reconnect(env); } else { throw ex; } } catch (NullPointerException npe) { // Jsch bug... retry? ;) log.log(Level.FINE, "Exception from JSch", npe); // NOI18N } } throw new IOException("Failed to execute " + worker.toString()); // NOI18N }
Example 7
Source File: JSchChannelsSupport.java From netbeans with Apache License 2.0 | 4 votes |
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 8
Source File: GitSshSessionFactory.java From orion.server with Eclipse Public License 1.0 | 4 votes |
@Override public RemoteSession getSession(URIish uri, CredentialsProvider credentialsProvider, FS fs, int tms) throws TransportException { int port = uri.getPort(); String user = uri.getUser(); String pass = uri.getPass(); if (credentialsProvider instanceof GitCredentialsProvider) { if (port <= 0) port = SSH_PORT; GitCredentialsProvider cp = (GitCredentialsProvider) credentialsProvider; if (user == null) { CredentialItem.Username u = new CredentialItem.Username(); if (cp.supports(u) && cp.get(cp.getUri(), u)) { user = u.getValue(); } } if (pass == null) { CredentialItem.Password p = new CredentialItem.Password(); if (cp.supports(p) && cp.get(cp.getUri(), p)) { pass = new String(p.getValue()); } } try { final SessionHandler session = new SessionHandler(user, uri.getHost(), port, cp.getKnownHosts(), cp.getPrivateKey(), cp.getPublicKey(), cp.getPassphrase()); if (pass != null) session.setPassword(pass); if (!credentialsProvider.isInteractive()) { session.setUserInfo(new CredentialsProviderUserInfo(session.getSession(), credentialsProvider)); } session.connect(tms); return new JschSession(session.getSession(), uri); } catch (JSchException e) { throw new TransportException(uri, e.getMessage(), e); } } return null; }
Example 9
Source File: MultiUserSshSessionFactory.java From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License | 4 votes |
@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 10
Source File: SshCache.java From ant-ivy with Apache License 2.0 | 4 votes |
/** * 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 11
Source File: Scp.java From ant-ivy with Apache License 2.0 | 4 votes |
/** * Copy a local file to a remote site, uses the specified mode when creating the file on the * remote side. * * @param localFile * Path and name of local file. Must be absolute. * @param remoteTargetDir * Remote target directory where the file has to end up (optional) * @param remoteTargetName * file name to use on the target system * @param mode * a four digit string (e.g., 0644, see "man chmod", "man open") * @throws IOException * in case of network problems * @throws RemoteScpException * in case of problems on the target system (connection ok) */ @SuppressWarnings("unused") public void put(String localFile, String remoteTargetDir, String remoteTargetName, String mode) throws IOException, RemoteScpException { ChannelExec channel = null; if (localFile == null || remoteTargetName == null) { throw new IllegalArgumentException("Null argument."); } if (mode != null) { if (mode.length() != MODE_LENGTH) { throw new IllegalArgumentException("Invalid mode."); } for (char c : mode.toCharArray()) { if (!Character.isDigit(c)) { throw new IllegalArgumentException("Invalid mode."); } } } String cmd = "scp -t "; if (mode != null) { cmd += "-p "; } if (remoteTargetDir != null && remoteTargetDir.length() > 0) { cmd += "-d " + remoteTargetDir; } try { channel = getExecChannel(); channel.setCommand(cmd); sendFile(channel, localFile, remoteTargetName, mode); channel.disconnect(); } catch (JSchException e) { if (channel != null) { channel.disconnect(); } throw new IOException("Error during SCP transfer." + e.getMessage(), e); } }