Java Code Examples for net.schmizz.sshj.SSHClient

The following examples show how to use net.schmizz.sshj.SSHClient. These examples are extracted from open source projects. 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 Project: cymbal   Source File: SshClientServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 2
Source Project: TeamSpeak-3-Java-API   Source File: SSHChannel.java    License: MIT License 6 votes vote down vote up
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 3
Source Project: datacollector   Source File: TestChrootSFTPClient.java    License: Apache License 2.0 6 votes vote down vote up
@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 4
Source Project: datacollector   Source File: TestChrootSFTPClient.java    License: Apache License 2.0 6 votes vote down vote up
@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 5
Source Project: datacollector   Source File: TestChrootSFTPClient.java    License: Apache License 2.0 6 votes vote down vote up
@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 6
Source Project: datacollector   Source File: TestChrootSFTPClient.java    License: Apache License 2.0 6 votes vote down vote up
@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 7
Source Project: datacollector   Source File: TestChrootSFTPClient.java    License: Apache License 2.0 6 votes vote down vote up
@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 8
Source Project: datacollector   Source File: TestChrootSFTPClient.java    License: Apache License 2.0 6 votes vote down vote up
@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 9
Source Project: datacollector   Source File: TestChrootSFTPClient.java    License: Apache License 2.0 6 votes vote down vote up
@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 10
Source Project: datacollector   Source File: TestChrootSFTPClient.java    License: Apache License 2.0 6 votes vote down vote up
@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 11
Source Project: lognavigator   Source File: SshLogAccessService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 12
Source Project: lognavigator   Source File: SshLogAccessService.java    License: Apache License 2.0 6 votes vote down vote up
@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 13
@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 14
Source Project: roboconf-platform   Source File: ConfiguratorOnCreation.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 15
Source Project: cymbal   Source File: SshClientServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
public SshClientServiceImpl() {
    defaultConfig = new DefaultConfig();

    // 免密登陆校验器
    Security.addProvider(new BouncyCastleProvider());

    // sshClient的缓存,避免每次命令都进行ssh连接的耗时
    sshClientCache = CacheBuilder.newBuilder().maximumSize(CACHE_CLIENT_MAX)
            .expireAfterAccess(CACHE_CLIENT_TTL, TimeUnit.SECONDS)
            .removalListener(new RemovalListener<SSHInfo, SSHClient>() {

                @Override
                public void onRemoval(RemovalNotification<SSHInfo, SSHClient> removalNotification) {
                    try {
                        removalNotification.getValue().disconnect();
                    } catch (IOException e) {
                        log.error("Close ssh connection error.", e);
                    }

                    log.debug("Ssh client to {} is expired.", removalNotification.getKey());
                }
            }).build(new CacheLoader<SSHInfo, SSHClient>() {

                @Override
                public SSHClient load(SSHInfo sshInfo) throws Exception {
                    return getSshCLient(sshInfo);
                }
            });
}
 
Example 16
Source Project: cyberduck   Source File: SFTPSession.java    License: GNU General Public License v3.0 5 votes vote down vote up
protected SSHClient connect(final HostKeyCallback key, final Config configuration) throws IOException {
    final SSHClient connection = new SSHClient(configuration);
    final int timeout = preferences.getInteger("connection.timeout.seconds") * 1000;
    connection.setTimeout(timeout);
    connection.setSocketFactory(new ProxySocketFactory(host));
    connection.addHostKeyVerifier(new HostKeyVerifier() {
        @Override
        public boolean verify(String hostname, int port, PublicKey publicKey) {
            try {
                return key.verify(host, publicKey);
            }
            catch(ConnectionCanceledException | ChecksumException e) {
                return false;
            }
        }
    });
    connection.addAlgorithmsVerifier(new AlgorithmsVerifier() {
        @Override
        public boolean verify(final NegotiatedAlgorithms negotiatedAlgorithms) {
            log.info(String.format("Negotiated algorithms %s", negotiatedAlgorithms));
            algorithms = negotiatedAlgorithms;
            return true;
        }
    });
    connection.setRemoteCharset(Charset.forName(host.getEncoding()));
    disconnectListener = new StateDisconnectListener();
    final Transport transport = connection.getTransport();
    transport.setDisconnectListener(disconnectListener);
    connection.connect(HostnameConfiguratorFactory.get(host.getProtocol()).getHostname(host.getHostname()), host.getPort());
    final KeepAlive keepalive = connection.getConnection().getKeepAlive();
    keepalive.setKeepAliveInterval(preferences.getInteger("ssh.heartbeat.seconds"));
    return connection;
}
 
