Java Code Examples for com.jcraft.jsch.Session#setConfig()
The following examples show how to use
com.jcraft.jsch.Session#setConfig() .
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: MultiUserSshSessionFactory.java From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License | 7 votes |
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 2
Source File: EmbeddedSSHClient.java From embeddedlinux-jvmdebugger-intellij with Apache License 2.0 | 7 votes |
/** * 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 3
Source File: GitContentRepositoryHelper.java From studio with GNU General Public License v3.0 | 6 votes |
private SshSessionFactory getSshSessionFactory(String remotePrivateKey, final Path tempKey) { try { Files.write(tempKey, remotePrivateKey.getBytes()); SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() { @Override protected void configure(OpenSshConfig.Host hc, Session session) { Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); } @Override protected JSch createDefaultJSch(FS fs) throws JSchException { JSch defaultJSch = super.createDefaultJSch(fs); defaultJSch.addIdentity(tempKey.toAbsolutePath().toString()); return defaultJSch; } }; return sshSessionFactory; } catch (IOException e) { logger.error("Failed to create private key for SSH connection.", e); } return null; }
Example 4
Source File: SFTPUtils.java From axelor-open-suite with GNU Affero General Public License v3.0 | 6 votes |
/** * Returns a new session created with given {@code host}, {@code port}, {@code username}, {@code * password}, {@code privateKey} and optional {@code passphrase}. * * @throws JSchException if {@code username} or {@code host} are invalid, or if {@code passphrase} * is not right. */ public static Session createSession( String host, int port, String username, String password, String privateKey, String passphrase) throws JSchException { JSch jsch = new JSch(); if (privateKey != null) { jsch.addIdentity(privateKey, passphrase); } Session session = jsch.getSession(username, host, port); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); return session; }
Example 5
Source File: JschUtil.java From jumbune with GNU Lesser General Public License v3.0 | 6 votes |
/** * 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 6
Source File: SftpVerifierExtension.java From syndesis with Apache License 2.0 | 6 votes |
private static void verifyCredentials(ResultBuilder builder, Map<String, Object> parameters) { final String host = ConnectorOptions.extractOption(parameters, "host"); final Integer port = ConnectorOptions.extractOptionAndMap(parameters, "port", Integer::parseInt, 22); final String userName = ConnectorOptions.extractOption(parameters, "username"); final String password = ConnectorOptions.extractOption(parameters, "password", ""); JSch jsch = new JSch(); Session session = null; try { session = jsch.getSession(userName, host, port); session.setConfig("StrictHostKeyChecking", "no"); session.setPassword(password); session.connect(); } catch (JSchException e) { builder.error(ResultErrorBuilder .withCodeAndDescription(VerificationError.StandardCode.AUTHENTICATION, e.getMessage()).build()); } finally { if (session != null) { session.disconnect(); jsch = null; } } }
Example 7
Source File: RemoteCredentialsSupport.java From kork with Apache License 2.0 | 5 votes |
static RemoteCredentials getRemoteCredentials( String command, String user, String host, int port) { RemoteCredentials remoteCredentials = new RemoteCredentials(); try { Session session = jsch.getSession(user, host, port); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); config.put("PreferredAuthentications", "publickey"); config.put("HashKnownHosts", "yes"); session.setConfig(config); session.setPassword(""); session.connect(); ChannelExec channel = (ChannelExec) session.openChannel("exec"); InputStream is = channel.getInputStream(); channel.setCommand(command); channel.connect(); String output = IOUtils.toString(is); log.debug("Remote credentials: {}", output); channel.disconnect(); session.disconnect(); output = output.replace("\n", ""); remoteCredentials = objectMapper.readValue(output, RemoteCredentials.class); } catch (Exception e) { log.error("Remote SSH execution failed.", e); } return remoteCredentials; }
Example 8
Source File: SshLocalhostExample.java From ExpectIt with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws JSchException, IOException { JSch jSch = new JSch(); Session session = jSch.getSession(System.getenv("USER"), "localhost"); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); jSch.addIdentity(System.getProperty("user.home") + "/.ssh/id_rsa"); session.setConfig(config); session.connect(); Channel channel = session.openChannel("shell"); channel.connect(); Expect expect = new ExpectBuilder() .withOutput(channel.getOutputStream()) .withInputs(channel.getInputStream(), channel.getExtInputStream()) .build(); try { expect.expect(contains("$")); expect.sendLine("pwd"); System.out.println( "pwd1:" + expect.expect(times(2, contains("\n"))) .getResults() .get(1) .getBefore()); expect.sendLine("pwd"); // a regexp which captures the output of pwd System.out.println("pwd2:" + expect.expect(regexp("(?m)\\n([^\\n]*)\\n")).group(1)); expect.expect(contains("$")); expect.sendLine("ls -l"); // skipping the echo command expect.expect(times(2, contains("\n"))); // getting the output of ls System.out.println(expect.expect(regexp(".*\\$")).getBefore().trim()); expect.sendLine("exit"); } finally { expect.close(); channel.disconnect(); session.disconnect(); } }
Example 9
Source File: DeploymentEngine.java From if1007 with MIT License | 5 votes |
private boolean executeSSH(){ //get deployment descriptor, instead of this hard coded. // or execute a script on the target machine which download artifact from nexus String command ="nohup java -jar -Dserver.port=8091 ./work/codebox/chapter6/chapter6.search/target/search-1.0.jar &"; try{ System.out.println("Executing "+ command); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); JSch jsch = new JSch(); Session session=jsch.getSession("rajeshrv", "localhost", 22); session.setPassword("rajeshrv"); session.setConfig(config); session.connect(); System.out.println("Connected"); ChannelExec channelExec = (ChannelExec)session.openChannel("exec"); InputStream in = channelExec.getInputStream(); channelExec.setCommand(command); channelExec.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; int index = 0; while ((line = reader.readLine()) != null) { System.out.println(++index + " : " + line); } channelExec.disconnect(); session.disconnect(); System.out.println("Done!"); }catch(Exception e){ e.printStackTrace(); return false; } return true; }
Example 10
Source File: SshProvider.java From parallec with Apache License 2.0 | 5 votes |
/** * Start ssh session and obtain session. * * @return the session */ public Session startSshSessionAndObtainSession() { Session session = null; try { JSch jsch = new JSch(); if (sshMeta.getSshLoginType() == SshLoginType.KEY) { String workingDir = System.getProperty("user.dir"); String privKeyAbsPath = workingDir + "/" + sshMeta.getPrivKeyRelativePath(); logger.debug("use privkey: path: " + privKeyAbsPath); if (!PcFileNetworkIoUtils.isFileExist(privKeyAbsPath)) { throw new RuntimeException("file not found at " + privKeyAbsPath); } if (sshMeta.isPrivKeyUsePassphrase() && sshMeta.getPassphrase() != null) { jsch.addIdentity(privKeyAbsPath, sshMeta.getPassphrase()); } else { jsch.addIdentity(privKeyAbsPath); } } session = jsch.getSession(sshMeta.getUserName(), targetHost, sshMeta.getSshPort()); if (sshMeta.getSshLoginType() == SshLoginType.PASSWORD) { session.setPassword(sshMeta.getPassword()); } session.setConfig("StrictHostKeyChecking", "no"); } catch (Exception t) { throw new RuntimeException(t); } return session; }
Example 11
Source File: DeploymentEngine.java From Microservices-Building-Scalable-Software with MIT License | 5 votes |
private boolean executeSSH(){ //get deployment descriptor, instead of this hard coded. // or execute a script on the target machine which download artifact from nexus String command ="nohup java -jar -Dserver.port=8091 ./work/codebox/chapter6/chapter6.search/target/search-1.0.jar &"; try{ System.out.println("Executing "+ command); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); JSch jsch = new JSch(); Session session=jsch.getSession("rajeshrv", "localhost", 22); session.setPassword("rajeshrv"); session.setConfig(config); session.connect(); System.out.println("Connected"); ChannelExec channelExec = (ChannelExec)session.openChannel("exec"); InputStream in = channelExec.getInputStream(); channelExec.setCommand(command); channelExec.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; int index = 0; while ((line = reader.readLine()) != null) { System.out.println(++index + " : " + line); } channelExec.disconnect(); session.disconnect(); System.out.println("Done!"); }catch(Exception e){ e.printStackTrace(); return false; } return true; }
Example 12
Source File: DeploymentEngine.java From Spring-Microservices with MIT License | 5 votes |
private boolean executeSSH(){ //get deployment descriptor, instead of this hard coded. // or execute a script on the target machine which download artifact from nexus String command ="nohup java -jar -Dserver.port=8091 ./work/codebox/chapter6/chapter6.search/target/search-1.0.jar &"; try{ System.out.println("Executing "+ command); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); JSch jsch = new JSch(); Session session=jsch.getSession("rajeshrv", "localhost", 22); session.setPassword("rajeshrv"); session.setConfig(config); session.connect(); System.out.println("Connected"); ChannelExec channelExec = (ChannelExec)session.openChannel("exec"); InputStream in = channelExec.getInputStream(); channelExec.setCommand(command); channelExec.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; int index = 0; while ((line = reader.readLine()) != null) { System.out.println(++index + " : " + line); } channelExec.disconnect(); session.disconnect(); System.out.println("Done!"); }catch(Exception e){ e.printStackTrace(); return false; } return true; }
Example 13
Source File: SshLocalhostNoEchoExample.java From ExpectIt with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws JSchException, IOException { JSch jSch = new JSch(); Session session = jSch.getSession(System.getenv("USER"), "localhost"); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); jSch.addIdentity(System.getProperty("user.home") + "/.ssh/id_rsa"); session.setConfig(config); session.connect(); Channel channel = session.openChannel("shell"); channel.connect(); Expect expect = new ExpectBuilder() .withOutput(channel.getOutputStream()) .withInputs(channel.getInputStream(), channel.getExtInputStream()) .build(); try { expect.expect(contains("$")); expect.sendLine("stty -echo"); expect.expect(contains("$")); expect.sendLine("pwd"); System.out.println("pwd1:" + expect.expect(contains("\n")).getBefore()); expect.sendLine("exit"); } finally { expect.close(); channel.disconnect(); session.disconnect(); } }
Example 14
Source File: PropertyBasedSshSessionFactory.java From spring-cloud-config with Apache License 2.0 | 5 votes |
@Override protected void configure(Host hc, Session session) { JGitEnvironmentProperties sshProperties = this.sshKeysByHostname .get(hc.getHostName()); String hostKeyAlgorithm = sshProperties.getHostKeyAlgorithm(); if (hostKeyAlgorithm != null) { session.setConfig(SERVER_HOST_KEY, hostKeyAlgorithm); } if (sshProperties.getHostKey() == null || !sshProperties.isStrictHostKeyChecking()) { session.setConfig(STRICT_HOST_KEY_CHECKING, NO_OPTION); } else { session.setConfig(STRICT_HOST_KEY_CHECKING, YES_OPTION); } String preferredAuthentications = sshProperties.getPreferredAuthentications(); if (preferredAuthentications != null) { session.setConfig(PREFERRED_AUTHENTICATIONS, preferredAuthentications); } ProxyHostProperties proxyHostProperties = sshProperties.getProxy() .get(ProxyHostProperties.ProxyForScheme.HTTP); if (proxyHostProperties != null) { ProxyHTTP proxy = createProxy(proxyHostProperties); proxy.setUserPasswd(proxyHostProperties.getUsername(), proxyHostProperties.getPassword()); session.setProxy(proxy); } }
Example 15
Source File: SshHelperTest.java From ssh-shell-spring-boot with Apache License 2.0 | 5 votes |
public static void call(String user, String pass, String host, int port, Executor executor) { try { JSch jsch = new JSch(); Session session = jsch.getSession(user, host, port); session.setPassword(pass); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); Channel channel = session.openChannel("shell"); PipedInputStream pis = new PipedInputStream(); PipedOutputStream pos = new PipedOutputStream(); channel.setInputStream(new PipedInputStream(pos)); channel.setOutputStream(new PipedOutputStream(pis)); channel.connect(); try { executor.execute(pis, pos); } catch (Exception e) { fail(e.toString()); } finally { pis.close(); pos.close(); channel.disconnect(); session.disconnect(); } } catch (JSchException | IOException ex) { fail(ex.toString()); } }
Example 16
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 17
Source File: JavaConnect.java From ssh-shell-spring-boot with Apache License 2.0 | 4 votes |
public static void main(String[] args) { String host = "localhost"; String user = "user"; int port = 2222; String password = "password"; String command = "help"; try { java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); JSch jsch = new JSch(); Session session = jsch.getSession(user, host, port); session.setPassword(password); session.setConfig(config); session.connect(); System.out.println("Connected"); Channel channel = session.openChannel("shell"); channel.connect(); channel.getOutputStream().write((command + "\r").getBytes(StandardCharsets.UTF_8)); channel.getOutputStream().flush(); channel.setInputStream(null); InputStream in = channel.getInputStream(); byte[] tmp = new byte[1024]; while (true) { while (in.available() > 0) { int i = in.read(tmp, 0, 1024); if (i < 0) break; System.out.print(new String(tmp, 0, i)); } if (channel.isClosed()) { System.out.println("exit-status: " + channel.getExitStatus()); break; } try { Thread.sleep(3000); } catch (Exception ee) { } } channel.disconnect(); session.disconnect(); System.out.println("DONE"); } catch (Exception e) { e.printStackTrace(); } }
Example 18
Source File: GitClient.java From flow-platform-x with Apache License 2.0 | 4 votes |
@Override protected void configure(OpenSshConfig.Host host, Session session) { session.setConfig("StrictHostKeyChecking", "no"); }
Example 19
Source File: StudioNodeSyncBaseTask.java From studio with GNU General Public License v3.0 | 4 votes |
@Override protected void configure(OpenSshConfig.Host hc, Session session) { Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); }
Example 20
Source File: MultiUserSshSessionFactory.java From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License | 3 votes |
/** * Create a new remote session for the requested address. * * @param hc host configuration * @param user login to authenticate as. * @param host server name to connect to. * @param port port number of the SSH daemon (typically 22). * @param fs the file system abstraction which will be necessary to * perform certain file system operations. * @return new session instance, but otherwise unconfigured. * @throws JSchException the session could not be created. */ protected Session createSession(final CredentialsProvider credentialsProvider, final OpenSshConfig.Host hc, final String user, final String host, final int port, FS fs) throws JSchException { Session session = getJSch(credentialsProvider, hc, fs).getSession(user, host, port); // FIXME workaround for com.jcraft.jsch.JSchException: UnknownHostKey Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); return session; }