Java Code Examples for net.schmizz.sshj.SSHClient#connect()

The following examples show how to use net.schmizz.sshj.SSHClient#connect() . 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: SSHChannel.java    From TeamSpeak-3-Java-API with 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 2
Source File: SshClientServiceImpl.java    From cymbal with Apache License 2.0 5 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 3
Source File: SshjHolderTests.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
public static void sshjConnectTest() throws IOException, InterruptedException {
	SSHClient ssh = new SSHClient();
	ssh.addHostKeyVerifier(new PromiscuousVerifier());
	ssh.connect("10.0.0.160");
	KeyProvider keyProvider = ssh.loadKeys(new String(PRIVATE_KEY), null, null);
	ssh.authPublickey("root", keyProvider);
	Session session = ssh.startSession();
	// TODO
	// session.allocateDefaultPTY();
	Session.Shell shell = session.startShell();
	String command = "mvn -version\n";

	OutputStream outputStream = shell.getOutputStream();
	outputStream.write(command.getBytes());
	outputStream.flush();
	outputStream.close();

	InputStream inputStream = shell.getInputStream();
	InputStream errorStream = shell.getErrorStream();

	Thread.sleep(1000);
	shell.close();
	if (nonNull(inputStream)) {
		String message = readFullyToString(inputStream);
		System.out.println(message);
	}
	if (nonNull(errorStream)) {
		String errmsg = readFullyToString(errorStream);
		System.out.println(errmsg);
	}

	session.close();
	ssh.close();

}
 
Example 4
Source File: SFTPSession.java    From cyberduck with 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 5
Source File: SSHClientRebuilder.java    From datacollector with 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 6
Source File: SSHDUnitTest.java    From datacollector with 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 7
Source File: Main.java    From aedict with GNU General Public License v3.0 5 votes vote down vote up
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 8
Source File: AwsYcloudHybridCloudTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private SSHClient getSshClient(String host) throws IOException {
    SSHClient client = new SSHClient();
    client.addHostKeyVerifier(new PromiscuousVerifier());
    client.connect(host, SSH_PORT);
    client.setConnectTimeout(SSH_CONNECT_TIMEOUT);

    return client;
}
 
Example 9
Source File: SshJClient.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
protected SSHClient createSshClient(String host) throws IOException {
    SSHClient client = new SSHClient();

    client.addHostKeyVerifier(new PromiscuousVerifier());
    client.connect(host, 22);
    client.setConnectTimeout(120000);
    client.authPublickey("cloudbreak", defaultPrivateKeyFile);
    Log.log(LOGGER, format("SSH client has been authenticated [%s] with at [%s]", client.isAuthenticated(), client.getRemoteHostname()));

    return client;
}
 
Example 10
Source File: SftpFileTransferLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
private SSHClient setupSshj() throws IOException {
    SSHClient client = new SSHClient();
    client.addHostKeyVerifier(new PromiscuousVerifier());
    client.connect(remoteHost);
    client.authPassword(username, password);
    return client;
}
 