Example 17
Source Project: cyberduck   Source File: SFTPSessionTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testAllHMAC() throws Exception {
    final DefaultConfig defaultConfig = new DefaultConfig();
    defaultConfig.setMACFactories(
        new HMACSHA2256.Factory(),
        new HMACSHA2512.Factory()
    );
    for(net.schmizz.sshj.common.Factory.Named<MAC> mac : defaultConfig.getMACFactories()) {
        final DefaultConfig configuration = new DefaultConfig();
        configuration.setMACFactories(Collections.singletonList(mac));
        final SSHClient client = session.connect(new DisabledHostKeyCallback(), configuration);
        assertTrue(client.isConnected());
        client.close();
    }
}
 
Example 18
Source Project: cyberduck   Source File: SFTPSessionTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testAES256CTRCipher() throws Exception {
    final DefaultConfig configuration = new DefaultConfig();
    configuration.setCipherFactories(Collections.singletonList(new AES256CTR.Factory()));
    final SSHClient client = session.connect(new DisabledHostKeyCallback(), configuration);
    assertTrue(client.isConnected());
    client.close();
}
 
Example 19
Source Project: cyberduck   Source File: SFTPSessionTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testECDHNistPKeyExchange() throws Exception {
    final DefaultConfig configuration = new DefaultConfig();
    configuration.setKeyExchangeFactories(Collections.singletonList(new ECDHNistP.Factory256()));
    final SSHClient client = session.connect(new DisabledHostKeyCallback(), configuration);
    assertTrue(client.isConnected());
    client.close();
}
 
Example 20
Source Project: datacollector   Source File: SSHClientRebuilder.java    License: Apache License 2.0 5 votes vote down vote up
public SSHClient build() throws IOException {
  SSHClient sshClient = new SSHClient(config);
  if (knownHosts != null) {
    sshClient.loadKnownHosts(knownHosts);
  } else {
    sshClient.addHostKeyVerifier(new PromiscuousVerifier());
  }
  KeyProvider keyProvider = null;
  if (password == null) {
    if (keyLocation != null) {
      if (keyPassphrase != null) {
        keyProvider = sshClient.loadKeys(keyLocation, keyPassphrase);
      } else {
        keyProvider = sshClient.loadKeys(keyLocation);
      }
    } else {
      if (keyPassphrase != null) {
        keyProvider = sshClient.loadKeys(keyPlainText, null, PasswordUtils.createOneOff(keyPassphrase.toCharArray()));
      } else {
        keyProvider = sshClient.loadKeys(keyPlainText, null, null);
      }
    }
  }
  sshClient.connect(hostname, port);
  if (password == null) {
    sshClient.authPublickey(username, keyProvider);
  } else {
    sshClient.authPassword(username, password);
  }
  sshClient.setTimeout(socketTimeout * 1000);
  sshClient.setConnectTimeout(connectionTimeout * 1000);
  return sshClient;
}
 
Example 21
Source Project: datacollector   Source File: SSHDUnitTest.java    License: Apache License 2.0 5 votes vote down vote up
protected SSHClient createSSHClient() throws IOException {
  SSHClient sshClient = new SSHClient();
  sshClient.addHostKeyVerifier(new PromiscuousVerifier());
  sshClient.connect("localhost", port);
  Assert.assertTrue(sshClient.isConnected());
  sshClient.authPassword(TESTUSER, TESTPASS);
  Assert.assertTrue(sshClient.isAuthenticated());
  return sshClient;
}
 
