Java 类com.jcraft.jsch.JSch 实例源码

项目:LesPatternsDuSwag    文件:SFTPUploader.java   
private void upload(String filename) {
    try {
        JSch jsch = new JSch();
        Session session = jsch.getSession(login, server, port);
        session.setPassword(password);

        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();

        Channel channel = session.openChannel("sftp");
        channel.connect();
        ChannelSftp channelSftp = (ChannelSftp) channel;
        channelSftp.cd(workingDirectory);
        File f = new File(filename);

        channelSftp.put(new FileInputStream(f), f.getName());

        f.delete();

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
项目:wherehowsX    文件:SshUtils.java   
public static void fileFetch(String host, String user, String keyLocation, String sourceDir, String destDir) {
    JSch jsch = new JSch();
    Session session = null;
    try {
        // set up session
        session = jsch.getSession(user,host);
        // use private key instead of username/password
        session.setConfig(
                "PreferredAuthentications",
                "publickey,gssapi-with-mic,keyboard-interactive,password");
        jsch.addIdentity(keyLocation);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();

        // copy remote log file to localhost.
        ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
        channelSftp.connect();
        channelSftp.get(sourceDir, destDir);
        channelSftp.exit();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        session.disconnect();
    }
}
项目:jwala    文件:JschBuilder.java   
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;
}
项目:KitchenSink    文件:App.java   
/**
 * Lists directory files on remote server.
 * @throws URISyntaxException 
 * @throws JSchException 
 * @throws SftpException 
 */
private void listFiles() throws URISyntaxException, JSchException, SftpException {

    JSch jsch = new JSch();
    JSch.setLogger(new JschLogger());
    setupSftpIdentity(jsch);

    URI uri = new URI(sftpUrl);
    Session session = jsch.getSession(sshLogin, uri.getHost(), 22);
    session.setConfig("StrictHostKeyChecking", "no");
    session.connect();
    System.out.println("Connected to SFTP server");

    Channel channel = session.openChannel("sftp");
    channel.connect();
    ChannelSftp sftpChannel = (ChannelSftp) channel;
    Vector<LsEntry> directoryEntries = sftpChannel.ls(uri.getPath());
    for (LsEntry file : directoryEntries) {
        System.out.println(String.format("File - %s", file.getFilename()));
    }
    sftpChannel.exit();
    session.disconnect();
}
项目:iBase4J-Common    文件:SftpClient.java   
public SftpClient init() {
    try {
        String host = PropertiesUtil.getString("sftp.host");
        int port = PropertiesUtil.getInt("sftp.port");
        String userName = PropertiesUtil.getString("sftp.user.name");
        String password = PropertiesUtil.getString("sftp.user.password");
        Integer timeout = PropertiesUtil.getInt("sftp.timeout");
        Integer aliveMax = PropertiesUtil.getInt("sftp.aliveMax");
        JSch jsch = new JSch(); // 创建JSch对象
        session = jsch.getSession(userName, host, port); // 根据用户名,主机ip,端口获取一个Session对象
        if (password != null) {
            session.setPassword(password); // 设置密码
        }
        session.setConfig("StrictHostKeyChecking", "no"); // 为Session对象设置properties
        if (timeout != null) session.setTimeout(timeout); // 设置timeout时间
        if (aliveMax != null) session.setServerAliveCountMax(aliveMax);
        session.connect(); // 通过Session建立链接
        channel = (ChannelSftp)session.openChannel("sftp"); // 打开SFTP通道
        channel.connect(); // 建立SFTP通道的连接
        logger.info("SSH Channel connected.");
    } catch (JSchException e) {
        throw new FtpException("", e);
    }
    return this;
}
项目:vco-powershel-plugin    文件:SSH2AbstractSession.java   
public void connectWithIdentity(String identityPath, String passPhrase) throws JSchException,FileNotFoundException {
    if (identityPath == null || new File(identityPath).exists() == false) {
        throw new FileNotFoundException("Identity file not found !") ;
    }
    if (m_session != null) {
        m_session.disconnect();
    }
    preConnect();
    JSch jsch = new JSch();
    if (passPhrase != null && passPhrase.length() >0) {
        jsch.addIdentity(identityPath, passPhrase);
    }
    else {
        jsch.addIdentity(identityPath);
    }

    SSH2User userInfo = new SSH2User(m_username, passPhrase);
    m_session = jsch.getSession(m_username, m_host, m_port);
    m_session.setConfig(infos);
    m_session.setUserInfo(userInfo);
    m_session.connect();
}
项目:BigDataScript    文件:Ssh.java   
/**
 * 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;
}
项目:acr-java-manage-azure-container-registry    文件:SSHShell.java   
/**
 * 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();
}
项目:acr-java-manage-azure-container-registry    文件:SSHShell.java   
/**
 * Automatically generate SSH keys.
 * @param passPhrase the byte array content to be uploaded
 * @param comment the name of the file for which the content will be saved into
 * @return SSH public and private key
 * @throws Exception exception thrown
 */
public static SshPublicPrivateKey generateSSHKeys(String passPhrase, String comment) throws Exception {
    JSch jsch = new JSch();
    KeyPair keyPair = KeyPair.genKeyPair(jsch, KeyPair.RSA);
    ByteArrayOutputStream privateKeyBuff = new ByteArrayOutputStream(2048);
    ByteArrayOutputStream publicKeyBuff = new ByteArrayOutputStream(2048);

    keyPair.writePublicKey(publicKeyBuff, (comment != null) ? comment : "SSHCerts");

    if (passPhrase == null  || passPhrase.isEmpty()) {
        keyPair.writePrivateKey(privateKeyBuff);
    } else {
        keyPair.writePrivateKey(privateKeyBuff, passPhrase.getBytes());
    }

    return new SshPublicPrivateKey(privateKeyBuff.toString(), publicKeyBuff.toString());
}
项目:kheera    文件:SeleniumGridManager.java   
public static String connectAndExecute(String user, String host, String password, String command1) {
    String CommandOutput = null;
    try {

        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        JSch jsch = new JSch();

        Session session = jsch.getSession(user, host, 22);
        session.setPassword(password);
        session.setConfig(config);
        session.connect();
        // System.out.println("Connected");

        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command1);
        channel.setInputStream(null);
        ((ChannelExec) channel).setErrStream(System.err);

        InputStream in = channel.getInputStream();

        channel.connect();
        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);

                if (i < 0)
                    break;
                // System.out.print(new String(tmp, 0, i));
                CommandOutput = new String(tmp, 0, i);
            }

            if (channel.isClosed()) {
                // System.out.println("exit-status: " +
                // channel.getExitStatus());
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception ee) {
            }
        }
        channel.disconnect();
        session.disconnect();
        // System.out.println("DONE");

    } catch (Exception e) {
        e.printStackTrace();
    }
    return CommandOutput;

}
项目:keepass2android    文件:SftpStorage.java   
ChannelSftp init(String filename) throws JSchException, UnsupportedEncodingException {
    jsch = new JSch();
    ConnectionInfo ci = splitStringToConnectionInfo(filename);

    Session session = jsch.getSession(ci.username, ci.host, ci.port);
    UserInfo ui = new SftpUserInfo(ci.password);
    session.setUserInfo(ui);

    session.connect();

    Channel channel = session.openChannel("sftp");
    channel.connect();
    ChannelSftp c = (ChannelSftp) channel;

    logDebug("success: init Sftp");
    return c;

}
项目:hadoop    文件:SshFenceByTcpPort.java   
private Session createSession(String host, Args args) throws JSchException {
  JSch jsch = new JSch();
  for (String keyFile : getKeyFiles()) {
    jsch.addIdentity(keyFile);
  }
  JSch.setLogger(new LogAdapter());

  Session session = jsch.getSession(args.user, host, args.sshPort);
  session.setConfig("StrictHostKeyChecking", "no");
  return session;
}
项目:ubongo    文件:SSHConnection.java   
public static Session establishWithKey(String sshHost, int sshPort, String user, String keyFilePath) throws JSchException {
    File keyFile = new File(keyFilePath);
    if (!keyFile.exists()) {
        String errorMsg = "Could not find SSH public key file in path: " + keyFilePath;
        logger.info(errorMsg);
        throw new JSchException(errorMsg);
    }
    Session session;
    JSch jsch = new JSch();
    try {
        jsch.addIdentity(keyFile.getAbsolutePath());
        session = jsch.getSession(user, sshHost, sshPort);
    }
    catch (JSchException e) {
        logger.error("SSH connection attempt to host: " + sshHost + ":" + sshPort + " failed");
        throw e;
    }
    return connect(session, sshHost, sshPort);
}
项目:InstantPatchIdeaPlugin    文件:RemoteClientImplTest.java   
@Test
public void testJschConnection() throws InterruptedException, SftpException, JSchException, IOException {
    JSch jsch = new JSch();
    String passphrase = "";
    jsch.addIdentity(privateKey,
        StringUtil.isEmpty(passphrase) ?
        null : passphrase);

    Session session = jsch.getSession(user, host, port);
    System.out.println("session created.");

    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    config.put("PreferredAuthentications",
        "publickey,keyboard-interactive,password");
    session.setConfig(config);
    session.connect();
    Thread.sleep(500);
    session.disconnect();
}
项目:ssh-proxy    文件:JSchHelper.java   
protected static void reconfigureServerHostKeyOrder(ServerHostKeySortOrder hostKeySortOrder) {
    List<HostKeyType> serverHostKeys = new ArrayList<>(getServerHostKeys());
    if (hostKeySortOrder == ServerHostKeySortOrder.PREFER_ECDSA) {
        Collections.sort(serverHostKeys, CMP_PREFER_ECDSA);
    } else if (hostKeySortOrder == ServerHostKeySortOrder.PREFER_RSA) {
        Collections.sort(serverHostKeys, CMP_PREFER_RSA);
    } else {
        throw new IllegalArgumentException("Unknown host key sort order: " + hostKeySortOrder);
    }

    if (!getServerHostKeys().equals(serverHostKeys)) {
        log.debug("changing server host key order to: " + serverHostKeys);

        List<String> serverHostKeyNames = new ArrayList<>();
        for (HostKeyType serverHostKey : serverHostKeys) {
            serverHostKeyNames.add(serverHostKey.getTypeString());
        }

        String newHostKeyOrder = Utils.join(serverHostKeyNames, SERVER_HOST_KEY_SEPARATOR);
        JSch.setConfig(JSCH_CONFIG_KEY_SERVER_HOST_KEY, newHostKeyOrder);
    }
}
项目:nomulus    文件:JSchModule.java   
@Provides
static JSch provideJSch(
    @Config("rdeSshIdentity") String identity,
    @Key("rdeSshClientPrivateKey") String privateKey,
    @Key("rdeSshClientPublicKey") String publicKey) {
  applyAppEngineKludge();
  JSch jsch = new JSch();
  try {
    jsch.addIdentity(
        identity,
        privateKey.getBytes(UTF_8),
        publicKey.getBytes(UTF_8),
        null);
  } catch (JSchException e) {
    throw new RuntimeException(e);
  }
  // TODO(b/13028224): Implement known hosts checking.
  JSch.setConfig("StrictHostKeyChecking", "no");
  return jsch;
}
项目:Ifc2Rdf    文件:SshFileUploader.java   
/**
     * 
     * @param sourceFilePath
     * @param destinationFilePath
     * @param destinationHost
     * @param destinationPort
     * @param destinationUserName
     * @param destinationUserPassword
     * @param destinationPrivateKeyFilePath
     * @param destinationPrivateKeyPassphrase
     * @throws IOException
     * @throws JSchException
     * @throws SftpException
     */
    public static void copyFile(
            String sourceFilePath,
            String destinationFilePath,
            String destinationHost,
            String destinationPort,
            String destinationUserName,
            String destinationUserPassword,
            String destinationPrivateKeyFilePath,
            String destinationPrivateKeyPassphrase) throws IOException, JSchException, SftpException {

        JSch jsch = new JSch();

        if (!StringUtils.isEmptyOrNull(destinationPrivateKeyFilePath)) {
            jsch.addIdentity(destinationPrivateKeyFilePath, destinationPrivateKeyPassphrase);
        }

        int destinationPortNumber = 22;
        if (!StringUtils.isEmptyOrNull(destinationPort)) {
            destinationPortNumber = Integer.parseInt(destinationPort);
        }

        Session session = jsch.getSession(destinationUserName, destinationHost, destinationPortNumber);
        if (!StringUtils.isEmptyOrNull(destinationUserPassword)) {
            session.setPassword(destinationUserPassword);
        }

//      Properties config = new Properties();
//        config.put("StrictHostKeyChecking", "no");
//        session.setConfig(config);
        session.connect();

        Channel channel = session.openChannel("sftp");
        channel.connect();

        ChannelSftp channelSftp = (ChannelSftp)channel;        
        File destinationFile = new File(destinationFilePath);
        channelSftp.cd(destinationFile.getPath());
        channelSftp.put(new FileInputStream(sourceFilePath), destinationFile.getName());


    }
