当前位置: 首页>>代码示例>>Java>>正文


Java SSHClient.addHostKeyVerifier方法代码示例

本文整理汇总了Java中net.schmizz.sshj.SSHClient.addHostKeyVerifier方法的典型用法代码示例。如果您正苦于以下问题:Java SSHClient.addHostKeyVerifier方法的具体用法?Java SSHClient.addHostKeyVerifier怎么用?Java SSHClient.addHostKeyVerifier使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在net.schmizz.sshj.SSHClient的用法示例。


在下文中一共展示了SSHClient.addHostKeyVerifier方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: uploadFile

import net.schmizz.sshj.SSHClient; //导入方法依赖的package包/类
@Test
public void uploadFile() throws IOException, NoSuchProviderException, NoSuchAlgorithmException {
  final SSHClient ssh = new SSHClient();
  ssh.addHostKeyVerifier(SecurityUtils.getFingerprint(subject.getHostsPublicKey()));

  ssh.connect("localhost", subject.getPort());
  try {
    ssh.authPublickey("this_is_ignored", new KeyPairWrapper(
        KeyPairGenerator.getInstance("DSA", "SUN").generateKeyPair()));

    final SFTPClient sftp = ssh.newSFTPClient();
    File testFile = local.newFile("fred.txt");
    try {
      sftp.put(new FileSystemFile(testFile), "/fred.txt");
    } finally {
      sftp.close();
    }
  } finally {
    ssh.disconnect();
  }

  assertThat(sftpHome.getRoot().list(), is(new String[]{"fred.txt"}));
}
 
开发者ID:mlk,项目名称:AssortmentOfJUnitRules,代码行数:24,代码来源:TestSftpRule.java

示例2: connectfromPItoServer

import net.schmizz.sshj.SSHClient; //导入方法依赖的package包/类
public static void connectfromPItoServer(int fotosAnzahl, int belichtungsDauer)
            throws IOException {
    	final String ipServer = Inet4Address.getLocalHost().getHostAddress();
//    	System.out.println(Inet4Address.getAllByName("raspberrypi"));
//    	System.out.println(fotosAnzahl);
        final SSHClient ssh = new SSHClient();
        ssh.addHostKeyVerifier(new NullHostKeyVerifier());
//        for(int i = 0; i < InetAddress.)
//        ssh.connect("192.168.2.100", 22);
        ssh.connect(Settings.raspberryIP, 22);
       
        try {
         ssh.authPassword("pi", "raspberry");
            final Session session = ssh.startSession();
            try {
            	System.out.println("BEGINNE MIt tray");
                final Command cmd = session.exec("java -jar Desktop/Driver/Java/client.jar " + fotosAnzahl + " " + ipServer + " " + belichtungsDauer);
                System.out.println(IOUtils.readFully(cmd.getInputStream()).toString());
                cmd.join(5, TimeUnit.SECONDS);
                System.out.println("\n** exit status: " + cmd.getExitStatus());
            } finally {
                session.close();
            }
        } finally {
            ssh.disconnect();
            ssh.close();
        }
    }
 
开发者ID:Raldir,项目名称:3DScanner.RaspberryPi,代码行数:29,代码来源:Exec.java

示例3: build

import net.schmizz.sshj.SSHClient; //导入方法依赖的package包/类
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;
}
 
开发者ID:zstackio,项目名称:zstack,代码行数:24,代码来源:Ssh.java

示例4: SshConnection

import net.schmizz.sshj.SSHClient; //导入方法依赖的package包/类
/**
 * Connects to a ssh server
 *
 * <p>
 * Do not call this constructor directly, use {@link SshConnector} instead for IoC
 *
 * @param config the ssh configuration
 * @param client an instance of {@link SSHClient} to use
 * @throws IOException failed to connect to the server
 */
public SshConnection(SshConfig config, SSHClient client) throws IOException {
	// TODO see if the SSHClient can be injected differently
	this.client = client;
	this.config = config;
	if (!config.getVerifyHostKey()) {
		client.addHostKeyVerifier(new PromiscuousVerifier());
	}
	client.connect(config.getHost(), config.getPort());
	if (config.getPassword() != null) {
		client.authPassword(config.getUser(), config.getPassword());
	} else if (config.getKeyFile() != null) {
		client.authPublickey(config.getUser(), config.getKeyFile().toString());
	} else {
		client.authPassword(config.getUser(), "");
	}
}
 
开发者ID:bugminer,项目名称:bugminer,代码行数:27,代码来源:SshConnection.java

示例5: downloadFile