Example 22
Source Project: datacollector   Source File: TestChrootSFTPClient.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testOpenForReadingReadAheadInputStreamDisabled() throws Exception {
  File file = testFolder.newFile("file.txt");
  String text = "hello";
  Files.write(text.getBytes(Charset.forName("UTF-8")), file);
  Assert.assertEquals(text, Files.readFirstLine(file, Charset.forName("UTF-8")));

  path = testFolder.getRoot().getAbsolutePath();
  setupSSHD(path);
  SSHClient sshClient = createSSHClient();
  final SFTPClient sftpClient = sshClient.newSFTPClient();
  final ChrootSFTPClient chrootSFTPClient = createChrootSFTPClient(
      sftpClient,
      path,
      false,
      null,
      false,
      true
  );
  final InputStream is = chrootSFTPClient.openForReading(file.getName());
  try {
    Assert.assertThat(is, instanceOf(RemoteFile.RemoteFileInputStream.class));
    Assert.assertTrue(is.getClass().getName().startsWith(SFTPStreamFactory.class.getCanonicalName()));
    Assert.assertNotNull(is);
    Assert.assertEquals(text, IOUtils.toString(is, Charset.forName("UTF-8")));
  } finally {
    is.close();
  }
}
 
Example 23
Source Project: datacollector   Source File: TestChrootSFTPClient.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testOpenForWriting() throws Exception {
  String text = "hello";
  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());

      OutputStream os = sftpClient.openForWriting(p);
      Assert.assertTrue(os.getClass().getName().startsWith(SFTPStreamFactory.class.getCanonicalName()));
      Assert.assertNotNull(os);
      IOUtils.write(text, os, Charset.forName("UTF-8"));
      os.close();

      Assert.assertEquals(text, Files.readFirstLine(file, Charset.forName("UTF-8")));
    }
  }
}
 
Example 24
Source Project: datacollector   Source File: TestChrootSFTPClient.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testOpenForWritingExists() throws Exception {
  String text = "hello";
  String oldText = "goodbye";
  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(),
    }) {
      Files.write(oldText.getBytes(Charset.forName("UTF-8")), file);
      Assert.assertEquals(oldText, Files.readFirstLine(file, Charset.forName("UTF-8")));

      OutputStream os = sftpClient.openForWriting(p);
      Assert.assertNotNull(os);
      IOUtils.write(text, os, Charset.forName("UTF-8"));
      os.close();

      Assert.assertEquals(text, Files.readFirstLine(file, Charset.forName("UTF-8")));
    }
  }
}
 
Example 25
Source Project: datacollector   Source File: TestChrootSFTPClient.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testArchiveNoArchiveDir() throws Exception {
  path = testFolder.getRoot().getAbsolutePath();
  String dataPath = testFolder.newFolder("dataDir").getAbsolutePath();

  File fromFile = new File(dataPath, "file.txt");

  setupSSHD(path);
  SSHClient sshClient = createSSHClient();

  for (ChrootSFTPClient sftpClient : getClientsWithEquivalentRoots(sshClient, null)) {
    // We can specify a file as either a relative path "file" or an absolute path "/file" and they should be
    // equivalent
    for (String fromPath : new String[] {
        "dataDir/" + fromFile.getName(),
        "/dataDir/" + fromFile.getName(),
    }) {
      String text = "hello";
      Files.write(text.getBytes(Charset.forName("UTF-8")), fromFile);
      Assert.assertEquals(text, Files.readFirstLine(fromFile, Charset.forName("UTF-8")));
      sftpClient.stat(fromPath);

      try {
        sftpClient.archive(fromPath);
        Assert.fail("Expected an SFTPException");
      } catch (IOException e) {
        Assert.assertEquals("No archive directory defined - cannot archive", e.getMessage());
      }

      Assert.assertEquals(text, Files.readFirstLine(fromFile, Charset.forName("UTF-8")));
      Assert.assertEquals(text, IOUtils.toString(sftpClient.openForReading(fromPath)));
      sftpClient.stat(fromPath);
    }
  }
}
 
