Java Code Examples for com.jcraft.jsch.JSch#getSession()
The following examples show how to use
com.jcraft.jsch.JSch#getSession() .
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: RemoteLauncherCommands.java From gemfirexd-oss with Apache License 2.0 | 8 votes |
/** * Connect to a remote host via SSH and execute a command. * * @param host * Host to connect to * @param user * User to login with * @param password * Password for the user * @param command * Command to execute * @return The result of the command execution */ private Result executeSshCommand(final String host, final String user, final String password, final String command) { StringBuilder result = new StringBuilder(); try { JSch jsch = new JSch(); Session session = jsch.getSession(user, host, 22); session.setUserInfo(createUserInfo(password)); session.connect(5000); ChannelExec channel = (ChannelExec) session.openChannel("exec"); channel.setCommand(command); channel.setInputStream(null); channel.setErrStream(System.err); InputStream in = channel.getInputStream(); channel.connect(); byte[] tmp = new byte[1024]; while (true) { while (in.available() > 0) { int i = in.read(tmp, 0, 1024); if (i < 0) break; result.append(new String(tmp, 0, i)); } if (channel.isClosed()) { break; } } channel.disconnect(); session.disconnect(); } catch (Exception jex) { return createResult(Result.Status.ERROR, jex.getMessage()); } return createResult(Result.Status.OK, result.toString()); }
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: 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 4
Source File: SshShell.java From azure-libraries-for-java with MIT License | 6 votes |
/** * Creates SSHShell. * * @param host the host name * @param port the ssh port * @param userName the ssh user name * @param password the ssh password * @return the shell * @throws JSchException * @throws IOException */ private SshShell(String host, int port, String userName, String password) throws JSchException, IOException { Closure expectClosure = getExpectClosure(); for (String linuxPromptPattern : new String[]{"\\>","#", "~#", "~\\$"}) { try { Match match = new RegExpMatch(linuxPromptPattern, expectClosure); linuxPromptMatches.add(match); } catch (MalformedPatternException malformedEx) { throw new RuntimeException(malformedEx); } } JSch jsch = new JSch(); this.session = jsch.getSession(userName, host, port); session.setPassword(password); Hashtable<String,String> config = new Hashtable<>(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(60000); this.channel = (ChannelShell) session.openChannel("shell"); this.expect = new Expect4j(channel.getInputStream(), channel.getOutputStream()); channel.connect(); }
Example 5
Source File: JSchUtils.java From primecloud-controller with GNU General Public License v2.0 | 6 votes |
/** * TODO: メソッドコメントを記述 * * @param username * @param privateKey * @param passphrase * @param host * @param port * @return */ public static Session createSessionByPrivateKey(String username, String privateKey, String passphrase, String host, int port) { Charset charset = Charset.forName("UTF-8"); byte[] privateKeyBytes = privateKey.getBytes(charset); byte[] passphraseBytes = null; if (passphrase != null) { passphraseBytes = passphrase.getBytes(charset); } try { JSch jsch = new JSch(); jsch.addIdentity("name", privateKeyBytes, null, passphraseBytes); Session session = jsch.getSession(username, host, port); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); return session; } catch (JSchException e) { throw new AutoException("ECOMMON-000302", username, host, port); } }
Example 6
Source File: JobConfigUtil.java From jumbune with GNU Lesser General Public License v3.0 | 6 votes |
private static Session getSession(String host, String username, String password, String privateKeyPath) throws JSchException { JSch jsch = new JSch(); Session session = null; if (StringUtils.isNotBlank(privateKeyPath)) { jsch.addIdentity(privateKeyPath); } session = jsch.getSession(username, host, 22); Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); if (StringUtils.isNotBlank(password)) { session.setPassword(password); config.put("PreferredAuthentications", "password"); } session.setConfig(config); session.connect(); return session; }
Example 7
Source File: CommandAsObjectResponserMethods.java From jumbune with GNU Lesser General Public License v3.0 | 6 votes |
/** * For creating a JSCH session. * * @param host * the host * @return a JSCH session * @throws JSchException * the jsch exception */ private Session createSession(CommandWritable.Command.SwitchedIdentity switchedIdentity, String host, CommandType commandType) throws JSchException { JSch jsch = new JSch(); Session session = null; if(switchedIdentity.getPrivatePath() != null && !switchedIdentity.getPrivatePath().isEmpty()){ jsch.addIdentity(switchedIdentity.getPrivatePath()); } java.util.Properties conf = new java.util.Properties(); session = jsch.getSession(switchedIdentity.getUser(), host, RemotingConstants.TWENTY_TWO); if(switchedIdentity.getPasswd()!=null){ try{ session.setPassword(StringUtil.getPlain(switchedIdentity.getPasswd())); }catch(Exception e){ LOGGER.error("Failed to Decrypt the password", e); } } conf.put(STRICT_HOST_KEY_CHECKING, "no"); session.setConfig(conf); session.connect(); LOGGER.debug("Session Established, for user ["+switchedIdentity.getUser()+"]"+":["+session.isConnected()+"]"); return session; }
Example 8
Source File: SftpFileUtil.java From Leo with Apache License 2.0 | 5 votes |
private Session getSession() { if (null!=session) { return session; } int ftpPort = 21; if (PORT != null && !PORT.equals("")) { ftpPort = Integer.valueOf(PORT); } JSch jsch = new JSch(); // 创建JSch对象 try { // 根据用户名,主机ip,端口获取一个Session对象 session = jsch.getSession(FTPUSERNAME, FTPHOST, ftpPort); if (FTPPASSWORD != null) { session.setPassword(FTPPASSWORD); // 设置密码 } Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); // 为Session对象设置properties session.setTimeout(300000); // 设置timeout时间为5分钟 session.connect(); // 通过Session建立链接 return session; } catch (JSchException e) { log.error("连接 "+FTPHOST+":"+ftpPort+"的SFTP通道创建失败"); log.error(e.getMessage()); return null; } }
Example 9
Source File: Scanner.java From ciscorouter with MIT License | 5 votes |
/** * Connects to the device and retrieves the configuration file from the * device. * @return A ArrayList containing the output from the GET_ALL_CONFIG * command */ private ArrayList<String> getConfigFile() throws Exception{ JSch jsch = new JSch(); InputStream in = null; Session session = jsch.getSession( host.getUser(), host.toString(), SSH_PORT); session.setPassword(host.getPass()); //If this line isn't present, every host must be in known_hosts session.setConfig("StrictHostKeyChecking", "no"); session.connect(); Channel channel = session.openChannel("shell"); in = channel.getInputStream(); OutputStream outputStream = channel.getOutputStream(); Expect expect = new ExpectBuilder() .withOutput(outputStream) .withInputs(channel.getInputStream(), channel.getExtInputStream()) //.withEchoOutput(System.out) //.withEchoInput(System.out) .build(); channel.connect(); if (host.usesEnable()) { expect.expect(contains(">")); expect.sendLine(ENABLE_SUPERUSER); expect.expect(contains(PASSWORD_PROMPT)); expect.sendLine(host.getEnablePass()); } expect.expect(contains("#")); //# expect.sendLine(DISABLE_OUTPUT_BUFFERING); //terminal length 0 expect.expect(contains("#")); //# expect.sendLine(GET_ALL_CONFIG); //show running-config full String result = expect.expect(contains("#")).getBefore(); //# channel.disconnect(); session.disconnect(); expect.close(); String[] arrLines = result.split("\n"); ArrayList<String> lines = new ArrayList<>(Arrays.asList(arrLines)); return lines; }
Example 10
Source File: SftpClient.java From netbeans with Apache License 2.0 | 5 votes |
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 11
Source File: SftpExecUtil.java From Leo with Apache License 2.0 | 5 votes |
private Session getSession() { if (null!=session) { return session; } String ftpHost = SshHost; String port = SshPort; String ftpUserName = SshUserName; String ftpPassword = SshPassword; int ftpPort = 21; if (port != null && !port.equals("")) { ftpPort = Integer.valueOf(port); } JSch jsch = new JSch(); // 创建JSch对象 try { // 根据用户名,主机ip,端口获取一个Session对象 session = jsch.getSession(ftpUserName, ftpHost, ftpPort); if (ftpPassword != null) { session.setPassword(ftpPassword); // 设置密码 } Properties config = new Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); // 为Session对象设置properties session.setTimeout(300000); // 设置timeout时间为5分钟 session.connect(); // 通过Session建立链接 // log.info("连接 "+ftpHost+":"+ftpPort+"的SFTP通道创建成功"); return session; } catch (JSchException e) { log.error("连接 "+ftpHost+":"+ftpPort+"的SFTP通道创建失败"); log.error(e.getMessage()); return null; } }
Example 12
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 13
Source File: ExecuteShellUtil.java From eladmin with Apache License 2.0 | 5 votes |
public ExecuteShellUtil(final String ipAddress, final String username, final String password,int port) { try { JSch jsch = new JSch(); session = jsch.getSession(username, ipAddress, port); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.connect(3000); } catch (Exception e) { log.error(e.getMessage(),e); } }
Example 14
Source File: SftpUtils.java From secure-data-service with Apache License 2.0 | 5 votes |
public static void landFile(File fileToLand, UploadProperties properties) throws Exception { JSch jsch = new JSch(); String host = properties.getSftpServer(); String user = properties.getUser(); String password = properties.getPassword(); int port = properties.getPort(); Session session = jsch.getSession(user, host, port); session.setOutputStream(System.out); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.connect(TIMEOUT); Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp c = (ChannelSftp) channel; // delete any existing file with the target filename, so that rename will work @SuppressWarnings("unchecked") Vector<LsEntry> files = c.ls("."); for (LsEntry file : files) { if (FINAL_REMOTE_FILENAME.equals(file.getFilename())) { c.rm(FINAL_REMOTE_FILENAME); } } // transmit file, using temp remote name, so ingestion won't process file until complete c.put(new FileInputStream(fileToLand), TEMP_REMOTE_FILENAME, ChannelSftp.OVERWRITE); // rename remote file so ingestion can begin c.rename(TEMP_REMOTE_FILENAME, FINAL_REMOTE_FILENAME); c.disconnect(); channel.disconnect(); session.disconnect(); }
Example 15
Source File: KeyReExchangeTest.java From termd with Apache License 2.0 | 5 votes |
@Test public void testReExchangeFromJschClient() throws Exception { Assume.assumeTrue("DH Group Exchange not supported", SecurityUtils.isDHGroupExchangeSupported()); setUp(0L, 0L, 0L); JSch.setConfig("kex", BuiltinDHFactories.Constants.DIFFIE_HELLMAN_GROUP_EXCHANGE_SHA1); JSch sch = new JSch(); com.jcraft.jsch.Session s = sch.getSession(getCurrentTestName(), TEST_LOCALHOST, port); try { s.setUserInfo(new SimpleUserInfo(getCurrentTestName())); s.connect(); com.jcraft.jsch.Channel c = s.openChannel(Channel.CHANNEL_SHELL); c.connect(); try (OutputStream os = c.getOutputStream(); InputStream is = c.getInputStream()) { String expected = "this is my command\n"; byte[] bytes = expected.getBytes(StandardCharsets.UTF_8); byte[] data = new byte[bytes.length + Long.SIZE]; for (int i = 1; i <= 10; i++) { os.write(bytes); os.flush(); int len = is.read(data); String str = new String(data, 0, len); assertEquals("Mismatched data at iteration " + i, expected, str); outputDebugMessage("Request re-key #%d", i); s.rekey(); } } finally { c.disconnect(); } } finally { s.disconnect(); } }
Example 16
Source File: ATest.java From aws-ec2-ssh with MIT License | 5 votes |
protected final void probeSSH(final String host, final User user) { final Callable<Boolean> callable = () -> { final JSch jsch = new JSch(); final Session session = jsch.getSession(user.userName, host); jsch.addIdentity(user.userName, user.sshPrivateKeyBlob, null, null); jsch.setConfig("StrictHostKeyChecking", "no"); // for testing this should be fine. adding the host key seems to be only possible via a file which is not very useful here session.connect(10000); session.disconnect(); return true; }; Assert.assertTrue(this.retry(callable)); }
Example 17
Source File: SshFenceByTcpPort.java From hadoop with Apache License 2.0 | 5 votes |
private Session createSession(String host, Args args) throws JSchException { JSch jsch = new JSch(); for (String keyFile : getKeyFiles()) { jsch.addIdentity(keyFile); } JSch.setLogger(new LogAdapter()); Session session = jsch.getSession(args.user, host, args.sshPort); session.setConfig("StrictHostKeyChecking", "no"); return session; }
Example 18
Source File: SshRequestHandler.java From trigger with GNU General Public License v2.0 | 4 votes |
public void run() { if (setup.getId() < 0) { this.listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, "Internal Error"); return; } if (setup.require_wifi && !WifiTools.isConnected()) { this.listener.onTaskResult(setup.getId(), ReplyCode.DISABLED, "Wifi Disabled."); return; } String command = ""; switch (action) { case open_door: command = setup.open_command; break; case close_door: command = setup.close_command; break; case ring_door: command = setup.ring_command; break; case fetch_state: command = setup.state_command; break; } String user = setup.user; String password = setup.password; String host = setup.host; KeyPair keypair = setup.keypair; int port = setup.port; try { if (command.isEmpty()) { listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, ""); return; } if (host.isEmpty()) { listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, "Host is empty."); return; } // fallback if (setup.user.isEmpty()) { user = "root"; } JSch jsch = new JSch(); if (keypair != null) { SshTools.KeyPairData data = SshTools.keypairToBytes(keypair); byte passphrase[] = new byte[0]; jsch.addIdentity("authkey", data.prvkey, data.pubkey, passphrase); } Session session = jsch.getSession(user, host, port); if (password.length() > 0) { session.setPassword(password); } session.setConfig("StrictHostKeyChecking", "no"); StringBuilder outputBuffer = new StringBuilder(); try { session.connect(5000); // 5sec timeout Channel channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); InputStream commandOutput = channel.getInputStream(); channel.connect(); int readByte = commandOutput.read(); while (readByte != 0xffffffff) { outputBuffer.append((char)readByte); readByte = commandOutput.read(); } channel.disconnect(); session.disconnect(); } catch (IOException ioe) { listener.onTaskResult(setup.getId(), ReplyCode.REMOTE_ERROR, ioe.getMessage()); } catch (JSchException jse) { listener.onTaskResult(setup.getId(), ReplyCode.REMOTE_ERROR, jse.getMessage()); } listener.onTaskResult(setup.getId(), ReplyCode.SUCCESS, outputBuffer.toString()); } catch (Exception e) { this.listener.onTaskResult(setup.getId(), ReplyCode.LOCAL_ERROR, e.toString()); } }
Example 19
Source File: SshConnectionImpl.java From gerrit-events with MIT License | 4 votes |
/** * Connects the connection. * @throws IOException if the unfortunate happens. */ @Override public synchronized void connect() throws IOException { logger.debug("connecting..."); Authentication auth = authentication; if (updater != null) { Authentication updatedAuth = updater.updateAuthentication(authentication); if (updatedAuth != null && auth != updatedAuth) { auth = updatedAuth; } } try { client = new JSch(); if (auth.getPrivateKeyPhrase() == null) { client.addIdentity(auth.getPrivateKeyFile().getAbsolutePath(), auth.getPrivateKeyFilePassword()); } else { client.addIdentity(auth.getUsername(), auth.getPrivateKeyPhrase(), null, auth.getPrivateKeyFilePassword().getBytes("UTF-8")); } client.setHostKeyRepository(new BlindHostKeyRepository()); connectSession = client.getSession(auth.getUsername(), host, port); connectSession.setConfig("PreferredAuthentications", "publickey"); if (proxy != null && !proxy.isEmpty()) { String[] splitted = proxy.split(":"); if (splitted.length > 2 && splitted[1].length() >= PROTO_HOST_DELIM_LENGTH) { String pproto = splitted[0]; String phost = splitted[1].substring(2); int pport = Integer.parseInt(splitted[2]); if (pproto.equals("socks5") || pproto.equals("http")) { if (pproto.equals("socks5")) { connectSession.setProxy(new ProxySOCKS5(phost, pport)); } else { connectSession.setProxy(new ProxyHTTP(phost, pport)); } } else { throw new MalformedURLException("Only http and socks5 protocols are supported"); } } else { throw new MalformedURLException(proxy); } } connectSession.connect(this.connectionTimeout); logger.debug("Connected: {}", connectSession.isConnected()); connectSession.setServerAliveInterval(ALIVE_INTERVAL); } catch (JSchException ex) { throw new SshException(ex); } }
Example 20
Source File: SSHCommandExecutor.java From journaldev with MIT License | 4 votes |
/** * @param args */ public static void main(String[] args) { String host="test.journaldev.com"; String user="my_user"; String password="my_pwd"; String command1="cd Apps;ls -ltr"; try{ java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); JSch jsch = new JSch(); Session session=jsch.getSession(user, host, 22); session.setPassword(password); session.setConfig(config); session.connect(); System.out.println("Connected"); Channel channel=session.openChannel("exec"); ((ChannelExec)channel).setCommand(command1); channel.setInputStream(null); ((ChannelExec)channel).setErrStream(System.err); InputStream in=channel.getInputStream(); channel.connect(); 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(1000);}catch(Exception ee){} } channel.disconnect(); session.disconnect(); System.out.println("DONE"); }catch(Exception e){ e.printStackTrace(); } }