import net.schmizz.sshj.SSHClient; //导入方法依赖的package包/类
@Test
public void downloadFile() throws IOException, NoSuchProviderException, NoSuchAlgorithmException {
  FileUtils.write(sftpHome.newFile("fred.txt"), "Electric boogaloo");

  final SSHClient ssh = new SSHClient();
  ssh.addHostKeyVerifier(SecurityUtils.getFingerprint(subject.getHostsPublicKey()));

  ssh.connect("localhost", subject.getPort());
  try {
    ssh.authPublickey("this_is_ignored", new KeyPairWrapper(
        KeyPairGenerator.getInstance("DSA", "SUN").generateKeyPair()));

    final SFTPClient sftp = ssh.newSFTPClient();

    try {
      sftp.get("fred.txt", new FileSystemFile(new File(local.getRoot(), "fred.txt")));
    } finally {
      sftp.close();
    }
  } finally {
    ssh.disconnect();
  }

  assertThat(FileUtils.readFileToString(new File(local.getRoot(), "fred.txt")),
      is("Electric boogaloo"));
}
 
开发者ID:mlk,项目名称:AssortmentOfJUnitRules,代码行数:27,代码来源:TestSftpRule.java

示例6: doInBackground

import net.schmizz.sshj.SSHClient; //导入方法依赖的package包/类
@Override
protected Boolean doInBackground(String... cmd) {
	String ssh_command = cmd[0];
	SSHClient ssh = new SSHClient();
	HostKeyVerifier always_verify = new HostKeyVerifier() {
				public boolean verify(String arg0, int arg1, PublicKey arg2) {
					return true;
				}  
	}; 
	ssh.addHostKeyVerifier(always_verify);  
	Boolean success = false;
	try {
		ssh.connect(this.ssh_server);
		ssh.authPassword(this.ssh_user, this.ssh_password);
		Session session = ssh.startSession();
		Command command = session.exec(ssh_command);
		command.join();
		Integer exit_status = command.getExitStatus(); 
		if (exit_status == this.expected_exit_status) {
			success = true;
		}
		session.close();
		ssh.close();
	} catch (IOException e) { }
	return success;
}
 
开发者ID:hkparker,项目名称:ComputerManager,代码行数:27,代码来源:BackgroundSSHExec.java

示例7: prepareSshConnection

import net.schmizz.sshj.SSHClient; //导入方法依赖的package包/类
private void prepareSshConnection(SSHClient ssh, String ip, int port, HostKeyVerifier hostKeyVerifier, String user,
        String privateKeyString, Stack stack) throws CloudbreakException, IOException {
    ssh.addHostKeyVerifier(hostKeyVerifier);
    ssh.connect(ip, port);
    if (stack.getStackAuthentication().passwordAuthenticationRequired()) {
        ssh.authPassword(user, stack.getStackAuthentication().getLoginPassword());
    } else {
        try {
            KeyPair keyPair = KeyStoreUtil.createKeyPair(privateKeyString);
            KeyPairWrapper keyPairWrapper = new KeyPairWrapper(keyPair);
            ssh.authPublickey(user, keyPairWrapper);
        } catch (Exception e) {
            throw new CloudbreakException("Couldn't prepare SSH connection", e);
        }
    }
}
 
开发者ID:hortonworks,项目名称:cloudbreak,代码行数:17,代码来源:TlsSetupService.java

示例8: loadKnownHostsInteractive

import net.schmizz.sshj.SSHClient; //导入方法依赖的package包/类
private void loadKnownHostsInteractive(SSHClient ssh) throws IOException {
    boolean loaded = false;
    final File sshDir = OpenSSHKnownHosts.detectSSHDir();
    if (sshDir != null) {
        for (File loc : Arrays.asList(new File(sshDir, "known_hosts"), new File(sshDir, "known_hosts2"))) {
            try {
                ssh.addHostKeyVerifier(new OpenSSHKnownHostsInteractive(loc));
                loaded = true;
            } catch (IOException ex) {
                // Ignore for now
            }
        }
    }
    if (!loaded) {
        throw new IOException("Could not load known_hosts");
    }
}
 
开发者ID:Alidron,项目名称:designer,代码行数:18,代码来源:SSHProviderImpl.java

示例9: getTempLocalInstance

import net.schmizz.sshj.SSHClient; //导入方法依赖的package包/类
public File getTempLocalInstance( String remoteFilePath )
{
  File tempFile = null;
  SSHClient client = new SSHClient();
  // required if host is not in knownLocalHosts
  client.addHostKeyVerifier(new PromiscuousVerifier());

  try {
    client.connect(hostName);
    client.authPassword(userName, userPass);

    tempFile = File.createTempFile("tmp", null, null);
    tempFile.deleteOnExit();

    SFTPClient sftp = client.newSFTPClient();
    sftp.get(remoteFilePath, new FileSystemFile(tempFile));
    sftp.close();
    client.disconnect();

  } catch( Exception e ) { 
    //TODO: this needs to be more robust than just catching all exceptions
    e.printStackTrace();
    logger.error( e.toString() );
    return null;
  } 
  
  return tempFile;
}
 