Example 11
Source File: RudimentaryPTY.java    From karamel with Apache License 2.0 4 votes vote down vote up
public static void main(String... args)
    throws IOException {
  String privateKey = "-----BEGIN RSA PRIVATE KEY-----\n"
      + "MIIEogIBAAKCAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzI\n"
      + "w+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9HZyN1Q9qgCgzUFtdOKLv6IedplqoP\n"
      + "kcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2\n"
      + "hMNG0zQPyUecp4pzC6kivAIhyfHilFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NO\n"
      + "Td0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcW\n"
      + "yLbIbEgE98OHlnVYCzRdK8jlqm8tehUc9c9WhQIBIwKCAQEA4iqWPJXtzZA68mKd\n"
      + "ELs4jJsdyky+ewdZeNds5tjcnHU5zUYE25K+ffJED9qUWICcLZDc81TGWjHyAqD1\n"
      + "Bw7XpgUwFgeUJwUlzQurAv+/ySnxiwuaGJfhFM1CaQHzfXphgVml+fZUvnJUTvzf\n"
      + "TK2Lg6EdbUE9TarUlBf/xPfuEhMSlIE5keb/Zz3/LUlRg8yDqz5w+QWVJ4utnKnK\n"
      + "iqwZN0mwpwU7YSyJhlT4YV1F3n4YjLswM5wJs2oqm0jssQu/BT0tyEXNDYBLEF4A\n"
      + "sClaWuSJ2kjq7KhrrYXzagqhnSei9ODYFShJu8UWVec3Ihb5ZXlzO6vdNQ1J9Xsf\n"
      + "4m+2ywKBgQD6qFxx/Rv9CNN96l/4rb14HKirC2o/orApiHmHDsURs5rUKDx0f9iP\n"
      + "cXN7S1uePXuJRK/5hsubaOCx3Owd2u9gD6Oq0CsMkE4CUSiJcYrMANtx54cGH7Rk\n"
      + "EjFZxK8xAv1ldELEyxrFqkbE4BKd8QOt414qjvTGyAK+OLD3M2QdCQKBgQDtx8pN\n"
      + "CAxR7yhHbIWT1AH66+XWN8bXq7l3RO/ukeaci98JfkbkxURZhtxV/HHuvUhnPLdX\n"
      + "3TwygPBYZFNo4pzVEhzWoTtnEtrFueKxyc3+LjZpuo+mBlQ6ORtfgkr9gBVphXZG\n"
      + "YEzkCD3lVdl8L4cw9BVpKrJCs1c5taGjDgdInQKBgHm/fVvv96bJxc9x1tffXAcj\n"
      + "3OVdUN0UgXNCSaf/3A/phbeBQe9xS+3mpc4r6qvx+iy69mNBeNZ0xOitIjpjBo2+\n"
      + "dBEjSBwLk5q5tJqHmy/jKMJL4n9ROlx93XS+njxgibTvU6Fp9w+NOFD/HvxB3Tcz\n"
      + "6+jJF85D5BNAG3DBMKBjAoGBAOAxZvgsKN+JuENXsST7F89Tck2iTcQIT8g5rwWC\n"
      + "P9Vt74yboe2kDT531w8+egz7nAmRBKNM751U/95P9t88EDacDI/Z2OwnuFQHCPDF\n"
      + "llYOUI+SpLJ6/vURRbHSnnn8a/XG+nzedGH5JGqEJNQsz+xT2axM0/W/CRknmGaJ\n"
      + "kda/AoGANWrLCz708y7VYgAtW2Uf1DPOIYMdvo6fxIB5i9ZfISgcJ/bbCUkFrhoH\n"
      + "+vq/5CIWxCPp0f85R4qxxQ5ihxJ0YDQT9Jpx4TMss4PSavPaBH3RXow5Ohe+bYoQ\n"
      + "NE5OgEXk2wVfZczCZpigBKbKZHNYcelXtTt/nP3rsCuGcM4h53s=\n"
      + "-----END RSA PRIVATE KEY-----";

  String publicKey = "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzIw+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9HZyN1Q9qgCgzUFtdOKLv6IedplqoPkcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2hMNG0zQPyUecp4pzC6kivAIhyfHilFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NOTd0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcWyLbIbEgE98OHlnVYCzRdK8jlqm8tehUc9c9WhQ== vagrant insecure public key";
  SSHClient client = new SSHClient();
  client.addHostKeyVerifier(new PromiscuousVerifier());
  KeyProvider keys = client.loadKeys(privateKey, publicKey, null);
  client.connect("192.168.33.10", 22);
  client.authPublickey("vagrant", keys);
  try {

    final Session session = client.startSession();
    try {

      session.allocateDefaultPTY();

      final Shell shell = session.startShell();

      new StreamCopier(shell.getInputStream(), System.out, LoggerFactory.DEFAULT)
          .bufSize(shell.getLocalMaxPacketSize())
          .spawn("stdout");

      new StreamCopier(shell.getErrorStream(), System.err, LoggerFactory.DEFAULT)
          .bufSize(shell.getLocalMaxPacketSize())
          .spawn("stderr");

      // Now make System.in act as stdin. To exit, hit Ctrl+D (since that results in an EOF on System.in)
      // This is kinda messy because java only allows console input after you hit return
      // But this is just an example... a GUI app could implement a proper PTY
      new StreamCopier(System.in, shell.getOutputStream(), LoggerFactory.DEFAULT)
          .bufSize(shell.getRemoteMaxPacketSize())
          .copy();

    } finally {
      session.close();
    }

  } finally {
    client.disconnect();
  }
}
 