Example 26
Source Project: datacollector   Source File: TestChrootSFTPClient.java    License: Apache License 2.0 5 votes vote down vote up
private void testArchiveHelper(ArchiveHelperCallable callable) throws Exception {
  path = testFolder.getRoot().getAbsolutePath();
  File dataPath = testFolder.newFolder("dataDir");
  File archivePath = testFolder.newFolder("archiveDir");

  File fromFile = new File(dataPath, "file.txt");

  archivePath.delete();
  setupSSHD(path);
  SSHClient sshClient = createSSHClient();

  for (ChrootSFTPClient sftpClient : getClientsWithEquivalentRoots(sshClient, archivePath.getAbsolutePath())) {
    // We can specify a file as either a relative path "file" or an absolute path "/file" and they should be
    // equivalent
    for (String fromPath : new String[] {
        "dataDir/" + fromFile.getName(),
        "/dataDir/" + fromFile.getName(),
    }) {
      File toFile = new File(
          archivePath,
          dataPath.getName() + "/" + fromFile.getName());
      for (String toPath : new String[] {
          archivePath.getName() + "/" + dataPath.getName() + "/" + toFile.getName(),
          "/" + archivePath.getName() + "/" + dataPath.getName() + "/" + toFile.getName()
      }) {
        callable.call(sftpClient, fromFile, fromPath, toFile, toPath);
      }
    }
  }
}
 
Example 27
Source Project: datacollector   Source File: TestChrootSFTPClient.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRename() 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));

        sftpClient.rename(source, target);
        expectNotExist(() -> sftpClient.stat(source));
        sftpClient.stat(target);
        Assert.assertEquals(text, Files.readFirstLine(targetFile, Charset.forName("UTF-8")));
        Assert.assertEquals(text, IOUtils.toString(sftpClient.openForReading(target)));
      }
    }
  }
}
 
Example 28
Source Project: datacollector   Source File: TestChrootSFTPClient.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRenameSourceNotExist() throws Exception {
  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(),
      }) {
        sourceFile.delete();
        Assert.assertFalse(sourceFile.exists());
        expectNotExist(() -> sftpClient.stat(source));

        targetFile.delete();
        Assert.assertFalse(targetFile.exists());
        expectNotExist(() -> sftpClient.stat(target));

        expectNotExist(() -> {
          sftpClient.rename(source, target);
          return null;
        });
        Assert.assertFalse(targetFile.exists());
        expectNotExist(() -> sftpClient.stat(target));
      }
    }
  }
}
 
Example 29
Source Project: datacollector   Source File: TestChrootSFTPClient.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRenameTargetExist() throws Exception {
  String sourceText = "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(sourceText.getBytes(Charset.forName("UTF-8")), sourceFile);
        Assert.assertEquals(sourceText, 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);

        sftpClient.rename(source, target);
        expectNotExist(() -> sftpClient.stat(source));
        sftpClient.stat(target);
        Assert.assertEquals(sourceText, Files.readFirstLine(targetFile, Charset.forName("UTF-8")));
        Assert.assertEquals(sourceText, IOUtils.toString(sftpClient.openForReading(target)));
      }
    }
  }
}
 
Example 30
Source Project: datacollector   Source File: TestChrootSFTPClient.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBooleanRenameOverwriteIsTrueTargetFileDoesntExist() 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, true));
        expectNotExist(() -> sftpClient.stat(source));
        sftpClient.stat(target);
        Assert.assertEquals(text, Files.readFirstLine(targetFile, Charset.forName("UTF-8")));
      }
    }
  }
}