开发者ID:prateek,项目名称:ssh-spool-source,代码行数:29,代码来源:SshClientJ.java

示例10: newClient

import net.schmizz.sshj.SSHClient; //导入方法依赖的package包/类
/**
 * 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;
}
 
开发者ID:apache,项目名称:incubator-provisionr,代码行数:25,代码来源:Ssh.java

示例11: onPreExecute

import net.schmizz.sshj.SSHClient; //导入方法依赖的package包/类
@Override
protected void onPreExecute() {
	super.onPreExecute();
	Toast.makeText(activity, getString(R.string.command_executor_execute),
			Toast.LENGTH_LONG).show();
	
	myTerminal.show();
	
	ssh = new SSHClient(new AndroidConfig());
	ssh.addHostKeyVerifier(new HostKeyVerifier() {
		@Override
		public boolean verify(String arg0, int arg1, PublicKey arg2) {
			return true;
		}
	});
}
 
开发者ID:joakim-ribier,项目名称:JOneTouch,代码行数:17,代码来源:CommandExecutor.java

示例12: connect

import net.schmizz.sshj.SSHClient; //导入方法依赖的package包/类
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) {
            try {
                return key.verify(hostname, port, 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;
        }
    });
    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;
}
 
开发者ID:iterate-ch,项目名称:cyberduck,代码行数:33,代码来源:SFTPSession.java

示例13: getConnectedClient

import net.schmizz.sshj.SSHClient; //导入方法依赖的package包/类
private SSHClient getConnectedClient() throws Exception {
	if (password == null && key == null)
		throw new Exception("You need to provide one among the key and the password to be used.");

	DefaultConfig defaultConfig = new DefaultConfig();
	defaultConfig.setKeepAliveProvider(KeepAliveProvider.KEEP_ALIVE);

	final SSHClient ssh = new SSHClient(defaultConfig);

	ssh.addHostKeyVerifier(new PromiscuousVerifier());

	ssh.connect(ip, SSH_PORT);

	if (key != null) {
		if (!key.endsWith(".pem"))
			key = key.concat(".pem");
		Path p = Configuration.getPathToFile(key);
		if (p != null)
			ssh.authPublickey(user, p.toString());
	} else {
		ssh.authPassword(user, password);
	}

	ssh.getConnection().getKeepAlive().setKeepAliveInterval(5);

	return ssh;
}
 
开发者ID:rickdesantis,项目名称:cloud-runner,代码行数:28,代码来源:Sshj.java

示例14: getSshClient

import net.schmizz.sshj.SSHClient; //导入方法依赖的package包/类
private static SSHClient getSshClient(HostInfo hostInfo) throws IOException {
    long sleepTimeMs = INITIAL_SLEEP_TIME_MS;

    for (int attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
        try {
            SSHClient ssh = new SSHClient(DEFAULT_CONFIG);
            ssh.addHostKeyVerifier(new PromiscuousVerifier());
            ssh.connect(hostInfo.host);
            ssh.authPublickey(hostInfo.user, hostInfo.privateKeyPath);
            ssh.useCompression();
            return ssh;
        } catch (IOException exception) {
            System.out.format("Failed to login to host %s as user %s. Exception: %s.%n", hostInfo.host, hostInfo.user, exception.getMessage());
            System.out.format("Attempt %d of %d. Sleeping for %d ms.%n", attempt, MAX_ATTEMPTS, sleepTimeMs);

            boolean lastAttempt = attempt == MAX_ATTEMPTS;

            if (lastAttempt) {
                throw exception;
            }

            try {
                Thread.sleep(sleepTimeMs);
            } catch (InterruptedException e) {
            }
            sleepTimeMs *= BACKOFF_FACTOR;
        }
    }

    throw new RuntimeException(String.format("Unable to login to host %s as user %s after %d attempts.", hostInfo.host, hostInfo.user, MAX_ATTEMPTS));
}
 
开发者ID:electronicarts,项目名称:gatling-aws-maven-plugin,代码行数:32,代码来源:SshClient.java

示例15: main

import net.schmizz.sshj.SSHClient; //导入方法依赖的package包/类
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)
          .bufSize(shell.getLocalMaxPacketSize())
          .spawn("stdout");

      new StreamCopier(shell.getErrorStream(), System.err)
          .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())
          .bufSize(shell.getRemoteMaxPacketSize())
          .copy();

    } finally {
      session.close();
    }

  } finally {
    client.disconnect();
  }
}
 
开发者ID:karamelchef,项目名称:karamel,代码行数:69,代码来源:RudimentaryPTY.java


注:本文中的net.schmizz.sshj.SSHClient.addHostKeyVerifier方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。