com.jcraft.jsch.Session Java Examples
The following examples show how to use
com.jcraft.jsch.Session.
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: JSchExecutorTests.java From vividus with Apache License 2.0 | 7 votes |
@Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void shouldExecuteSuccessfullyWithoutAgentForwarding() throws Exception { ServerConfiguration server = getDefaultServerConfiguration(); JSch jSch = mock(JSch.class); whenNew(JSch.class).withNoArguments().thenReturn(jSch); Session session = mock(Session.class); when(jSch.getSession(server.getUsername(), server.getHost(), server.getPort())).thenReturn(session); ChannelExec channelExec = mockChannelOpening(session); SshOutput actual = new TestJSchExecutor().execute(server, COMMANDS); assertEquals(SSH_OUTPUT, actual); InOrder ordered = inOrder(jSch, session, channelExec); ordered.verify(jSch).addIdentity(IDENTITY_NAME, server.getPrivateKey().getBytes(StandardCharsets.UTF_8), server.getPublicKey().getBytes(StandardCharsets.UTF_8), server.getPassphrase().getBytes(StandardCharsets.UTF_8)); verifyFullConnection(ordered, server, session, channelExec); }
Example #2
Source File: SSHServerTest.java From vertx-shell with Apache License 2.0 | 7 votes |
@Test public void testWrite() throws Exception { termHandler = term -> { term.write("hello"); }; startShell(); Session session = createSession("paulo", "secret", false); session.connect(); Channel channel = session.openChannel("shell"); channel.connect(); Reader in = new InputStreamReader(channel.getInputStream()); int count = 5; StringBuilder sb = new StringBuilder(); while (count > 0) { int code = in.read(); if (code == -1) { count = 0; } else { count--; sb.append((char) code); } } assertEquals("hello", sb.toString()); channel.disconnect(); session.disconnect(); }
Example #3
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 #4
Source File: JSchUtilsTest.java From primecloud-controller with GNU General Public License v2.0 | 7 votes |
@Test @Ignore public void testExecuteCommand3() throws Exception { // 鍵認証(パスフレーズあり) File privateKeyFile = new ClassPathResource(ClassUtils.addResourcePathToPackagePath(getClass(), "key02.pem")) .getFile(); String privateKey = FileUtils.readFileToString(privateKeyFile, "UTF-8"); Session session = JSchUtils.createSessionByPrivateKey("user01", privateKey, "passw0rd", "172.22.0.23"); JSchResult result = JSchUtils.executeCommand(session, "env", "UTF-8"); assertEquals(0, result.getExitStatus()); result = JSchUtils.executeCommand(session, "ls -l /etc", "UTF-8"); assertEquals(0, result.getExitStatus()); session.disconnect(); }
Example #5
Source File: CommandRunner.java From jsch-extension with MIT License | 6 votes |
/** * Executes <code>command</code> and returns the result. Use this method * when the command you are executing requires no input, writes only UTF-8 * compatible text to STDOUT and/or STDERR, and you are comfortable with * buffering up all of that data in memory. Otherwise, use * {@link #open(String)}, which allows you to work with the underlying * streams. * * @param command * The command to execute * @return The resulting data * * @throws JSchException * If ssh execution fails * @throws IOException * If unable to read the result data */ public ExecuteResult execute( String command ) throws JSchException, IOException { logger.debug( "executing {} on {}", command, sessionManager ); Session session = sessionManager.getSession(); ByteArrayOutputStream stdErr = new ByteArrayOutputStream(); ByteArrayOutputStream stdOut = new ByteArrayOutputStream(); int exitCode; ChannelExecWrapper channel = null; try { channel = new ChannelExecWrapper( session, command, null, stdOut, stdErr ); } finally { exitCode = channel.close(); } return new ExecuteResult( exitCode, new String( stdOut.toByteArray(), UTF8 ), new String( stdErr.toByteArray(), UTF8 ) ); }
Example #6
Source File: AgentProxyAwareJschConfigSessionFactory.java From gitflow-incremental-builder with MIT License | 6 votes |
@Override protected Session createSession(Host hc, String user, String host, int port, FS fs) throws JSchException { JSch jSch = getJSch(hc, fs); // assumption: identities from agent are always unencrypted final Collection<Identity> allUnencryptedIdentities = getIdentitiesFromAgentProxy(); @SuppressWarnings("unchecked") Collection<Identity> identities = ((Collection<Identity>) jSch.getIdentityRepository().getIdentities()); identities.stream() .filter(id -> !id.isEncrypted()) .forEach(allUnencryptedIdentities::add); Session session = jSch.getSession(user, host, port); session.setIdentityRepository(new ReadOnlyIdentityRepository(allUnencryptedIdentities)); return session; }
Example #7
Source File: JSchExecutorTests.java From vividus with Apache License 2.0 | 6 votes |
@Test @SuppressWarnings("PMD.SignatureDeclareThrowsException") public void shouldFailOnCommandExecutionError() throws Exception { ServerConfiguration server = getDefaultServerConfiguration(); server.setPublicKey(null); JSch jSch = mock(JSch.class); whenNew(JSch.class).withNoArguments().thenReturn(jSch); Session session = mock(Session.class); when(jSch.getSession(server.getUsername(), server.getHost(), server.getPort())).thenReturn(session); ChannelExec channelExec = mockChannelOpening(session); JSchException jSchException = new JSchException(); CommandExecutionException exception = assertThrows(CommandExecutionException.class, () -> new TestJSchExecutor() { @Override protected SshOutput executeCommand(ServerConfiguration serverConfig, Commands commands, ChannelExec channel) throws JSchException { throw jSchException; } }.execute(server, COMMANDS)); assertEquals(jSchException, exception.getCause()); InOrder ordered = inOrder(jSch, session, channelExec); verifyFullConnection(ordered, server, session, channelExec); }
Example #8
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 #9
Source File: SSHShellTest.java From vertx-shell with Apache License 2.0 | 6 votes |
@Test public void testDeployServiceWithShiroAuthOptions(TestContext context) throws Exception { Async async = context.async(); vertx.deployVerticle("service:io.vertx.ext.shell", new DeploymentOptions().setConfig(new JsonObject().put("sshOptions", new JsonObject(). put("host", "localhost"). put("port", 5000). put("keyPairOptions", new JsonObject(). put("path", "src/test/resources/server-keystore.jks"). put("password", "wibble")). put("authOptions", new JsonObject().put("provider", "shiro").put("config", new JsonObject(). put("properties_path", "classpath:test-auth.properties"))))) , context.asyncAssertSuccess(v -> { async.complete(); })); async.awaitSuccess(2000); Session session = createSession("paulo", "secret", false); session.connect(); Channel channel = session.openChannel("shell"); channel.connect(); channel.disconnect(); session.disconnect(); }
Example #10
Source File: SftpFileProvider.java From commons-vfs with Apache License 2.0 | 6 votes |
/** * Creates a new Session. * * @return A Session, never null. */ static Session createSession(final GenericFileName rootName, final FileSystemOptions fileSystemOptions) throws FileSystemException { UserAuthenticationData authData = null; try { authData = UserAuthenticatorUtils.authenticate(fileSystemOptions, AUTHENTICATOR_TYPES); return SftpClientFactory.createConnection(rootName.getHostName(), rootName.getPort(), UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(rootName.getUserName())), UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(rootName.getPassword())), fileSystemOptions); } catch (final Exception e) { throw new FileSystemException("vfs.provider.sftp/connect.error", rootName, e); } finally { UserAuthenticatorUtils.cleanup(authData); } }
Example #11
Source File: JavaStatusChecker.java From embeddedlinux-jvmdebugger-intellij with Apache License 2.0 | 6 votes |
/** * Stops java application that needs to, this should be called when the user wants to manually stop the application * so that it kills the remote java process * * @param session * @param isRunningAsRoot * @param mainClass * @throws JSchException * @throws IOException */ public void forceStopJavaApplication(@Nullable Session session, @NotNull boolean isRunningAsRoot, @NotNull String mainClass) throws JSchException, IOException { if (session == null) { return; } String javaKillCmd = String.format("%s kill -9 $(ps -efww | grep \"%s\"| grep -v grep | tr -s \" \"| cut -d\" \" -f2)", isRunningAsRoot ? "sudo" : "", mainClass); Channel channel = session.openChannel("shell"); OutputStream inputstream_for_the_channel = channel.getOutputStream(); PrintStream commander = new PrintStream(inputstream_for_the_channel, true); channel.connect(); commander.println(javaKillCmd); commander.close(); channel.disconnect(); session.disconnect(); }
Example #12
Source File: GenericBasedGitVcsOperator.java From super-cloudops with Apache License 2.0 | 6 votes |
/** * New transport callback for ssh-key authenticate credentials. * * @param identity * @return * @throws Exception * @see {@link TransportConfigCallback} */ private TransportConfigCallback newTransportConfigCallback(byte[] identity) throws Exception { return new TransportConfigCallback() { @Override public void configure(Transport transport) { SshTransport sshTransport = (SshTransport) transport; sshTransport.setSshSessionFactory(new JschConfigSessionFactory() { @Override protected void configure(OpenSshConfig.Host hc, Session session) { session.setConfig("StrictHostKeyChecking", "no"); // session.setPort(2022); } @Override protected JSch createDefaultJSch(FS fs) throws JSchException { JSch jsch = super.createDefaultJSch(fs); jsch.removeAllIdentity(); // jsch.addIdentity("/Users/vjay/.ssh/id_rsa"); jsch.getIdentityRepository().add(identity); return jsch; } }); } }; }
Example #13
Source File: JschUtil.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 */ public static 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); conf.put(STRICT_HOST_KEY_CHECKING, "no"); if(switchedIdentity.getPasswd()!=null){ try { session.setPassword(StringUtil.getPlain(switchedIdentity.getPasswd())); } catch (Exception e) { LOGGER.error("Unable to get decrypted Password", e); } } session.setConfig(conf); return session; }
Example #14
Source File: CommandLineAction.java From EasyXMS with Apache License 2.0 | 6 votes |
/** * 直接从命令行上传文件 * @param src_file 上传的原文件 * @param remote_path 远程服务器的路径 * @param objects ServerInfo对象列表 */ public void commandlineUploadFile(String src_file,String remote_path,List<ServerInfo> objects){ WriteLog writeLog = new WriteLog(); SessionPool.setSftp_connection_pool(sessionHashMap); UploadFile.setWriteLog(writeLog); UploadFile.setSrc(src_file); UploadFile.setDst(remote_path); if (! remote_path.startsWith("/")){ remote_path = "$HOME/" + remote_path; } HelpPrompt.printFileSizeAndRemotePath(src_file,remote_path); long start_time = System.currentTimeMillis(); MultiThread multiThread = new MultiThread(); multiThread.startMultiThread(objects,"sftp"); HashMap<String, Session> sessions = SessionPool.getSftp_connection_pool(); for (Session session : sessions.values()){ session.disconnect(); } sessionHashMap.clear(); long end_time = System.currentTimeMillis(); System.out.println(); HelpPrompt.printExecuteTime(objects.size(),(end_time - start_time)/1000); }
Example #15
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 #16
Source File: SSHExecProcessAdapter.java From teamcity-deployer-plugin with Apache License 2.0 | 6 votes |
@Override public BuildFinishedStatus runProcess() { JSch.setLogger(new JSchBuildLogger(myLogger)); Session session = null; try { session = myProvider.getSession(); return executeCommand(session, myPty, myCommands); } catch (JSchException e) { logBuildProblem(myLogger, e.getMessage()); LOG.warnAndDebugDetails("Error executing SSH command", e); return BuildFinishedStatus.FINISHED_FAILED; } finally { if (session != null) { session.disconnect(); } } }
Example #17
Source File: SessionEstablisher.java From jumbune with GNU Lesser General Public License v3.0 | 6 votes |
/** * This method execute the given command over SSH * * @param session * @param command * Command to be executed * @throws JSchException * @throws IOException * @throws InterruptedException */ static String executeCommand(Session session, String command) throws JSchException, IOException { InputStream in = null; Channel channel = null; String msg = null; try { channel = session.openChannel("exec"); ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); ((ChannelExec) channel).setErrStream(System.err); in = channel.getInputStream(); channel.connect(); msg = validateCommandExecution(channel, in); } catch (InterruptedException e) { CONSOLE_LOGGER.error(e); } finally { if (in != null) { in.close(); } if (channel != null) { channel.disconnect(); } } return msg; }
Example #18
Source File: CommandAsObjectResponserHA.java From jumbune with GNU Lesser General Public License v3.0 | 6 votes |
/** * Handle cpu usage command. * * @param commandWritable the command writable * @param command the command * @return the object * @throws IOException Signals that an I/O exception has occurred. */ private Object handleCpuUsageCommand(CommandWritable commandWritable, Command command) throws IOException { JschExecutor jschExecutor = new JschExecutor(); Session session = jschExecutor.getSession(commandWritable, command); ChannelReaderResponse channelReaderResponse = jschExecutor.executeResponsiveShellJsch(session, command); String lineBeforeLogout = ""; try (BufferedReader br = (BufferedReader)channelReaderResponse.getReader()) { for (String line = br.readLine(); br != null && line != null; line = br.readLine()) { if(!line.equals(LOGOUT)) { lineBeforeLogout = line; } } } catch (IOException e) { LOGGER.error(e.getMessage(), e); } jschExecutor.closeChannel(channelReaderResponse.getChannel()); jschExecutor.closeSession(session); return lineBeforeLogout; }
Example #19
Source File: SshUtil.java From onos with Apache License 2.0 | 6 votes |
/** * Creates a new session with a given ssh access information. * * @param sshInfo information to ssh to the remote server * @return ssh session, or null */ public static Session connect(SshAccessInfo sshInfo) { Session session; try { JSch jsch = new JSch(); jsch.addIdentity(sshInfo.privateKey()); session = jsch.getSession(sshInfo.user(), sshInfo.remoteIp().toString(), sshInfo.port().toInt()); session.setConfig(STRICT_HOST_CHECKING, DEFAULT_STRICT_HOST_CHECKING); session.connect(DEFAULT_SESSION_TIMEOUT); } catch (JSchException e) { log.warn("Failed to connect to {}", sshInfo.toString(), e); session = authUserPwd(sshInfo); } return session; }
Example #20
Source File: AbstractSshSupport.java From sshd-shell-spring-boot with Apache License 2.0 | 6 votes |
void sshCall(String username, String password, SshExecutor executor, String channelType) { try { Session session = openSession(username, password); Channel channel = session.openChannel(channelType); 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); } finally { pis.close(); pos.close(); channel.disconnect(); session.disconnect(); } } catch (JSchException | IOException ex) { fail(ex.toString()); } }
Example #21
Source File: SSHServerTest.java From vertx-shell with Apache License 2.0 | 6 votes |
@Test public void testKeymapFromFilesystem() throws Exception { URL url = TermServer.class.getResource(SSHTermOptions.DEFAULT_INPUTRC); File f = new File(url.toURI()); termHandler = Term::close; startShell(new SSHTermOptions().setIntputrc(f.getAbsolutePath()).setPort(5000).setHost("localhost").setKeyPairOptions( new JksOptions().setPath("src/test/resources/server-keystore.jks").setPassword("wibble")). setAuthOptions(new JsonObject() .put("provider", "shiro") .put("type", "PROPERTIES") .put("config", new JsonObject().put("properties_path", "classpath:test-auth.properties")))); Session session = createSession("paulo", "secret", false); session.connect(); Channel channel = session.openChannel("shell"); channel.connect(); }
Example #22
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 #23
Source File: CommandLineAction.java From EasyXMS with Apache License 2.0 | 6 votes |
/** * 直接从命令行执行命令 * @param objects ServerInfo对象列表 * @param command 要执行的命令 */ public void commandlineExec(List<ServerInfo> objects,String command){ long start_time = System.currentTimeMillis(); WriteLog writeLog = new WriteLog(); SessionPool.setSsh_connection_pool(sessionHashMap); writeLog.writeCommand(command); ExecCommand.setCommand(command); ExecCommand.setWriteLog(writeLog); MultiThread multiThread = new MultiThread(); multiThread.startMultiThread(objects,"ssh"); HashMap<String, Session> sessions = SessionPool.getSsh_connection_pool(); for (Session session : sessions.values()){ session.disconnect(); } sessionHashMap.clear(); long end_time = System.currentTimeMillis(); HelpPrompt.printExecuteTime(objects.size(),(end_time - start_time)/1000); }
Example #24
Source File: SystemInfo.java From app-runner with MIT License | 6 votes |
private static List<String> getPublicKeys() throws Exception { return new JschConfigSessionFactory() { @Override protected void configure(OpenSshConfig.Host hc, Session session) { } List<String> getPublicKeys() throws Exception { JSch jSch = createDefaultJSch(FS.DETECTED); List<String> keys = new ArrayList<>(); for (Object o : jSch.getIdentityRepository().getIdentities()) { Identity i = (Identity) o; KeyPair keyPair = KeyPair.load(jSch, i.getName(), null); StringBuilder sb = new StringBuilder(); try (StringBuilderWriter sbw = new StringBuilderWriter(sb); OutputStream os = new WriterOutputStream(sbw, "UTF-8")) { keyPair.writePublicKey(os, keyPair.getPublicKeyComment()); } finally { keyPair.dispose(); } keys.add(sb.toString().trim()); } return keys; } }.getPublicKeys(); }
Example #25
Source File: PortForwardingTest.java From termd with Apache License 2.0 | 5 votes |
protected Session createSession() throws JSchException { JSch sch = new JSch(); Session session = sch.getSession(getCurrentTestName(), TEST_LOCALHOST, sshPort); session.setUserInfo(new SimpleUserInfo(getCurrentTestName())); session.connect(); return session; }
Example #26
Source File: TestSshGit.java From Jpom with MIT License | 5 votes |
public static void main(String[] args) throws GitAPIException { Git.cloneRepository() .setURI("[email protected]:jiangzeyin/test.git") .setDirectory(new File("D:\\test\\gitssh")) .setTransportConfigCallback(new TransportConfigCallback() { @Override public void configure(Transport transport) { SshTransport sshTransport = (SshTransport) transport; sshTransport.setSshSessionFactory(new JschConfigSessionFactory() { @Override protected void configure(OpenSshConfig.Host hc, Session session) { session.setConfig("StrictHostKeyChecking", "no"); session.setPassword(""); } @Override protected JSch createDefaultJSch(FS fs) throws JSchException { JSch defaultJSch = super.createDefaultJSch(fs); defaultJSch.addIdentity("C:\\Users\\Colorful\\.ssh\\id_rsa.pub"); return defaultJSch; } }); } }) .call(); }
Example #27
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 #28
Source File: SSHClient.java From Kylin with Apache License 2.0 | 5 votes |
private Session newJSchSession() throws JSchException { JSch jsch = new JSch(); if (identityPath != null) { jsch.addIdentity(identityPath); } Session session = jsch.getSession(username, hostname, 22); if (password != null) { session.setPassword(password); } session.setConfig("StrictHostKeyChecking", "no"); return session; }
Example #29
Source File: SFtpUInfoTask.java From Aria with Apache License 2.0 | 5 votes |
@Override protected void getFileInfo(Session session) throws JSchException, UnsupportedEncodingException, SftpException { SFtpTaskOption option = (SFtpTaskOption) getWrapper().getTaskOption(); ChannelSftp channel = (ChannelSftp) session.openChannel("sftp"); channel.connect(1000); String remotePath = option.getUrlEntity().remotePath; String temp = CommonUtil.convertSFtpChar(getOption().getCharSet(), remotePath) + "/" + getWrapper().getEntity().getFileName(); SftpATTRS attr = null; try { attr = channel.stat(temp); } catch (Exception e) { ALog.d(TAG, String.format("文件不存在,remotePath:%s", remotePath)); } boolean isComplete = false; UploadEntity entity = getWrapper().getEntity(); if (attr != null && attr.getSize() == entity.getFileSize()) { isComplete = true; } CompleteInfo info = new CompleteInfo(); info.code = isComplete ? ISCOMPLETE : 200; info.obj = attr; channel.disconnect(); callback.onSucceed(getWrapper().getKey(), info); }
Example #30
Source File: ATest.java From aws-cf-templates with Apache License 2.0 | 5 votes |
protected final void probeSSH(final String host, final KeyPair key) { final Callable<Boolean> callable = () -> { final JSch jsch = new JSch(); final Session session = jsch.getSession("ec2-user", host); jsch.addIdentity(key.getKeyName(), key.getKeyMaterial().getBytes(), 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)); }