项目:kxssh    文件:JSchScpUploadTest.java   
@Before
public void setUp() throws IOException {
    remoteFile = "remote.txt";
    localFile = File.createTempFile("local", ".txt");
    connectionProperties = mock(SshConnectionProperties.class);
    authentication = mock(SshPasswordAuthentication.class);
    session = mock(Session.class);
    ioFactory = mock(SshIOFactory.class);
    jschFactory = mock(JSchFactory.class);
    jsch = mock(JSch.class);
    listener = mock(SshStatusListener.class);
    ioChannel = mock(JSchIOChannel.class);
    input = mock(FileInputStream.class);
    output = mock(FileOutputStream.class);
    connectionProperties = mock(SshConnectionProperties.class);
    upload = new JSchScpUpload(connectionProperties);

    byte[] buffer = "test file".getBytes("UTF-8");
    new FileOutputStream(localFile).write(buffer);
    filesize = buffer.length;
}
项目:SPA    文件:SSHRemoteConnection.java   
@Override
public void open() throws RemoteConnectionException
{
    try
    {
        jsch = new JSch();
        LOGGER.debug("Adding publickey %s", host.getKeyFile());
        jsch.addIdentity(host.getKeyFile());

        openSession();

        connectionRegistry.add(this);
    } catch (JSchException e)
    {
        throw new RemoteConnectionException(e);
    }
}
项目:SPA    文件:SSHRemoteConnection.java   
@Override
public void open() throws RemoteConnectionException
{
    try
    {
        jsch = new JSch();
        LOGGER.debug("Adding publickey %s", host.getKeyFile());
        jsch.addIdentity(host.getKeyFile());

        openSession();

        connectionRegistry.add(this);
    } catch (JSchException e)
    {
        throw new RemoteConnectionException(e);
    }
}
项目:twister.github.io    文件:LibrariesPanel.java   
private void initializeSftp(){
    try{
        JSch jsch = new JSch();
        session = jsch.getSession(RunnerRepository.user, RunnerRepository.host, 22);
        session.setPassword(RunnerRepository.password);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        Channel channel = session.openChannel("sftp");
        channel.connect();
        connection = (ChannelSftp)channel;
    } catch (Exception e){
        e.printStackTrace();
    }
}
项目:twister.github.io    文件:RunnerRepository.java   
private static void ssh(String user, String passwd, String host){
    try{JSch jsch = new JSch();
        session = jsch.getSession(user, host, 22);
        session.setPassword(passwd);
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();
        Channel channel = session.openChannel("shell");
        channel.connect();
        Thread.sleep(1000);
        channel.disconnect();
        session.disconnect();
    }catch(Exception e){
        e.printStackTrace();
    }
}
项目:twister.github.io    文件:RunnerRepository.java   
public static boolean userpassword(String user,String password, String host){
        boolean passed = false;
            try{
                JSch jsch = new JSch();
                session = jsch.getSession(user, host, 22);
                session.setPassword(password);
                Properties config = new Properties();
                config.put("StrictHostKeyChecking", "no");
                session.setConfig(config);
                session.connect();
                Channel channel = session.openChannel("sftp");
                channel.connect();
                connection = (ChannelSftp)channel;
                try{USERHOME = connection.pwd();}
                catch(Exception e){
                    System.out.println("ERROR: Could not retrieve remote user home directory");}
                REMOTECONFIGDIRECTORY = USERHOME+"/twister/config/";
                passed = true;
            }
            catch(JSchException ex){
                if(ex.toString().indexOf("Auth fail")!=-1)
                    System.out.println("wrong user and/or password");
                else{ex.printStackTrace();
                    System.out.println("Could not connect to server");}}
//                 }
        return true;}
