當前位置: 首頁>>代碼示例>>Java>>正文


Java JSch.setKnownHosts方法代碼示例

本文整理匯總了Java中com.jcraft.jsch.JSch.setKnownHosts方法的典型用法代碼示例。如果您正苦於以下問題:Java JSch.setKnownHosts方法的具體用法?Java JSch.setKnownHosts怎麽用?Java JSch.setKnownHosts使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在com.jcraft.jsch.JSch的用法示例。


在下文中一共展示了JSch.setKnownHosts方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: build

import com.jcraft.jsch.JSch; //導入方法依賴的package包/類
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;
}
 
開發者ID:cerner,項目名稱:jwala,代碼行數:20,代碼來源:JschBuilder.java

示例2: connect

import com.jcraft.jsch.JSch; //導入方法依賴的package包/類
/**
 * 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;
}
 
開發者ID:pcingola,項目名稱:BigDataScript,代碼行數:25,代碼來源:Ssh.java

示例3: SSHShell

import com.jcraft.jsch.JSch; //導入方法依賴的package包/類
/**
 * 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();
}
 
開發者ID:Azure-Samples,項目名稱:acr-java-manage-azure-container-registry,代碼行數:34,代碼來源:SSHShell.java

示例4: isValidKnownHostsFile

import com.jcraft.jsch.JSch; //導入方法依賴的package包/類
private static boolean isValidKnownHostsFile(String knownHostsFile) {
    JSch test = new JSch();

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

    return true;
}
 
開發者ID:apache,項目名稱:incubator-netbeans,代碼行數:12,代碼來源:Authentication.java

示例5: openSession

import com.jcraft.jsch.JSch; //導入方法依賴的package包/類
protected Session openSession(final ProcessContext context) throws JSchException {
    final JSch jsch = new JSch();
    final String hostKeyVal = context.getProperty(HOST_KEY_FILE).getValue();
    if (hostKeyVal != null) {
        jsch.setKnownHosts(hostKeyVal);
    }

    final Session session = jsch.getSession(context.getProperty(USERNAME).evaluateAttributeExpressions().getValue(),
            context.getProperty(HOSTNAME).evaluateAttributeExpressions().getValue(),
            context.getProperty(PORT).evaluateAttributeExpressions().asInteger().intValue());

    final Properties properties = new Properties();
    properties.setProperty("StrictHostKeyChecking", context.getProperty(STRICT_HOST_KEY_CHECKING).asBoolean() ? "yes" : "no");
    properties.setProperty("PreferredAuthentications", "publickey,password,keyboard-interactive");

    final PropertyValue compressionValue = context.getProperty(USE_COMPRESSION);
    if (compressionValue != null && "true".equalsIgnoreCase(compressionValue.getValue())) {
        properties.setProperty("compression.s2c", "[email protected],zlib,none");
        properties.setProperty("compression.c2s", "[email protected],zlib,none");
    } else {
        properties.setProperty("compression.s2c", "none");
        properties.setProperty("compression.c2s", "none");
    }

    session.setConfig(properties);

    final String privateKeyFile = context.getProperty(PRIVATE_KEY_PATH).evaluateAttributeExpressions().getValue();
    if (privateKeyFile != null) {
        jsch.addIdentity(privateKeyFile, context.getProperty(PRIVATE_KEY_PASSPHRASE).evaluateAttributeExpressions().getValue());
    }

    final String password = context.getProperty(PASSWORD).evaluateAttributeExpressions().getValue();
    if (password != null) {
        session.setPassword(password);
    }

    session.setTimeout(context.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    session.connect();
    return session;
}
 
開發者ID:Asymmetrik,項目名稱:nifi-nars,代碼行數:41,代碼來源:AbstractScpProcessor.java

示例6: connect

import com.jcraft.jsch.JSch; //導入方法依賴的package包/類
public void connect() {
	if (session != null) {
		throw new IllegalStateException("Already Connected");
	}
	try {
		JSch jSch = new JSch();
		if (knownHosts != null) {
			jSch.setKnownHosts(knownHosts);
		}
		if (identity != null) {
			jSch.addIdentity(identity);
		}
		session = jSch.getSession(user, host, 22);
		Properties properties = new Properties();
		properties.setProperty("StrictHostKeyChecking", "no");
		properties.setProperty("PreferredAuthentications", "publickey");
		session.setConfig(properties);
		session.connect();
		channelSftp = (ChannelSftp) session.openChannel("sftp");
		channelSftp.connect();

		LOGGER.info("connect() - Connected to %s", host);
	} catch (Exception ex) {
		// Failed to connect
		session = null;
		LOGGER.error("connect() - Failed to connect to %s - %s ", host, ex.getMessage());
		throw new RuntimeException(ex);
	}
}
 
開發者ID:gchq,項目名稱:stroom-agent,代碼行數:30,代碼來源:SFTPTransfer.java

示例7: knownHosts

import com.jcraft.jsch.JSch; //導入方法依賴的package包/類
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.
    }
}
 
開發者ID:Coding,項目名稱:WebIDE-Backend,代碼行數:19,代碼來源:MultiUserSshSessionFactory.java

示例8: getHostKeyRepository

import com.jcraft.jsch.JSch; //導入方法依賴的package包/類
/**
 * @param knownHostFile
 * @return
 * @throws JSchException
 */
