Java Code Examples for com.jcraft.jsch.JSch#setKnownHosts()

The following examples show how to use com.jcraft.jsch.JSch#setKnownHosts() . 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: SSHManager.java    From pacbot with Apache License 2.0 6 votes vote down vote up
private static void doCommonConstructorActions(String userName,
        String password, String connectionIP, String knownHostsFileName) {
    jschSSHChannel = new JSch();

    try {
        jschSSHChannel.setKnownHosts(knownHostsFileName);
    } catch (JSchException jschX) {
        LOGGER.error(jschX.getMessage());
        errorMessage = jschX.getMessage();
    }

    strUserName = userName;
    strPassword = password;
    strConnectionIP = connectionIP;
}
 
Example 2
Source File: LazyKnownHosts.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
LazyKnownHosts(JSch jsch, String knownHosts) throws JSchException {
	if (knownHosts != null) {
		try {
			final InputStream in = new ByteArrayInputStream(knownHosts.getBytes("UTF8"));
			try {
				jsch.setKnownHosts(in);
			} finally {
				in.close();
			}
		} catch (IOException e) {
			// no known hosts
		}
	}
	this.repo = jsch.getHostKeyRepository();

}
 
Example 3
Source File: SSHShell.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Creates SSHShell.
 *
 * @param host the host name
 * @param port the ssh port
 * @param userName the ssh user name
 * @param sshPrivateKey the ssh password
 * @return the shell
 * @throws JSchException
 * @throws IOException
 */
private SSHShell(String host, int port, String userName, byte[] sshPrivateKey)
    throws JSchException, IOException {
    Closure expectClosure = getExpectClosure();
    for (String linuxPromptPattern : new String[]{"\\>", "#", "~#", "~\\$"}) {
        try {
            Match match = new RegExpMatch(linuxPromptPattern, expectClosure);
            linuxPromptMatches.add(match);
        } catch (MalformedPatternException malformedEx) {
            throw new RuntimeException(malformedEx);
        }
    }
    JSch jsch = new JSch();
    jsch.setKnownHosts(System.getProperty("user.home") + "/.ssh/known_hosts");
    jsch.addIdentity(host, sshPrivateKey, (byte[]) null, (byte[]) null);
    this.session = jsch.getSession(userName, host, port);
    this.session.setConfig("StrictHostKeyChecking", "no");
    this.session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
    session.connect(60000);
    this.channel = (ChannelShell) session.openChannel("shell");
    this.expect = new Expect4j(channel.getInputStream(), channel.getOutputStream());
    channel.connect();
}
 
Example 4
Source File: JschBuilder.java    From jwala with Apache License 2.0 6 votes vote down vote up
public JSch build() throws JSchException {
    LOGGER.debug("Initializing JSch Logger");
    JSch.setLogger(new JschLogger());
    final JSch jsch = new JSch();
    try {
        if (null != knownHostsFileName && new File(knownHostsFileName).exists()) {
            jsch.setKnownHosts(knownHostsFileName);
        }
        if (null != privateKeyFileName && new File(privateKeyFileName).exists()) {
            jsch.addIdentity(privateKeyFileName);
        }
    } catch (JSchException e) {
        LOGGER.error("Could not access known hosts or private key file.", e);
        if (!(e.getCause() instanceof FileNotFoundException)) {
            throw new JSchException();
        }
    }
    return jsch;
}
 
Example 5
Source File: MultiUserSshSessionFactory.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static void knownHosts(final JSch sch, FS fs) throws JSchException {
    final File home = fs.userHome();
    if (home == null)
        return;
    final File known_hosts = new File(new File(home, ".ssh"), "known_hosts"); //$NON-NLS-1$ //$NON-NLS-2$
    try {
        final FileInputStream in = new FileInputStream(known_hosts);
        try {
            sch.setKnownHosts(in);
        } finally {
            in.close();
        }
    } catch (FileNotFoundException none) {
        // Oh well. They don't have a known hosts in home.
    } catch (IOException err) {
        // Oh well. They don't have a known hosts in home.
    }
}
 