项目:twister.github.io    文件:ConfigTree.java   
private void initializeSftp(){
    try{
        JSch jsch = new JSch();
        session = jsch.getSession(RunnerRepository.user, RunnerRepository.host, 22);
        session.setPassword(RunnerRepository.password);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        Channel channel = session.openChannel("sftp");
        channel.connect();
        connection = (ChannelSftp)channel;
    } catch (Exception e){
        e.printStackTrace();
    }
}
项目:lakeside-java    文件:SshConnection.java   
/**
 * Connects to and maintains a ssh connection.  If this method is called
 * twice, a reconnection is attempted
 *
 * @throws SshException          If the members of the SshConnection class are not properly set or if
 *                               there was a problem actually connecting to the specified host.
 * @throws IllegalStateException If connect() was called once successfully. connect() and any setter
 *                               method can't be called after successfully connecting without first
 *                               disconnecting.
 */
public void connect() throws SshException {
    exceptIfAlreadyConnected();

    try {
        JSch jsch = new JSch();

        validateMembers();

        if (this.usePrivateKey) {
            jsch.addIdentity(this.privateKeyFile.getAbsolutePath());
        }

        this.sshSession = jsch.getSession(this.username, this.host, this.port);
        this.sshSession.setConfig(SSH_PROPERTIES);

        if (!this.usePrivateKey && this.password != null) {
            this.sshSession.setPassword(this.password);
        }

        this.sshSession.connect();
    } catch (JSchException e) {
        throw new SshException(e);
    }

}
项目:acr-java-manage-azure-container-registry    文件:SSHShell.java   
/**
 * Creates SSHShell.
 *
 * @param host the host name
 * @param port the ssh port
 * @param userName the ssh user name
 * @param password the ssh password
 * @return the shell
 * @throws JSchException
 * @throws IOException
 */