private static HostKeyRepository getHostKeyRepository( String knownHostFile )
    throws JSchException
{
    JSch jsch = new JSch();
    jsch.setKnownHosts( knownHostFile );
    return jsch.getHostKeyRepository();
}
 
開發者ID:vmware,項目名稱:OHMS,代碼行數:13,代碼來源:SshUtil.java

示例9: build

import com.jcraft.jsch.JSch; //導入方法依賴的package包/類
public JSch build() throws SshException, JSchException {
    JSch jsch = new JSch();
    if (knownHosts != null) {
        jsch.setKnownHosts(knownHosts);
    }
    if (authentication == null) {
        throw new SshException("Error: authentication not set");
    }
    authentication.prepare(jsch);
    return jsch;
}
 
開發者ID:kemitix,項目名稱:kxssh,代碼行數:12,代碼來源:JSchFactory.java

示例10: connectAndGetSftpChannel

import com.jcraft.jsch.JSch; //導入方法依賴的package包/類
public ChannelSftp connectAndGetSftpChannel() throws JSchException {
    JSch jsch = new JSch();
    jsch.setKnownHosts(context.getFilesDir().getAbsolutePath() + File.separator + "jsch_known_hosts");

    String username = prefs.sshUserName().getOr(null);
    String host = prefs.sshServerAddress().getOr(null);
    String port = prefs.sshServerPort().getOr(null);
    if (username == null || host == null || port == null)
        throw new IllegalStateException("Please enter your server settings first");

    Session session = jsch.getSession(username, host, Integer.parseInt(port));

    UserInfo info = storedOrAskedUserInfo;
    session.setUserInfo(info);
    try {
        session.connect(5000);
        storedOrAskedUserInfo.confirmPasswordRight();
    }
    catch (JSchException je) {
        if ("auth fail".equals(je.getMessage().toLowerCase())) { // undocumented!
            storedOrAskedUserInfo.clearPassword();
        }
        throw je;
    }

    ChannelSftp channel = (ChannelSftp)session.openChannel("sftp");
    channel.connect(5000);
    return channel;
}
 
開發者ID:egueli,項目名稱:ETStreamHome,代碼行數:30,代碼來源:SftpManager.java

示例11: connect

import com.jcraft.jsch.JSch; //導入方法依賴的package包/類
@Override
public void connect(String host) throws IOException {
    if (session == null) {
        try {
            JSch sshClient = new JSch();
            if (privateKey != null) {
                sshClient.addIdentity(privateKey.toString());
            }
            if (knownHosts != null) {
                sshClient.setKnownHosts(knownHosts.toString());
            } else {
                sshClient.setKnownHosts("~/.ssh/known_hosts");
            }
            
            session = sshClient.getSession(user, host);
            if (password != null) {
                session.setPassword(password);
            } else if (privateKey == null){
                throw new IOException("Either privateKey nor password is set. Please call one of the authentication method.");
            }
            session.connect();
        } catch (JSchException ex) {
            throw new IOException(ex);
        }
    }

}
 
開發者ID:sparsick,項目名稱:comparison-java-ssh-libs,代碼行數:28,代碼來源:JSchClient.java

示例12: createSession

import com.jcraft.jsch.JSch; //導入方法依賴的package包/類
protected Session createSession() throws JSchException {
    final JSch jsch = new JSch();
    final Session session = jsch.getSession( username, host, port );

    if ( this.knownHostsInputStream != null ) {
        jsch.setKnownHosts( this.knownHostsInputStream );
    }

    if ( this.strictHostkeyChecking == StrictHostkeyChecking.OFF ) {
        LOG.warn( "Session created with StrictHostKeyChecking disabled." );
        // If this property is set to ``yes'', jsch will never automatically add
        // host keys to the $HOME/.ssh/known_hosts file, and refuses to connect
        // to hosts whose host key has changed.  This property forces the user
        // to manually add all new hosts.  If this property is set to ``no'',
        // jsch will automatically add new host keys to the user known hosts files.
        session.setConfig( "StrictHostKeyChecking", "no" );
    }
    session.setPassword( password );

    // socket timeout in milliseconds
    session.setTimeout( socketTimeoutMs );

    return session;
}
 