Example 6
Source File: SFtpUtil.java    From Aria with Apache License 2.0 6 votes vote down vote up
private void setKnowHost(JSch jSch, FtpUrlEntity entity) throws JSchException {
  IdEntity idEntity = entity.idEntity;
  if (idEntity.knowHost != null) {
    File knowFile = new File(idEntity.knowHost);
    if (!knowFile.exists()) {
      FileUtil.createFile(knowFile);
    }
    jSch.setKnownHosts(idEntity.knowHost);

    //HostKeyRepository hkr = jSch.getHostKeyRepository();
    //hkr.add(new HostKey(entity.hostName, HostKey.SSHRSA, getPubKey(idEntity.pubKey)), new JschUserInfo());
    //
    //HostKey[] hks = hkr.getHostKey();
    //if (hks != null) {
    //  System.out.println("Host keys in " + hkr.getKnownHostsRepositoryID());
    //  for (int i = 0; i < hks.length; i++) {
    //    HostKey hk = hks[i];
    //    System.out.println(hk.getHost() + " " +
    //        hk.getType() + " " +
    //        hk.getFingerPrint(jSch));
    //  }
    //}
  }
}
 
Example 7
Source File: Ssh.java    From BigDataScript with Apache License 2.0 6 votes vote down vote up
/**
 * Connect to a remote host and return a channel (session and jsch are set)
 */
Channel connect(String channleType, String sshCommand) throws Exception {
	JSch.setConfig("StrictHostKeyChecking", "no"); // Not recommended, but useful
	jsch = new JSch();

	// Some "reasonable" defaults
	if (Gpr.exists(defaultKnownHosts)) jsch.setKnownHosts(defaultKnownHosts);
	for (String identity : defaultKnownIdentity)
		if (Gpr.exists(identity)) jsch.addIdentity(identity);

	// Create session and connect
	if (debug) Gpr.debug("Create conection:\n\tuser: '" + host.getUserName() + "'\n\thost : '" + host.getHostName() + "'\n\tport : " + host.getPort());
	session = jsch.getSession(host.getUserName(), host.getHostName(), host.getPort());
	session.setUserInfo(new SshUserInfo());
	session.connect();

	// Create channel
	channel = session.openChannel(channleType);
	if ((sshCommand != null) && (channel instanceof ChannelExec)) ((ChannelExec) channel).setCommand(sshCommand);

	return channel;
}
 
Example 8
Source File: SFTPUtils.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
public static Session createSession(final SFTPConfiguration conf, final JSch jsch) throws JSchException, IOException {
    if (conf == null || null == jsch) {
        throw new NullPointerException();
    }

    final Hashtable<String, String> newOptions = new Hashtable<>();

    Session session = jsch.getSession(conf.username, conf.hostname, conf.port);

    final String hostKeyVal = conf.hostkeyFile;

    if (null != hostKeyVal) {
        try {
            jsch.setKnownHosts(hostKeyVal);
        } catch (final IndexOutOfBoundsException iob) {
            throw new IOException("Unable to establish connection due to bad known hosts key file " + hostKeyVal, iob);
        }
    } else {
        newOptions.put("StrictHostKeyChecking", "no");
        session.setConfig(newOptions);
    }

    final String privateKeyVal = conf.privatekeyFile;
    if (null != privateKeyVal) {
        jsch.addIdentity(privateKeyVal, conf.privateKeypassphrase);
    }

    if (null != conf.password) {
        session.setPassword(conf.password);
    }

    session.setTimeout(conf.connectionTimeout); //set timeout for connection
    session.connect();
    session.setTimeout(conf.dataTimeout); //set timeout for data transfer

    return session;
}
 
Example 9
Source File: Authentication.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isValidKnownHostsFile(String knownHostsFile) {
    JSch test = new JSch();

    try {
        test.setKnownHosts(knownHostsFile);
    } catch (JSchException ex) {
        return false;
    }

    return true;
}
 
Example 10
Source File: GitMonitoringService.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
private SshSessionFactory getSshSessionFactory() {
  JschConfigSessionFactory sessionFactory = new JschConfigSessionFactory() {
    @Override
    protected void configure(OpenSshConfig.Host hc, Session session) {
      if (!GitMonitoringService.this.strictHostKeyCheckingEnabled) {
        session.setConfig("StrictHostKeyChecking", "no");
      }
    }

    @Override
    protected JSch createDefaultJSch(FS fs) throws JSchException {
      if (GitMonitoringService.this.isJschLoggerEnabled) {
        JSch.setLogger(new JschLogger());
      }
      JSch defaultJSch = super.createDefaultJSch(fs);
      defaultJSch.getIdentityRepository().removeAll();
      if (GitMonitoringService.this.privateKeyPath != null) {
        defaultJSch.addIdentity(GitMonitoringService.this.privateKeyPath, GitMonitoringService.this.passphrase);
      } else {
        defaultJSch.addIdentity("gaas-git", GitMonitoringService.this.privateKey, null,
            GitMonitoringService.this.passphrase.getBytes(Charset.forName("UTF-8")));
      }
      if (!Strings.isNullOrEmpty(GitMonitoringService.this.knownHosts)) {
        defaultJSch.setKnownHosts(new ByteArrayInputStream(GitMonitoringService.this.knownHosts.getBytes(Charset.forName("UTF-8"))));
      } else if (!Strings.isNullOrEmpty(GitMonitoringService.this.knownHostsFile)) {
        defaultJSch.setKnownHosts(GitMonitoringService.this.knownHostsFile);
      }
      return defaultJSch;
    }
  };
  return sessionFactory;
}
 