private SSHShell(String host, int port, String userName, String password)
        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();
    this.session = jsch.getSession(userName, host, port);
    session.setPassword(password);
    Hashtable<String, String> config = new Hashtable<>();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.connect(60000);
    this.channel = (ChannelShell) session.openChannel("shell");
    this.expect = new Expect4j(channel.getInputStream(), channel.getOutputStream());
    channel.connect();
}
项目:n4js    文件:SshSessionFactory.java   
private JSch configureIdentity(final JSch jsch) throws JSchException {

        final File sshDirectory = new File(StandardSystemProperty.USER_HOME.value() + "/.ssh");
        checkState(sshDirectory.exists(), ".ssh directory does not exist under home folder.");
        checkState(sshDirectory.canRead(), ".ssh directory content cannot be read.");
        checkState(sshDirectory.isDirectory(), sshDirectory.getAbsoluteFile() + " is not a directory.");
        final File[] keyFiles = sshDirectory.listFiles();
        checkState(null != keyFiles && keyFiles.length > 0, "No SSH key files exist.");

        jsch.removeAllIdentity();
        for (final File keyFile : keyFiles) {
            if (keyFile.isFile()) {
                final String keyUri = keyFile.toURI().toString();
                final int lastIndexOf = keyUri.lastIndexOf("/");
                if (lastIndexOf > 0) {
                    final String keyFileName = keyUri.substring(lastIndexOf + 1);
                    if ("id_rsa".equals(keyFileName) || "id_dsa".equals(keyFileName)) {
                        if (isEncrypted(keyFile)) {
                            String pw = getPassphrase(keyFile);
                            jsch.addIdentity(keyFile.getAbsolutePath(), pw);
                        } else {
                            jsch.addIdentity(keyFile.getAbsolutePath());
                        }

                        break;
                    }
                }
            }
        }

        return jsch;
    }
