public SSHClient setupClient(Config config) { if (client == null) { client = new SSHClient(config); client.addHostKeyVerifier(fingerprint); } return client; }
SSHClient ssh = new SSHClient(); //ssh.useCompression(); ssh.loadKnownHosts(); ssh.connect("localhost"); try { ssh.authPublickey(System.getProperty("user.name")); new SCPDownloadClient(ssh).copy("ten", "/tmp"); } finally { ssh.disconnect(); }
@Test public void shouldNotThrowTimeoutOnDisconnect() throws IOException { fixture.getClient().authPassword("u", "u"); Session session = fixture.getClient().startSession(); session.allocateDefaultPTY(); Session.Shell shell = session.startShell(); session.close(); fixture.getClient().disconnect(); } }
/** * Authenticate {@code username} using the {@code "publickey"} authentication method, with keys from one or more * {@code locations} in the file system. * <p/> * In case multiple {@code locations} are specified; authentication is attempted in order as long as the {@code * "publickey"} authentication method is available. If there is an error loading keys from any of them (e.g. file * could not be read, file format not recognized) that key file it is ignored. * <p/> * This method does not provide a way to specify a passphrase. * * @param username user to authenticate * @param locations one or more locations in the file system containing the private key * * @throws UserAuthException in case of authentication failure * @throws TransportException if there was a transport-layer error */ public void authPublickey(String username, String... locations) throws UserAuthException, TransportException { final List<KeyProvider> keyProviders = new LinkedList<KeyProvider>(); for (String loc : locations) { try { log.debug("Attempting to load key from: {}", loc); keyProviders.add(loadKeys(loc)); } catch (IOException logged) { log.info("Could not load keys from {} due to: {}", loc, logged.getMessage()); } } authPublickey(username, keyProviders); }
/** * Create a new {@code SSHClient} connected to the remote machine using the * AdminAccess credentials as provided */ public static SSHClient newClient( Machine machine, AdminAccess adminAccess, int timeoutInMillis ) throws IOException { checkArgument(timeoutInMillis >= 0, "timeoutInMillis should be positive or 0"); final SSHClient client = new SSHClient(); client.addHostKeyVerifier(AcceptAnyHostKeyVerifier.INSTANCE); if (timeoutInMillis != 0) { client.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT); client.setTimeout(timeoutInMillis); } client.connect(machine.getPublicDnsName(), machine.getSshPort()); OpenSSHKeyFile key = new OpenSSHKeyFile(); key.init(adminAccess.getPrivateKey(), adminAccess.getPublicKey()); client.authPublickey(adminAccess.getUsername(), key); return client; }
@SuppressWarnings("resource") private SSHResources tryGetSSHSession() throws IOException { final SSHClient ssh = new SSHClient(); Session session = null; try { ssh.addHostKeyVerifier(new PromiscuousVerifier()); ssh.connect("localhost", vm.getSshForwardPort()); ssh.authPassword("root", ""); session = ssh.startSession(); return new SSHResources(ssh, session); } catch (Throwable ex) { if (session != null) { try { session.close(); } catch (Throwable ex1) { } } if (ssh.isConnected()) { ssh.disconnect(); } throw ex; } }
public Session getSession(String hostAddress) throws IOException { try { if (sshClient == null) { sshClient = new SSHClient(); } if (getSSHClient().isConnected()) return getSSHClient().startSession(); KeyProvider pkey = getSSHClient().loadKeys(getPrivateKeyLoc(), getKeyPass()); getSSHClient().loadKnownHosts(); getSSHClient().connect(hostAddress); getSSHClient().authPublickey(getUsername(), pkey); session = getSSHClient().startSession(); return session; } catch (NullPointerException ne) { throw new SecurityException("Cannot load security context for SSH", ne); } }
break; sshClient = new SSHClient(defaultConfig); sshClient.addHostKeyVerifier((h, p, k) -> true); sshClient.connect(ip, port); sshClient.setTimeout(this.readTimeout * 1000); sshClient.setConnectTimeout(this.connectTimeout * 1000); sshClient.getConnection().getKeepAlive().setKeepAliveInterval(this.keepAlive); if (StringUtils.isNotBlank(pemPath)) { log.info("Use key at [" + pemPath + "] to connect to the machine [" + ip + "]"); sshClient.authPublickey(user, pemPath); } else if (StringUtils.isNotBlank(pemContent)) { log.info("Use key content with length [" + pemContent.length() + "] to connect to the machine [" + ip + "]"); KeyFormat format = KeyProviderUtil.detectKeyFileFormat(pemContent, false); final FileKeyProvider fkp = Factory.Named.Util.create(sshClient.getTransport().getConfig().getFileKeyProviderFactories(), format.toString()); if (fkp == null) throw new SSHException("No provider available for " + format + " key file"); fkp.init(pemContent, null); sshClient.authPublickey(user, fkp); } else { sshClient.authPassword(user, password);
final SSHClient ssh = new SSHClient(); ssh.addHostKeyVerifier("XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX"); ssh.connect("host"); PKCS8KeyFile keyFile = new PKCS8KeyFile(); keyFile.init(new File("server_pem.pem")); ssh.auth("ec2-user", new AuthPublickey(keyFile)); try { final Session session = ssh.startSession(); try { final Command command = session.exec("whoami"); String response = IOUtils.readFully(command.getInputStream()).toString(); command.join(10, TimeUnit.SECONDS); return response; } finally { session.close(); } } finally { ssh.disconnect(); }
private void build() throws IOException { if (init) { return; } ssh = new SSHClient(); ssh.addHostKeyVerifier(new HostKeyVerifier() { @Override public boolean verify(String arg0, int arg1, PublicKey arg2) { return true; } }); ssh.connect(hostname, port); if (privateKey != null) { privateKeyFile = File.createTempFile("zstack", "tmp"); FileUtils.writeStringToFile(privateKeyFile, privateKey); ssh.authPublickey(username, privateKeyFile.getAbsolutePath()); } else { ssh.authPassword(username, password); } init = true; }
final SSHClient ssh = new SSHClient(); ssh.loadKnownHosts(); // or, to skip host verification: ssh.addHostKeyVerifier(new PromiscuousVerifier()) ssh.connect("localhost"); try { ssh.authPassword("user", "password"); // or ssh.authPublickey(System.getProperty("user.name")) final SFTPClient sftp = ssh.newSFTPClient(); try { sftp.get("test_file", "/tmp/test.tmp"); } finally { sftp.close(); } } finally { ssh.disconnect(); }
public void stopClient() { if (client != null && client.isConnected()) { try { client.disconnect(); } catch (IOException e) { throw new RuntimeException(e); } finally { client = null; } } else if (client != null) { client = null; } }
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(socketFactory); connection.addHostKeyVerifier(new HostKeyVerifier() { @Override public boolean verify(String hostname, int port, PublicKey publicKey) { connection.addAlgorithmsVerifier(new AlgorithmsVerifier() { @Override public boolean verify(final NegotiatedAlgorithms negotiatedAlgorithms) { 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;
Session session = null; try { session = ssh.startSession(); if (logger.isTraceEnabled()) { logger.trace(String.format("[start SSH] %s", cmd));
@Test public void shouldCorrectlyHandleSessionChannelEof() throws IOException, InterruptedException { fixture.setupConnectedDefaultClient().authPassword("jeroen", "jeroen"); Session session = fixture.getClient().startSession(); session.allocateDefaultPTY(); session.close(); Thread.sleep(1000); assertThat("Should still be connected", fixture.getClient().isConnected()); }
@Test public void shouldHandlePasswordChangeWithWrongPasswordOnFirstAttempt() throws IOException { SSHClient sshClient = fixture.setupConnectedDefaultClient(); sshClient.authPassword("jeroen", new PasswordFinder() { @Override public char[] reqPassword(Resource<?> resource) { return "changeme".toCharArray(); } @Override public boolean shouldRetry(Resource<?> resource) { return false; } }, new StaticPasswordUpdateProvider("bad", "jeroen")); assertThat("Should have been authenticated", sshClient.isAuthenticated()); }
@Override public final void connect(String password) throws RaspiQueryException { LOGGER.info("Connecting to host '{}' on port '{}'.", hostname, port); client = newAndroidSSHClient(); LOGGER.info("Using no host key verification."); client.addHostKeyVerifier(new PromiscuousVerifier()); try { client.connect(hostname, port); client.authPassword(username, password); } catch (UserAuthException e) { throw RaspiQueryException.createAuthenticationFailure(hostname, username, e); } catch (TransportException e) { throw RaspiQueryException.createTransportFailure(hostname, e); } catch (IOException e) { throw RaspiQueryException.createConnectionFailure(hostname, port, e); } }
public void connect() throws IOException { ssh.connect(host); if (connectMethod.equals(ConnectMethod.PASSWORD)) { ssh.authPassword(user, password); } else { ssh.authPublickey(user, keyFile); } }
@Test public void shouldExecuteBackgroundCommand() throws IOException { SSHClient sshClient = fixture.setupConnectedDefaultClient(); sshClient.authPassword("jeroen", "jeroen"); File file = new File(temp.getRoot(), "testdir"); assertThat("File should not exist", !file.exists()); // TODO figure out why this does not really execute in the background. Session.Command exec = sshClient.startSession().exec("mkdir " + file.getPath() + " &"); exec.join(); assertThat("File should exist", file.exists()); assertThat("File should be directory", file.isDirectory()); SFTPClient sftpClient = sshClient.newSFTPClient(); if (sftpClient.statExistence("&") != null) { sftpClient.rmdir("&"); // TODO fail here when this is fixed } } }
/** * Same as {@link #disconnect()}. * * @throws IOException */ @Override public void close() throws IOException { disconnect(); }