Example 12
Source File: SshMachineTest.java    From karamel with Apache License 2.0 4 votes vote down vote up
public void testReadLogfile() throws IOException {
  String privateKey = "-----BEGIN RSA PRIVATE KEY-----\n"
      + "MIIEogIBAAKCAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzI\n"
      + "w+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9HZyN1Q9qgCgzUFtdOKLv6IedplqoP\n"
      + "kcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2\n"
      + "hMNG0zQPyUecp4pzC6kivAIhyfHilFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NO\n"
      + "Td0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcW\n"
      + "yLbIbEgE98OHlnVYCzRdK8jlqm8tehUc9c9WhQIBIwKCAQEA4iqWPJXtzZA68mKd\n"
      + "ELs4jJsdyky+ewdZeNds5tjcnHU5zUYE25K+ffJED9qUWICcLZDc81TGWjHyAqD1\n"
      + "Bw7XpgUwFgeUJwUlzQurAv+/ySnxiwuaGJfhFM1CaQHzfXphgVml+fZUvnJUTvzf\n"
      + "TK2Lg6EdbUE9TarUlBf/xPfuEhMSlIE5keb/Zz3/LUlRg8yDqz5w+QWVJ4utnKnK\n"
      + "iqwZN0mwpwU7YSyJhlT4YV1F3n4YjLswM5wJs2oqm0jssQu/BT0tyEXNDYBLEF4A\n"
      + "sClaWuSJ2kjq7KhrrYXzagqhnSei9ODYFShJu8UWVec3Ihb5ZXlzO6vdNQ1J9Xsf\n"
      + "4m+2ywKBgQD6qFxx/Rv9CNN96l/4rb14HKirC2o/orApiHmHDsURs5rUKDx0f9iP\n"
      + "cXN7S1uePXuJRK/5hsubaOCx3Owd2u9gD6Oq0CsMkE4CUSiJcYrMANtx54cGH7Rk\n"
      + "EjFZxK8xAv1ldELEyxrFqkbE4BKd8QOt414qjvTGyAK+OLD3M2QdCQKBgQDtx8pN\n"
      + "CAxR7yhHbIWT1AH66+XWN8bXq7l3RO/ukeaci98JfkbkxURZhtxV/HHuvUhnPLdX\n"
      + "3TwygPBYZFNo4pzVEhzWoTtnEtrFueKxyc3+LjZpuo+mBlQ6ORtfgkr9gBVphXZG\n"
      + "YEzkCD3lVdl8L4cw9BVpKrJCs1c5taGjDgdInQKBgHm/fVvv96bJxc9x1tffXAcj\n"
      + "3OVdUN0UgXNCSaf/3A/phbeBQe9xS+3mpc4r6qvx+iy69mNBeNZ0xOitIjpjBo2+\n"
      + "dBEjSBwLk5q5tJqHmy/jKMJL4n9ROlx93XS+njxgibTvU6Fp9w+NOFD/HvxB3Tcz\n"
      + "6+jJF85D5BNAG3DBMKBjAoGBAOAxZvgsKN+JuENXsST7F89Tck2iTcQIT8g5rwWC\n"
      + "P9Vt74yboe2kDT531w8+egz7nAmRBKNM751U/95P9t88EDacDI/Z2OwnuFQHCPDF\n"
      + "llYOUI+SpLJ6/vURRbHSnnn8a/XG+nzedGH5JGqEJNQsz+xT2axM0/W/CRknmGaJ\n"
      + "kda/AoGANWrLCz708y7VYgAtW2Uf1DPOIYMdvo6fxIB5i9ZfISgcJ/bbCUkFrhoH\n"
      + "+vq/5CIWxCPp0f85R4qxxQ5ihxJ0YDQT9Jpx4TMss4PSavPaBH3RXow5Ohe+bYoQ\n"
      + "NE5OgEXk2wVfZczCZpigBKbKZHNYcelXtTt/nP3rsCuGcM4h53s=\n"
      + "-----END RSA PRIVATE KEY-----";

  String publicKey = "ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzIw+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9HZyN1Q9qgCgzUFtdOKLv6IedplqoPkcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2hMNG0zQPyUecp4pzC6kivAIhyfHilFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NOTd0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcWyLbIbEgE98OHlnVYCzRdK8jlqm8tehUc9c9WhQ== vagrant insecure public key";
  SSHClient client = new SSHClient();
  client.addHostKeyVerifier(new PromiscuousVerifier());
  KeyProvider keys = client.loadKeys(privateKey, publicKey, null);
  client.connect("192.168.33.10", 22);
  client.authPublickey("vagrant", keys);

  Session session = client.startSession();
  final Session.Command cmd = session.exec("ls");
  cmd.join();
  final byte[] buffer = new byte[65536];
  InputStream is = cmd.getInputStream();
  int r;
  while ((r = is.read(buffer)) > 0) {
    String decoded = new String(buffer, "UTF-8");
    System.out.println(decoded);
  }

}
 
Example 13
Source File: SshJExample.java    From ExpectIt with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws IOException {
    SSHClient ssh = new SSHClient();
    ssh.addHostKeyVerifier(
            new HostKeyVerifier() {
                @Override
                public boolean verify(String s, int i, PublicKey publicKey) {
                    return true;
                }
            });
    ssh.connect("sdf.org");
    ssh.authPassword("new", "");
    Session session = ssh.startSession();
    session.allocateDefaultPTY();
    Shell shell = session.startShell();
    Expect expect = new ExpectBuilder()
            .withOutput(shell.getOutputStream())
            .withInputs(shell.getInputStream(), shell.getErrorStream())
            .withEchoInput(System.out)
            .withEchoOutput(System.err)
            .withInputFilters(removeColors(), removeNonPrintable())
            .withExceptionOnFailure()
            .build();
    try {
        expect.expect(contains("[RETURN]"));
        expect.sendLine();
        String ipAddress = expect.expect(regexp("Trying (.*)\\.\\.\\.")).group(1);
        System.out.println("Captured IP: " + ipAddress);
        expect.expect(contains("login:"));
        expect.sendLine("new");
        expect.expect(contains("(Y/N)"));
        expect.send("N");
        expect.expect(regexp(": $"));
        expect.send("\b");
        expect.expect(regexp("\\(y\\/n\\)"));
        expect.sendLine("y");
        expect.expect(contains("Would you like to sign the guestbook?"));
        expect.send("n");
        expect.expect(contains("[RETURN]"));
        expect.sendLine();
    } finally {
        expect.close();
        session.close();
        ssh.close();
    }
}