项目:incubator-netbeans    文件:JGitSshSessionFactory.java   
private boolean setupJSchIdentityRepository (JSch jsch, String identityFile, boolean preferAgent) throws JSchException {
    boolean agentUsed = false;
    if (preferAgent) {
        Connector con = ConnectorFactory.getInstance().createConnector(ConnectorFactory.ConnectorKind.ANY);
        if (con != null) {
            IdentityRepository irepo = new IdentityRepositoryImpl(con);
            if (irepo.getStatus() == IdentityRepository.RUNNING) {
                jsch.setIdentityRepository(irepo);
                agentUsed = true;
            }
        }
    }
    if (!agentUsed) {
        jsch.setIdentityRepository(null);
        // remove all identity files
        jsch.removeAllIdentity();
        // and add the one specified by CredentialsProvider
        jsch.addIdentity(identityFile);
    }
    return agentUsed;
}
项目:incubator-netbeans    文件:Authentication.java   
public static boolean isValidSSHKeyFile(String filename) {
    JSch test = new JSch();

    try {
        test.addIdentity(filename);
    } catch (JSchException ex) {
        return false;
    }

    return true;
}
项目:incubator-netbeans    文件:Authentication.java   
private static boolean isValidKnownHostsFile(String knownHostsFile) {
    JSch test = new JSch();

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

    return true;
}
项目:hadoop-oss    文件:SshFenceByTcpPort.java   
private Session createSession(String host, Args args) throws JSchException {
  JSch jsch = new JSch();
  for (String keyFile : getKeyFiles()) {
    jsch.addIdentity(keyFile);
  }
  JSch.setLogger(new LogAdapter());

  Session session = jsch.getSession(args.user, host, args.sshPort);
  session.setConfig("StrictHostKeyChecking", "no");
  return session;
}
项目:hue    文件:SshService.java   
public void connect() throws SshException {
    try {
        final JSch jsch = new JSch();
        if (sshKeyFile != null) {
            if (sshPassphrase != null && !sshPassphrase.trim().equals("")) {
                jsch.addIdentity(sshKeyFile);
            }
            else {
                jsch.addIdentity(sshKeyFile, sshPassphrase);
            }
        }

        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");

        session = jsch.getSession(sshUserName, sshHostName, sshPort);
        session.setConfig(config);

        if (sshKeyFile == null) {
            session.setPassword(sshPassword);
        }

        session.connect();
        session.setPortForwardingL(localPort, hostName, port);
    }
    catch (Exception e) {
        if (CommonUtils.doesPortForwardingAlreadyExist(e))
            session = null;
        else
            throw new SshException(e);
    }
}
项目:bestconf    文件:SFTPUtil.java   
public static Session connect(String host, Integer port, String user, String password) throws JSchException{
    Session session = null;
    try {
        JSch jsch = new JSch();
        if(port != null){
            session = jsch.getSession(user, host, port.intValue());
        }else{
            session = jsch.getSession(user, host);
        }
        session.setPassword(password);

        session.setConfig("StrictHostKeyChecking", "no");
        //time out
        session.connect(3000);
    } catch (JSchException e) {
        e.printStackTrace();
        System.out.println("SFTPUitl connection error");
        throw e;
    }
    return session;
}
项目:azure-libraries-for-java    文件:SshShell.java   
/**
 * Creates SSHShell.
 *
 * @param host the host name
 * @param port the ssh port
 * @param userName the ssh user name
 * @param password the ssh password
 * @return the shell
 * @throws JSchException
 * @throws IOException
 */