Example 11
Source File: SftpFileTransferLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
private ChannelSftp setupJsch() throws JSchException {
    JSch jsch = new JSch();
    jsch.setKnownHosts(knownHostsFileLoc);
    Session jschSession = jsch.getSession(username, remoteHost);
    jschSession.setPassword(password);
    //jschSession.setConfig("StrictHostKeyChecking", "no");
    jschSession.connect();
    return (ChannelSftp) jschSession.openChannel("sftp");
}
 
Example 12
Source File: SftpFsHelper.java    From incubator-gobblin with Apache License 2.0 4 votes vote down vote up
/**
 * Opens up a connection to specified host using the username. Connects to the source using a private key without
 * prompting for a password. This method does not support connecting to a source using a password, only by private
 * key
 * @throws org.apache.gobblin.source.extractor.filebased.FileBasedHelperException
 */
@Override
public void connect() throws FileBasedHelperException {

  String privateKey = PasswordManager.getInstance(this.state)
      .readPassword(this.state.getProp(ConfigurationKeys.SOURCE_CONN_PRIVATE_KEY));
  String password = PasswordManager.getInstance(this.state)
      .readPassword(this.state.getProp(ConfigurationKeys.SOURCE_CONN_PASSWORD));
  String knownHosts = this.state.getProp(ConfigurationKeys.SOURCE_CONN_KNOWN_HOSTS);

  String userName = this.state.getProp(ConfigurationKeys.SOURCE_CONN_USERNAME);
  String hostName = this.state.getProp(ConfigurationKeys.SOURCE_CONN_HOST_NAME);
  int port = this.state.getPropAsInt(ConfigurationKeys.SOURCE_CONN_PORT, ConfigurationKeys.SOURCE_CONN_DEFAULT_PORT);

  String proxyHost = this.state.getProp(ConfigurationKeys.SOURCE_CONN_USE_PROXY_URL);
  int proxyPort = this.state.getPropAsInt(ConfigurationKeys.SOURCE_CONN_USE_PROXY_PORT, -1);

  JSch.setLogger(new JSchLogger());
  JSch jsch = new JSch();

  log.info("Attempting to connect to source via SFTP with" + " privateKey: " + privateKey + " knownHosts: "
      + knownHosts + " userName: " + userName + " hostName: " + hostName + " port: " + port + " proxyHost: "
      + proxyHost + " proxyPort: " + proxyPort);

  try {

    if (!Strings.isNullOrEmpty(privateKey)) {
      List<IdentityStrategy> identityStrategies = ImmutableList.of(new LocalFileIdentityStrategy(),
          new DistributedCacheIdentityStrategy(), new HDFSIdentityStrategy());

      for (IdentityStrategy identityStrategy : identityStrategies) {
        if (identityStrategy.setIdentity(privateKey, jsch)) {
          break;
        }
      }
    }

    this.session = jsch.getSession(userName, hostName, port);
    this.session.setConfig("PreferredAuthentications", "publickey,password");

    if (Strings.isNullOrEmpty(knownHosts)) {
      log.info("Known hosts path is not set, StrictHostKeyChecking will be turned off");
      this.session.setConfig("StrictHostKeyChecking", "no");
    } else {
      jsch.setKnownHosts(knownHosts);
    }

    if (!Strings.isNullOrEmpty(password)) {
      this.session.setPassword(password);
    }

    if (proxyHost != null && proxyPort >= 0) {
      this.session.setProxy(new ProxyHTTP(proxyHost, proxyPort));
    }

    UserInfo ui = new MyUserInfo();
    this.session.setUserInfo(ui);
    this.session.setDaemonThread(true);
    this.session.connect();

    log.info("Finished connecting to source");
  } catch (JSchException e) {
    if (this.session != null) {
      this.session.disconnect();
    }
    log.error(e.getMessage(), e);
    throw new FileBasedHelperException("Cannot connect to SFTP source", e);
  }
}