開發者ID:freiheit-com,項目名稱:fuava_simplebatch,代碼行數:25,代碼來源:SftpClient.java

示例13: getServerHostKey

import com.jcraft.jsch.JSch; //導入方法依賴的package包/類
@Override
public String getServerHostKey(String host, int port, Algorithm algorithm) throws Throwable {
    JSch jsch = new JSch();

    // set the algorithm/key type
    JSch.setConfig("server_host_key", algorithm.signature());

    // in-memory buffer & stream to store the remote host key.
    byte[] knownHosts = new byte[8192];
    ByteArrayInputStream in = new ByteArrayInputStream(knownHosts);

    // set the in-memory stream as key repository
    jsch.setKnownHosts(in);

    // create a session where user name is nobody, it can be anything except null. Because it will fail to
    // authenticate anyway. The remote host key will be added to repository before the authentication.

    com.jcraft.jsch.Session session = jsch.getSession("nobody", host, port);
    // accept unknown key
    session.setConfig("StrictHostKeyChecking", "no");

    try {
        // connect to remote host. It will do host key exchange first then authentication.
        session.connect();
    } catch (JSchException e) {
        // authentication fails but it is ok.
    } finally {
        if (session.isConnected()) {
            // by any chance it is connected, disconnect it.
            session.disconnect();
        }
    }
    return session.getHostKey().getKey();
}
 
開發者ID:uom-daris,項目名稱:daris,代碼行數:35,代碼來源:JSchSsh.java

示例14: JschConnection

import com.jcraft.jsch.JSch; //導入方法依賴的package包/類
public JschConnection(ConnectionDetails cxnDetails, int maxChannels, boolean verbose) throws Throwable {
    _cxnDetails = cxnDetails;
    _maxChannels = maxChannels;
    _verbose = verbose;

    _channels = Collections.synchronizedCollection(new HashSet<com.jcraft.jsch.Channel>());

    _jsch = new JSch();
    _jsch.setKnownHosts(new ByteArrayInputStream(new byte[8192]));
    String hostKey = _cxnDetails.hostKey();
    if (hostKey != null) {
        _jsch.getHostKeyRepository()
                .add(new HostKey(_cxnDetails.host(), Base64.getDecoder().decode(hostKey.getBytes())), userInfo());
    }
    /*
     * added user's identity (private & public keys)
     */
    if (_cxnDetails.privateKey() != null) {
        _jsch.addIdentity(_cxnDetails.username() + "_identity", _cxnDetails.privateKey().getBytes(),
                _cxnDetails.publicKey() != null ? _cxnDetails.publicKey().getBytes() : null,
                _cxnDetails.passphrase() != null ? _cxnDetails.passphrase().getBytes() : null);
    }

    /*
     * connect
     */
    _jschSession = _jsch.getSession(_cxnDetails.username(), _cxnDetails.host(), _cxnDetails.port());
    _jschSession.setConfig("StrictHostKeyChecking", _cxnDetails.hostKey() != null ? "yes" : "no");
    _jschSession.setUserInfo(userInfo());
    if (_verbose) {
        System.out.print("opening connection to " + _cxnDetails.host() + ":" + _cxnDetails.port() + " ...");
    }
    _jschSession.connect();
    if (_verbose) {
        System.out.println("done");
    }
}
 
開發者ID:uom-daris,項目名稱:daris,代碼行數:38,代碼來源:JschConnection.java

示例15: getServerHostKey

import com.jcraft.jsch.JSch; //導入方法依賴的package包/類
@Override
public String getServerHostKey(String host, int port, KeyType type) throws Throwable {

    JSch jsch = new JSch();

    // set the algorithm/key type
    JSch.setConfig("server_host_key", type.publicKeyTypeName());

    // in-memory buffer & stream to store the remote host key.
    byte[] knownHosts = new byte[8192];
    ByteArrayInputStream in = new ByteArrayInputStream(knownHosts);

    // set the in-memory stream as key repository
    jsch.setKnownHosts(in);

    // create a session where user name is nobody, it can be anything except
    // null. Because it will fail to authenticate anyway. The remote host
    // key will be added to repository before the authentication.

    com.jcraft.jsch.Session session = jsch.getSession("nobody", host, port);
    // accept unknown key
    session.setConfig("StrictHostKeyChecking", "no");

    try {
        // connect to remote host. It will do host key exchange first then
        // authentication.
        session.connect();
    } catch (JSchException e) {
        // authentication fails but it is ok.
    } finally {
        if (session.isConnected()) {
            // by any chance it is connected, disconnect it.
            session.disconnect();
        }
    }
    return session.getHostKey().getKey();
}
 
開發者ID:uom-daris,項目名稱:daris,代碼行數:38,代碼來源:JschKeyTools.java


注:本文中的com.jcraft.jsch.JSch.setKnownHosts方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。