private SshShell(String host, int port, String userName, String password)
        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();
    this.session = jsch.getSession(userName, host, port);
    session.setPassword(password);
    Hashtable<String,String> config = new Hashtable<>();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.connect(60000);
    this.channel = (ChannelShell) session.openChannel("shell");
    this.expect = new Expect4j(channel.getInputStream(), channel.getOutputStream());
    channel.connect();
}
项目:azure-libraries-for-java    文件:ComputeManagementTest.java   
protected void ensureCanDoSsh(String fqdn, int sshPort, String uname, String password) {
    if (isPlaybackMode()) {
        return;
    }
    JSch jsch = new JSch();
    com.jcraft.jsch.Session session = null;
    try {
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session = jsch.getSession(uname, fqdn, sshPort);
        session.setPassword(password);
        session.setConfig(config);
        session.connect();
    } catch (Exception e) {
        Assert.fail("SSH connection failed" + e.getMessage());
    } finally {
        if (session != null) {
            session.disconnect();
        }
    }
}
项目:azure-libraries-for-java    文件:SSHShell.java   
/**
 * Creates SSHShell.
 *
 * @param host the host name
 * @param port the ssh port
 * @param userName the ssh user name
 * @param password the ssh password
 * @return the shell
 * @throws JSchException
 * @throws IOException
 */
