net.schmizz.sshj.SSHClient Java Examples
The following examples show how to use
net.schmizz.sshj.SSHClient.
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: SshLogAccessService.java From lognavigator with Apache License 2.0 | 6 votes |
/** * Override listFiles() method to share the ssh client among the different executed commands */ @Override public Set<FileInfo> listFiles(String logAccessConfigId, String subPath) throws LogAccessException { // Get the LogAccessConfig LogAccessConfig logAccessConfig = configService.getLogAccessConfig(logAccessConfigId); // Create ssh client, authenticate and put it into thread local for a shared use SSHClient sshClient = connectAndAuthenticate(logAccessConfig); sshClientThreadLocal.set(sshClient); // List files using prepared ssh client try { return super.listFiles(logAccessConfigId, subPath); } finally { sshClientThreadLocal.remove(); try { sshClient.disconnect(); } catch (IOException e) {} } }
Example #2
Source File: SshLogAccessService.java From lognavigator with Apache License 2.0 | 6 votes |
@Override public void downloadFile(String logAccessConfigId, String fileName, OutputStream downloadOutputStream) throws LogAccessException { // Get the LogAccessConfig LogAccessConfig logAccessConfig = configService.getLogAccessConfig(logAccessConfigId); // Create ssh client and authenticate SSHClient sshClient = connectAndAuthenticate(logAccessConfig); // Execute the download try { String filePath = fileName.startsWith("/") ? fileName : logAccessConfig.getDirectory() + "/" + fileName; sshClient.newSCPFileTransfer().download(filePath, new ScpStreamingSystemFile(downloadOutputStream)); } catch (IOException e) { throw new LogAccessException("Error when executing downloading " + fileName + " on " + logAccessConfig, e); } finally { try { sshClient.disconnect(); } catch (IOException ioe) {} } }
Example #3
Source File: TestChrootSFTPClient.java From datacollector with Apache License 2.0 | 6 votes |
@Test public void testExists() throws Exception { File file = testFolder.newFile("file.txt"); path = testFolder.getRoot().getAbsolutePath(); setupSSHD(path); SSHClient sshClient = createSSHClient(); for (ChrootSFTPClient sftpClient : getClientsWithEquivalentRoots(sshClient)) { // We can specify a file as either a relative path "file" or an absolute path "/file" and they should be // equivalent for (String p : new String[] { file.getName(), "/" + file.getName(), }) { Assert.assertTrue(sftpClient.exists(p)); } } }
Example #4
Source File: TestChrootSFTPClient.java From datacollector with Apache License 2.0 | 6 votes |
@Test public void testStatNotExist() throws Exception { File file = testFolder.newFile("file.txt"); file.delete(); Assert.assertFalse(file.exists()); path = testFolder.getRoot().getAbsolutePath(); setupSSHD(path); SSHClient sshClient = createSSHClient(); for (ChrootSFTPClient sftpClient : getClientsWithEquivalentRoots(sshClient)) { // We can specify a file as either a relative path "file" or an absolute path "/file" and they should be // equivalent for (String p : new String[]{ file.getName(), "/" + file.getName(), }) { expectNotExist(() -> sftpClient.stat(p)); } } }
Example #5
Source File: ConfiguratorOnTermination.java From roboconf-platform with Apache License 2.0 | 6 votes |
@Override Map<String,String> prepareConfiguration( TargetHandlerParameters parameters, SSHClient ssh, File tmpDir ) throws IOException { try { // Reset all the fields Map<String,String> keyToNewValue = new HashMap<> (); keyToNewValue.put( AGENT_APPLICATION_NAME, "" ); keyToNewValue.put( AGENT_SCOPED_INSTANCE_PATH, "" ); keyToNewValue.put( AGENT_DOMAIN, "" ); keyToNewValue.put( AGENT_PARAMETERS, Constants.AGENT_RESET ); return keyToNewValue; } finally { // Consider the IP as not used anymore, no matter what this.embedded.releaseIpAddress( this.ip ); } }
Example #6
Source File: TestChrootSFTPClient.java From datacollector with Apache License 2.0 | 6 votes |
@Test public void testLsNotExist() throws Exception { File dir = testFolder.newFile("dir"); dir.delete(); Assert.assertFalse(dir.exists()); path = testFolder.getRoot().getAbsolutePath(); setupSSHD(path); SSHClient sshClient = createSSHClient(); for (ChrootSFTPClient sftpClient : getClientsWithEquivalentRoots(sshClient)) { // We can specify a dir as either a relative path "dir" or an absolute path "/dir" and they should be // equivalent for (String p : new String[]{ dir.getName(), "/" + dir.getName(), }) { expectNotExist(() -> sftpClient.ls(p)); } } }
Example #7
Source File: TestChrootSFTPClient.java From datacollector with Apache License 2.0 | 6 votes |
@Test public void testSetSFTPClient() throws Exception { path = testFolder.getRoot().getAbsolutePath(); setupSSHD(path); SSHClient sshClient = createSSHClient(); ChrootSFTPClient sftpClient = new ChrootSFTPClient(sshClient.newSFTPClient(), path, false, false, false); sftpClient.ls(); // Close the SSH client so it's no longer usable and the SFTP client will get an exception sshClient.close(); try { sftpClient.ls(); Assert.fail("Expected a TransportException"); } catch (TransportException se) { Assert.assertEquals("Socket closed", se.getMessage()); } // Set a new SSH client and try again sftpClient.setSFTPClient(createSSHClient().newSFTPClient()); sftpClient.ls(); }
Example #8
Source File: TestChrootSFTPClient.java From datacollector with Apache License 2.0 | 6 votes |
@Test public void testRootNotExistAndMake() throws Exception { path = testFolder.getRoot().getAbsolutePath(); setupSSHD(path); SSHClient sshClient = createSSHClient(); Assert.assertFalse(new File(path + "/blah").exists()); // absolute path new ChrootSFTPClient(sshClient.newSFTPClient(), path + "/blah", false, true, false); Assert.assertTrue(new File(path + "/blah").exists()); // relative path new ChrootSFTPClient(sshClient.newSFTPClient(), "/blah", true, true, false); Assert.assertTrue(new File(path + "/blah").exists()); // relative path new ChrootSFTPClient(sshClient.newSFTPClient(), "blah", true, true, false); Assert.assertTrue(new File(path + "/blah").exists()); }
Example #9
Source File: SSHChannel.java From TeamSpeak-3-Java-API with MIT License | 6 votes |
SSHChannel(TS3Config config) throws IOException { if (!config.hasLoginCredentials()) { throw new TS3ConnectionFailedException("Anonymous queries are not supported when using SSH.\n" + "\t\tYou must specify a query username and password using TS3Config#setLoginCredentials."); } try { client = new SSHClient(); File knownHostsFile = new File(OpenSSHKnownHosts.detectSSHDir(), KNOWN_HOSTS_FILE_NAME); client.addHostKeyVerifier(new AutoAddKnownHosts(knownHostsFile)); client.setConnectTimeout(config.getCommandTimeout()); client.setTimeout(config.getCommandTimeout()); client.setRemoteCharset(StandardCharsets.UTF_8); client.connect(config.getHost(), config.getQueryPort()); client.authPassword(config.getUsername(), config.getPassword()); session = client.startSession(); session.startShell(); } catch (UserAuthException uae) { close(); throw new TS3ConnectionFailedException("Invalid query username or password"); } catch (IOException ioe) { close(); throw ioe; } }
Example #10
Source File: ConfiguratorOnCreation.java From roboconf-platform with Apache License 2.0 | 6 votes |
/** * Updates the configuration file of an agent. * @param parameters * @param ssh * @param tmpDir * @param keyToNewValue * @throws IOException */ void updateAgentConfigurationFile( TargetHandlerParameters parameters, SSHClient ssh, File tmpDir, Map<String,String> keyToNewValue ) throws IOException { this.logger.fine( "Updating agent parameters on remote host..." ); // Update the agent's configuration file String agentConfigDir = Utils.getValue( parameters.getTargetProperties(), SCP_AGENT_CONFIG_DIR, DEFAULT_SCP_AGENT_CONFIG_DIR ); File localAgentConfig = new File( tmpDir, Constants.KARAF_CFG_FILE_AGENT ); File remoteAgentConfig = new File( agentConfigDir, Constants.KARAF_CFG_FILE_AGENT ); // Download remote agent config file... ssh.newSCPFileTransfer().download(remoteAgentConfig.getCanonicalPath(), new FileSystemFile(tmpDir)); // Replace "parameters" property to point on the user data file... String config = Utils.readFileContent(localAgentConfig); config = Utils.updateProperties( config, keyToNewValue ); Utils.writeStringInto(config, localAgentConfig); // Then upload agent config file back ssh.newSCPFileTransfer().upload(new FileSystemFile(localAgentConfig), agentConfigDir); }
Example #11
Source File: TestChrootSFTPClient.java From datacollector with Apache License 2.0 | 6 votes |
@Test public void testOpenForReadingNotExist() throws Exception { File file = testFolder.newFile("file.txt"); file.delete(); Assert.assertFalse(file.exists()); path = testFolder.getRoot().getAbsolutePath(); setupSSHD(path); SSHClient sshClient = createSSHClient(); for (ChrootSFTPClient sftpClient : getClientsWithEquivalentRoots(sshClient)) { // We can specify a file as either a relative path "file" or an absolute path "/file" and they should be // equivalent for (String p : new String[] { file.getName(), "/" + file.getName(), }) { expectNotExist(() -> sftpClient.openForReading(p)); } } }
Example #12
Source File: TestChrootSFTPClient.java From datacollector with Apache License 2.0 | 6 votes |
@Test public void testDelete() throws Exception { File file = testFolder.newFile("file.txt"); path = testFolder.getRoot().getAbsolutePath(); setupSSHD(path); SSHClient sshClient = createSSHClient(); for (ChrootSFTPClient sftpClient : getClientsWithEquivalentRoots(sshClient)) { // We can specify a file as either a relative path "file" or an absolute path "/file" and they should be // equivalent for (String p : new String[] { file.getName(), "/" + file.getName(), }) { file.createNewFile(); Assert.assertTrue(file.exists()); sftpClient.stat(p); sftpClient.delete(p); expectNotExist(() -> sftpClient.stat(p)); } } }
Example #13
Source File: TestChrootSFTPClient.java From datacollector with Apache License 2.0 | 6 votes |
@Test public void testDeleteNotExist() throws Exception { File file = testFolder.newFile("file.txt"); path = testFolder.getRoot().getAbsolutePath(); setupSSHD(path); SSHClient sshClient = createSSHClient(); for (ChrootSFTPClient sftpClient : getClientsWithEquivalentRoots(sshClient)) { // We can specify a file as either a relative path "file" or an absolute path "/file" and they should be // equivalent for (String p : new String[] { file.getName(), "/" + file.getName(), }) { file.delete(); Assert.assertFalse(file.exists()); expectNotExist(() -> sftpClient.stat(p)); expectNotExist(() -> {sftpClient.delete(p); return null;}); } } }
Example #14
Source File: ConfiguratorOnCreationTest.java From roboconf-platform with Apache License 2.0 | 5 votes |
@Test public void testPrepareConfiguration() throws Exception { // Prepare the mocks File tmpDir = this.folder.newFolder(); TargetHandlerParameters parameters = new TargetHandlerParameters() .targetProperties( new HashMap<String,String>( 0 )); SSHClient ssh = Mockito.mock( SSHClient.class ); SCPFileTransfer scp = Mockito.mock( SCPFileTransfer.class ); Mockito.when( ssh.newSCPFileTransfer()).thenReturn( scp ); // Invoke the method EmbeddedHandler embedded = new EmbeddedHandler(); embedded.karafData = this.folder.newFolder().getAbsolutePath(); ConfiguratorOnCreation configurator = new ConfiguratorOnCreation( parameters, "ip", "machineId", embedded ); Map<String,String> keyToNewValue = configurator.prepareConfiguration( parameters, ssh, tmpDir ); // We made one upload for this method! Mockito.verify( scp ).upload( Mockito.any( LocalSourceFile.class ), Mockito.anyString()); // Prevent a compilation warning about leaks configurator.close(); // Verify the map's content Assert.assertEquals( 4, keyToNewValue.size()); Assert.assertEquals( "", keyToNewValue.get( AGENT_APPLICATION_NAME )); Assert.assertEquals( "", keyToNewValue.get( AGENT_SCOPED_INSTANCE_PATH )); Assert.assertEquals( "", keyToNewValue.get( AGENT_DOMAIN )); Assert.assertEquals( "file:" + DEFAULT_SCP_AGENT_CONFIG_DIR + "/" + USER_DATA_FILE, keyToNewValue.get( AGENT_PARAMETERS )); }
Example #15
Source File: RaspiQuery.java From rpicheck with MIT License | 5 votes |
/** * Checks if the path is a correct path to vcgencmd. * * @param path the path to check * @param client authenticated and open client * @return true, if correct, false if not * @throws IOException if something ssh related goes wrong */ private boolean isValidVcgencmdPath(String path, SSHClient client) throws IOException { final Session session = client.startSession(); session.allocateDefaultPTY(); LOGGER.debug("Checking vcgencmd location: {}", path); final Command cmd = session.exec(path); cmd.join(30, TimeUnit.SECONDS); session.close(); final Integer exitStatus = cmd.getExitStatus(); final String output = IOUtils.readFully(cmd.getInputStream()).toString().toLowerCase(); LOGGER.debug("Path check output: {}", output); return exitStatus != null && exitStatus.equals(0) && !output.contains("not found") && !output.contains("no such file or directory"); }
Example #16
Source File: SftpFileTransferLiveTest.java From tutorials with MIT License | 5 votes |
private SSHClient setupSshj() throws IOException { SSHClient client = new SSHClient(); client.addHostKeyVerifier(new PromiscuousVerifier()); client.connect(remoteHost); client.authPassword(username, password); return client; }
Example #17
Source File: SshJClientActions.java From cloudbreak with Apache License 2.0 | 5 votes |
private static Pair<Integer, String> execute(SSHClient ssh, String command) throws IOException { LOGGER.info("Waiting to SSH command to be executed..."); try (Session session = startSshSession(ssh); Session.Command cmd = session.exec(command); OutputStream os = IOUtils.readFully(cmd.getInputStream())) { Log.log(LOGGER, format("The following SSH command [%s] is going to be executed on host [%s]", ssh.getConnection().getTransport().getRemoteHost(), command)); cmd.join(10L, TimeUnit.SECONDS); return Pair.of(cmd.getExitStatus(), os.toString()); } }
Example #18
Source File: SftpFileTransferLiveTest.java From tutorials with MIT License | 5 votes |
@Test public void whenUploadFileUsingSshj_thenSuccess() throws IOException { SSHClient sshClient = setupSshj(); SFTPClient sftpClient = sshClient.newSFTPClient(); sftpClient.put(localFile, remoteDir + "sshjFile.txt"); sftpClient.close(); sshClient.disconnect(); }
Example #19
Source File: SshJClientActions.java From cloudbreak with Apache License 2.0 | 5 votes |
private void checkNoOutboundInternetTraffic(String instanceIP) { String checkInternetCommand = "curl --max-time 30 cloudera.com"; try (SSHClient sshClient = createSshClient(instanceIP)) { Pair<Integer, String> cmdOut = execute(sshClient, checkInternetCommand); Log.log(LOGGER, format("Command exit status [%s] and result [%s].", cmdOut.getKey(), cmdOut.getValue())); if (cmdOut.getKey() == 0) { throw new TestFailException("Instance [" + instanceIP + "] has internet coonection but shouldn't have!"); } } catch (Exception e) { LOGGER.error("SSH fail on [{}] while executing command [{}]", instanceIP, checkInternetCommand); throw new TestFailException(" SSH fail on [" + instanceIP + "] while executing command [" + checkInternetCommand + "]."); } }
Example #20
Source File: SshJClientActions.java From cloudbreak with Apache License 2.0 | 5 votes |
public SdxInternalTestDto checkFilesByNameAndPath(SdxInternalTestDto testDto, SdxClient sdxClient, List<String> hostGroupNames, String filePath, String fileName, long requiredNumberOfFiles) { String fileListCommand = String.format("find %s -type f -name %s", filePath, fileName); AtomicLong quantity = new AtomicLong(0); /** * Right now only the Private IP is available for an Instance. */ getSdxInstanceGroupIps(testDto.getName(), sdxClient, hostGroupNames, false).forEach(instanceIP -> { try (SSHClient sshClient = createSshClient(instanceIP)) { Pair<Integer, String> cmdOut = execute(sshClient, fileListCommand); Log.log(LOGGER, format("Command exit status [%s] and result [%s].", String.valueOf(cmdOut.getKey()), cmdOut.getValue())); List<String> cmdOutputValues = List.of(cmdOut.getValue().split("[\\r\\n\\t]")) .stream().filter(Objects::nonNull).collect(Collectors.toList()); boolean fileFound = cmdOutputValues.stream() .anyMatch(outputValue -> outputValue.strip().startsWith("/")); String foundFilePath = cmdOutputValues.stream() .filter(outputValue -> outputValue.strip().startsWith("/")).findFirst().orElse(null); Log.log(LOGGER, format("The file is present [%s] at [%s] path.", fileFound, foundFilePath)); quantity.set(cmdOutputValues.stream() .filter(outputValue -> outputValue.strip().startsWith("/")).count()); } catch (Exception e) { LOGGER.error("SSH fail on [{}] while getting info for [{}] file", instanceIP, filePath); throw new TestFailException(" SSH fail on [" + instanceIP + "] while getting info for [" + filePath + "] file."); } }); if (requiredNumberOfFiles == quantity.get()) { Log.log(LOGGER, format(" File [%s] is available at [%s] host group(s). ", filePath, hostGroupNames.toString())); } else { LOGGER.error("File [{}] is NOT available at [{}] host group(s).", filePath, hostGroupNames.toString()); throw new TestFailException(" File at: " + filePath + " path is NOT available at: " + hostGroupNames.toString() + " host group(s)."); } return testDto; }
Example #21
Source File: AwsYcloudHybridCloudTest.java From cloudbreak with Apache License 2.0 | 5 votes |
private void testShhAuthenticationFailure(String username, String host) throws IOException { SSHClient client = null; try { client = getSshClient(host); client.authPassword(username, MOCK_UMS_PASSWORD_INVALID); fail("SSH authentication passed with invalid password."); } catch (UserAuthException ex) { //Expected } if (client != null) { client.close(); } }
Example #22
Source File: TestChrootSFTPClient.java From datacollector with Apache License 2.0 | 5 votes |
@Test public void testBooleanRenameOverwriteIsFalseTargetFileDoesntExist() throws Exception { String text = "hello"; File sourceFile = testFolder.newFile("source.txt"); File targetFile = testFolder.newFile("target.txt"); path = testFolder.getRoot().getAbsolutePath(); setupSSHD(path); SSHClient sshClient = createSSHClient(); for (ChrootSFTPClient sftpClient : getClientsWithEquivalentRoots(sshClient)) { // We can specify a file as either a relative path "file" or an absolute path "/file" and they should be // equivalent for (String source : new String[] { sourceFile.getName(), "/" + sourceFile.getName(), }) { for (String target : new String[] { targetFile.getName(), "/" + targetFile.getName(), }) { Files.write(text.getBytes(Charset.forName("UTF-8")), sourceFile); Assert.assertEquals(text, Files.readFirstLine(sourceFile, Charset.forName("UTF-8"))); sftpClient.stat(source); targetFile.delete(); Assert.assertFalse(targetFile.exists()); expectNotExist(() -> sftpClient.stat(target)); Assert.assertTrue(sftpClient.rename(source, target, false)); expectNotExist(() -> sftpClient.stat(source)); sftpClient.stat(target); Assert.assertEquals(text, Files.readFirstLine(targetFile, Charset.forName("UTF-8"))); } } } }
Example #23
Source File: SshLogAccessService.java From lognavigator with Apache License 2.0 | 5 votes |
@Override public InputStream executeCommand(String logAccessConfigId, String shellCommand) throws LogAccessException { // Get the LogAccessConfig LogAccessConfig logAccessConfig = configService.getLogAccessConfig(logAccessConfigId); // Create ssh client and authenticate SSHClient sshClient = sshClientThreadLocal.get(); boolean closeSshClient = false; if (sshClient == null) { sshClient = connectAndAuthenticate(logAccessConfig); closeSshClient = true; } // Define the precommand (if any) String precommand = ""; if (StringUtils.hasText(logAccessConfig.getPreCommand())) { precommand = logAccessConfig.getPreCommand() + " && "; } // Execute the shell command Session session = null; Command resultCommand; try { session = sshClient.startSession(); resultCommand = session.exec("cd \"" + logAccessConfig.getDirectory() + "\" && " + precommand + shellCommand); } catch (SSHException e) { IOUtils.closeQuietly(session, sshClient); throw new LogAccessException("Error when executing command " + shellCommand + " to " + logAccessConfig, e); } // Get and return the result stream InputStream sequenceStream = new SequenceInputStream(resultCommand.getInputStream(), resultCommand.getErrorStream()); InputStream resultStream = new SshCloseFilterInputStream(sequenceStream, resultCommand, session, (closeSshClient ? sshClient : null)); return resultStream; }
Example #24
Source File: Main.java From aedict with GNU General Public License v3.0 | 5 votes |
private void upload() throws Exception { System.out.println("Uploading"); final SSHClient ssh = new SSHClient(); ssh.loadKnownHosts(); String password = config.password; if (password == null) { System.out.println("Enter password"); final Scanner s = new Scanner(System.in); password = s.nextLine(); if (MiscUtils.isBlank(password)) { throw new RuntimeException("Invalid password: blank"); } } System.out.println("Connecting"); ssh.connect("rt.sk"); try { System.out.println("Authenticating"); ssh.authPassword("moto", password); System.out.println("Uploading version"); final String targetFName = REMOTE_DIR + "/" + config.getTargetFileName(); exec(ssh, "echo `date +%Y%m%d` >" + REMOTE_DIR + "/" + config.getTargetFileName() + ".version"); exec(ssh, "rm -f " + targetFName); System.out.println("Uploading"); final SCPFileTransfer ft = ssh.newSCPFileTransfer(); ft.upload(config.getTargetFileName(), targetFName); } finally { ssh.disconnect(); } }
Example #25
Source File: Main.java From aedict with GNU General Public License v3.0 | 5 votes |
private static void exec(SSHClient ssh, String cmd) throws ConnectionException, TransportException, IOException { final Session s = ssh.startSession(); try { final Command c = s.exec(cmd); if (c.getExitErrorMessage() != null) { throw new RuntimeException("Command " + cmd + " failed to execute with status " + c.getExitStatus() + ": " + c.getExitErrorMessage() + ", " + c.getErrorAsString()); } } finally { MiscUtils.closeQuietly(s); } }
Example #26
Source File: TestSFTPRemoteConnector.java From datacollector with Apache License 2.0 | 5 votes |
protected void testVerifyAndReconnectHelper(RemoteConnector connector) throws Exception { SFTPRemoteConnectorForTest con = (SFTPRemoteConnectorForTest) connector; // We'll fail the first call to sftpClient.ls, which will cause verifyAndReconnect to replace sshClient with // a new one con.sftpClient = Mockito.spy(con.sftpClient); SSHClient originalSshClient = con.sshClient; Mockito.when(con.sftpClient.ls()).thenThrow(new IOException("")).thenCallRealMethod(); connector.verifyAndReconnect(); Assert.assertNotEquals(originalSshClient, con.sshClient); verifyConnection(connector); }
Example #27
Source File: TestChrootSFTPClient.java From datacollector with Apache License 2.0 | 5 votes |
private List<ChrootSFTPClient> getClientsWithEquivalentRoots(SSHClient sshClient, String archiveDir) throws Exception { SFTPClient rawSftpClient = sshClient.newSFTPClient(); // The following clients are all equivalent, just using different ways of declaring the paths List<ChrootSFTPClient> clients = new ArrayList<>(); // root and archiveDir are both absolute paths clients.add(createChrootSFTPClient(rawSftpClient, path, false, archiveDir, false)); // root is relative to home dir, archiveDir is absolute clients.add(createChrootSFTPClient(rawSftpClient, "/", true, archiveDir, false)); // root is relative to home dir, archiveDir is absolute clients.add(createChrootSFTPClient(rawSftpClient, "", true, archiveDir, false)); if (archiveDir != null) { String relArchiveDir = Paths.get(path).relativize(Paths.get(archiveDir)).toString(); // root is absolute, archiveDir is relative to home dir clients.add(createChrootSFTPClient(rawSftpClient, path, false, "/" + relArchiveDir, true)); // root and archiveDir are both relative to home dir clients.add(createChrootSFTPClient(rawSftpClient, "/", true, "/" + relArchiveDir, true)); // root and archiveDir are both relative to home dir clients.add(createChrootSFTPClient(rawSftpClient, "", true, "/" + relArchiveDir, true)); // root is absolute, archiveDir is relative to home dir clients.add(createChrootSFTPClient(rawSftpClient, path, false, relArchiveDir, true)); // root and archiveDir are both relative to home dir clients.add(createChrootSFTPClient(rawSftpClient, "/", true, relArchiveDir, true)); // root and archiveDir are both relative to home dir clients.add(createChrootSFTPClient(rawSftpClient, "", true, relArchiveDir, true)); } return clients; }
Example #28
Source File: TestChrootSFTPClient.java From datacollector with Apache License 2.0 | 5 votes |
@Test public void testBooleanRenameOverwriteIsFalseTargetFileExists() throws Exception { String text = "hello"; String targetText = "goodbye"; File sourceFile = testFolder.newFile("source.txt"); File targetFile = testFolder.newFile("target.txt"); path = testFolder.getRoot().getAbsolutePath(); setupSSHD(path); SSHClient sshClient = createSSHClient(); for (ChrootSFTPClient sftpClient : getClientsWithEquivalentRoots(sshClient)) { // We can specify a file as either a relative path "file" or an absolute path "/file" and they should be // equivalent for (String source : new String[] { sourceFile.getName(), "/" + sourceFile.getName(), }) { for (String target : new String[] { targetFile.getName(), "/" + targetFile.getName(), }) { Files.write(text.getBytes(Charset.forName("UTF-8")), sourceFile); Assert.assertEquals(text, Files.readFirstLine(sourceFile, Charset.forName("UTF-8"))); sftpClient.stat(source); Files.write(targetText.getBytes(Charset.forName("UTF-8")), targetFile); Assert.assertEquals(targetText, Files.readFirstLine(targetFile, Charset.forName("UTF-8"))); sftpClient.stat(target); Assert.assertFalse(sftpClient.rename(source, target, false)); sftpClient.stat(source); sftpClient.stat(target); Assert.assertEquals(targetText, Files.readFirstLine(targetFile, Charset.forName("UTF-8"))); } } } }
Example #29
Source File: TestChrootSFTPClient.java From datacollector with Apache License 2.0 | 5 votes |
@Test public void testBooleanRenameOverwriteIsTrueTargetFileExists() throws Exception { String text = "hello"; String targetText = "goodbye"; File sourceFile = testFolder.newFile("source.txt"); File targetFile = testFolder.newFile("target.txt"); path = testFolder.getRoot().getAbsolutePath(); setupSSHD(path); SSHClient sshClient = createSSHClient(); for (ChrootSFTPClient sftpClient : getClientsWithEquivalentRoots(sshClient)) { // We can specify a file as either a relative path "file" or an absolute path "/file" and they should be // equivalent for (String source : new String[] { sourceFile.getName(), "/" + sourceFile.getName(), }) { for (String target : new String[] { targetFile.getName(), "/" + targetFile.getName(), }) { Files.write(text.getBytes(Charset.forName("UTF-8")), sourceFile); Assert.assertEquals(text, Files.readFirstLine(sourceFile, Charset.forName("UTF-8"))); sftpClient.stat(source); Files.write(targetText.getBytes(Charset.forName("UTF-8")), targetFile); Assert.assertEquals(targetText, Files.readFirstLine(targetFile, Charset.forName("UTF-8"))); sftpClient.stat(target); Assert.assertTrue(sftpClient.rename(source, target, true)); expectNotExist(() -> sftpClient.stat(source)); sftpClient.stat(target); Assert.assertEquals(text, Files.readFirstLine(targetFile, Charset.forName("UTF-8"))); } } } }
Example #30
Source File: SshClientServiceImpl.java From cymbal with Apache License 2.0 | 5 votes |
private SSHClient getSshCLient(final SSHInfo sshInfo) throws IOException { SSHClient ssh = new SSHClient(defaultConfig); // 登陆验证器 ssh.addHostKeyVerifier(new PromiscuousVerifier()); // ? ssh.loadKnownHosts(); // do connect ssh.connect(sshInfo.getHostName()); // 加载免密登陆私钥 KeyProvider keyProvider = ssh.loadKeys(keyPath); ssh.authPublickey(sshInfo.getUser(), keyProvider); return ssh; }