private SSHShell(String host, int port, String userName, String password)
        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();
    this.session = jsch.getSession(userName, host, port);
    session.setPassword(password);
    Hashtable<String, String> config = new Hashtable<>();
    config.put("StrictHostKeyChecking", "no");
    session.setConfig(config);
    session.connect(60000);
    this.channel = (ChannelShell) session.openChannel("shell");
    this.expect = new Expect4j(channel.getInputStream(), channel.getOutputStream());
    channel.connect();
}
项目:azure-libraries-for-java    文件:SSHShell.java   
/**
 * 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();
}
项目:azure-libraries-for-java    文件:SSHShell.java   
/**
 * Automatically generate SSH keys.
 * @param passPhrase the byte array content to be uploaded
 * @param comment the name of the file for which the content will be saved into
 * @return SSH public and private key
 * @throws Exception exception thrown
 */
public static SshPublicPrivateKey generateSSHKeys(String passPhrase, String comment) throws Exception {
    JSch jsch = new JSch();
    KeyPair keyPair = KeyPair.genKeyPair(jsch, KeyPair.RSA);
    ByteArrayOutputStream privateKeyBuff = new ByteArrayOutputStream(2048);
    ByteArrayOutputStream publicKeyBuff = new ByteArrayOutputStream(2048);

    keyPair.writePublicKey(publicKeyBuff, (comment != null) ? comment : "SSHCerts");

    if (passPhrase == null  || passPhrase.isEmpty()) {
        keyPair.writePrivateKey(privateKeyBuff);
    } else {
        keyPair.writePrivateKey(privateKeyBuff, passPhrase.getBytes());
    }

    return new SshPublicPrivateKey(privateKeyBuff.toString(), publicKeyBuff.toString());
}
项目:oneops    文件:TransUtil.java   
public Map<String,String> keyGen(String passPhrase, String pubDesc) {
    JSch jsch=new JSch();
       String passphrase= (passPhrase == null) ? "" : passPhrase;
       Map<String,String> result = new HashMap<String,String>();
       try{
        KeyPair kpair=KeyPair.genKeyPair(jsch, KeyPair.RSA, 2048);
        kpair.setPassphrase(passphrase);
        OutputStream prkos = new ByteArrayOutputStream();
        kpair.writePrivateKey(prkos);
        String privateKey = prkos.toString();
        //removing "\n" at the end of the string
        result.put("private", privateKey.substring(0, privateKey.length() - 1));
        OutputStream pubkos = new ByteArrayOutputStream();
        kpair.writePublicKey(pubkos, pubDesc);
        String pubKey = pubkos.toString();
        //removing "\n" at the end of the string
        result.put("public", pubKey.substring(0, pubKey.length() - 1));
        kpair.dispose();
        return result;
       } catch(Exception e){
        System.out.println(e);
        logger.error(e.getMessage());
        throw new TransistorException(CmsError.TRANSISTOR_EXCEPTION, e.getMessage());
       }
}
项目:Hydrograph    文件:SCPUtility.java   
public Message validateCredentials(String host, String user, String password) {

        JSch jsch = new JSch();

        Session session;
        try {
            session = jsch.getSession(user, host, SSH_PORT);

            session.setPassword(password);

            java.util.Properties config = new java.util.Properties();
            config.put(STRICT_HOST_KEY_CHECKING, STRICT_HOST_KEY_CHECKING_DEFAULT_VALUE);
            session.setConfig(config);

            session.setConfig(PREFERRED_AUTHENTICATIONS, PREFERRED_AUTHENTICATIONS_DEFAULT_VALUES);

            session.connect();
            session.disconnect();
        } catch (Exception e) {
            return getErrorMessage(e);
        }

        return new Message(MessageType.SUCCESS, GENERAL_SUCCESS_MESSAGE);
    }