Java Code Examples for com.jcraft.jsch.jsch#addIdentity()

The following examples show how to use com.jcraft.jsch.jsch#addIdentity() . 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: EmbeddedSSHClient.java    From embeddedlinux-jvmdebugger-intellij with Apache License 2.0 7 votes vote down vote up
/**
 * Gets SSH Client
 *
 * @return
 */
@SneakyThrows(JSchException.class)
public Session get() {
    JSch jsch = new JSch();
    UserInfo userInfo;
    Session session = jsch.getSession(username, hostname, port);
    if (useKey) {
        jsch.addIdentity(key);
        userInfo = new EmbeddedUserInfoInteractive();
    } else {
        session.setPassword(password);
        session.setConfig("StrictHostKeyChecking", "no");
        userInfo = EmbeddedUserInfo.builder().password(password).build();
    }
    session.setUserInfo(userInfo);
    session.setConfig("HashKnownHosts", "yes");
    session.setTimeout(10000);
    session.connect();
    return session;
}
 
Example 2
Source File: JSchModule.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Provides
static JSch provideJSch(
    @Config("rdeSshIdentity") String identity,
    @Key("rdeSshClientPrivateKey") String privateKey,
    @Key("rdeSshClientPublicKey") String publicKey) {
  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;
}
 
Example 3
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 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: GitContentRepository.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
private SshSessionFactory getSshSessionFactory(String privateKey, final Path tempKey)  {
    try {
        Files.write(tempKey, privateKey.getBytes());
        SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
            @Override
            protected void configure(OpenSshConfig.Host hc, Session session) {
                Properties config = new Properties();
                config.put("StrictHostKeyChecking", "no");
                session.setConfig(config);
            }

            @Override
            protected JSch createDefaultJSch(FS fs) throws JSchException {
                JSch defaultJSch = new JSch();
                defaultJSch.addIdentity(tempKey.toAbsolutePath().toString());
                return defaultJSch;
            }
        };
        return sshSessionFactory;
    } catch (IOException e) {
        logger.error("Failed to create private key for SSH connection.", e);
    }
    return null;
}
 
Example 6
Source File: GitRepositoryHelper.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
public SshSessionFactory getSshSessionFactory(String privateKey, final Path tempKey)  {
    try {
        Files.write(tempKey, privateKey.getBytes());
        SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
            @Override
            protected void configure(OpenSshConfig.Host hc, Session session) {
                Properties config = new Properties();
                config.put("StrictHostKeyChecking", "no");
                session.setConfig(config);
            }

            @Override
            protected JSch createDefaultJSch(FS fs) throws JSchException {
                JSch defaultJSch = new JSch();
                defaultJSch.addIdentity(tempKey.toAbsolutePath().toString());
                return defaultJSch;
            }
        };
        return sshSessionFactory;
    } catch (IOException e) {
        logger.error("Failed to create private key for SSH connection.", e);
    }
    return null;
}
 
Example 7
Source File: CustomJschConfigSessionFactory.java    From attic-stratos with Apache License 2.0 6 votes vote down vote up
@Override
protected JSch createDefaultJSch(FS fs) throws JSchException {

    JSch def = super.createDefaultJSch(fs);
    String keyName = ServerConfiguration.getInstance().
            getFirstProperty(GitDeploymentSynchronizerConstants.SSH_PRIVATE_KEY_NAME);
    String keyPath = ServerConfiguration.getInstance().
            getFirstProperty(GitDeploymentSynchronizerConstants.SSH_PRIVATE_KEY_PATH);

    if (keyName == null || keyName.isEmpty())
        keyName = GitDeploymentSynchronizerConstants.SSH_KEY;

    if (keyPath == null || keyPath.isEmpty())
        keyPath = System.getProperty("user.home") + "/" + GitDeploymentSynchronizerConstants.SSH_KEY_DIRECTORY;

    if (keyPath.endsWith("/"))
        def.addIdentity(keyPath + keyName);
    else
        def.addIdentity(keyPath + "/" + keyName);

    return def;
}
 
Example 8
Source File: SftpClient.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private boolean setAgent(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
        if (StringUtils.hasText(identityFile)) {
            jsch.addIdentity(identityFile);
        }
    }
    return agentUsed;
}
 
Example 9
Source File: CommandDelegatorMethods.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * For creating a JSCH session.
 * 
 * @param host
 *            the host
 * @return a JSCH session
 * @throws JSchException
 *             the jsch exception
 */
private Session createSession(CommandWritable.Command.SwitchedIdentity switchedIdentity, String host, CommandType commandType) throws JSchException {
	JSch jsch = new JSch();
	Session session = null;
	if(switchedIdentity.getPrivatePath() != null && !switchedIdentity.getPrivatePath().isEmpty()){
		jsch.addIdentity(switchedIdentity.getPrivatePath());	
	}
	java.util.Properties conf = new java.util.Properties();
	session = jsch.getSession(switchedIdentity.getUser(), host, RemotingConstants.TWENTY_TWO);
	if(switchedIdentity.getPasswd()!=null){
		try{
			session.setPassword(StringUtil.getPlain(switchedIdentity.getPasswd()));
		}catch(Exception e){
			LOGGER.error("Failed to Decrypt the password", e);
		}
	}
	conf.put(STRICT_HOST_KEY_CHECKING, "no");
	session.setConfig(conf);
    session.connect();
	LOGGER.debug("Session Established "+":["+session.isConnected()+"], for user ["+switchedIdentity.getUser()+"]");
	return session;
}
 
Example 10
Source File: JobConfigUtil.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static Session getSession(String host, String username, String password, String privateKeyPath)
		throws JSchException {
	JSch jsch = new JSch();
	Session session = null;
	if (StringUtils.isNotBlank(privateKeyPath)) {
		jsch.addIdentity(privateKeyPath);
	}
	session = jsch.getSession(username, host, 22);

	Properties config = new Properties();
	config.put("StrictHostKeyChecking", "no");
	if (StringUtils.isNotBlank(password)) {
		session.setPassword(password);
		config.put("PreferredAuthentications", "password");
	}
	session.setConfig(config);
	session.connect();
	return session;
}
 
Example 11
Source File: PooledSFTPConnection.java    From CloverETL-Engine with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void addIdentity(JSch jsch, URI key) throws IOException {
	try {
		String keyName = key.toString();
		log.debug("Adding new identity from " + keyName);
		try (InputStream is = FileUtils.getInputStream(null, keyName)) {
			byte[] prvKey = IOUtils.toByteArray(is);
			jsch.addIdentity(keyName, prvKey, null, null);
		}
	} catch (Exception e) {
		throw new IOException("Failed to read private key", e);
	}
}
 
Example 12
Source File: Authentication.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static boolean isValidSSHKeyFile(String filename) {
    JSch test = new JSch();

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

    return true;
}
 
Example 13
Source File: SftpFsHelper.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@Override
public boolean setIdentity(String privateKey, JSch jsch) {
  try {
    jsch.addIdentity(privateKey);
    log.info("Successfully set identity using local file " + privateKey);
    return true;
  } catch (Exception e) {
    log.warn("Failed to set identity using local file. Will attempt next strategy. " + e.getMessage());
  }
  return false;
}
 
Example 14
Source File: SshLocalhostNoEchoExample.java    From ExpectIt with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws JSchException, IOException {
    JSch jSch = new JSch();
    Session session = jSch.getSession(System.getenv("USER"), "localhost");
    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");
    jSch.addIdentity(System.getProperty("user.home") + "/.ssh/id_rsa");
    session.setConfig(config);
    session.connect();
    Channel channel = session.openChannel("shell");
    channel.connect();

    Expect expect = new ExpectBuilder()
            .withOutput(channel.getOutputStream())
            .withInputs(channel.getInputStream(), channel.getExtInputStream())
            .build();
    try {
        expect.expect(contains("$"));
        expect.sendLine("stty -echo");
        expect.expect(contains("$"));
        expect.sendLine("pwd");
        System.out.println("pwd1:" + expect.expect(contains("\n")).getBefore());
        expect.sendLine("exit");
    } finally {
        expect.close();
        channel.disconnect();
        session.disconnect();
    }
}
 
Example 15
Source File: JGitConfigSessionFactory.java    From mOrgAnd with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected JSch getJSch(OpenSshConfig.Host hc, FS fs) throws JSchException {
    JSch jSch = super.getJSch(hc, fs);
    jSch.removeAllIdentity();
    if (!keyLocation.isEmpty())
        jSch.addIdentity(keyLocation, password);
    return jSch;
}
 
Example 16
Source File: MultiUserSshSessionFactory.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void loadIdentity(final JSch sch, final File priv) {
    if (priv.isFile()) {
        try {
            sch.addIdentity(priv.getAbsolutePath());
        } catch (JSchException e) {
            // Instead, pretend the key doesn't exist.
        }
    }
}
 
Example 17
Source File: Identity.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a key pair from private key and public key files.
 * The public key file will be the private key file with {@code .pub} appended to the name.
 *
 * @param privateKeyFile The private key file.
 * @param passphrase The passphrase for the private key.
 * @return The created key pair.
 */
public static Identity fromFiles(final File privateKeyFile, final String passphrase) {
    Objects.requireNonNull(privateKeyFile);
    return new Identity() {

        @Override
        void addIdentity(JSch jsch) throws JSchException {
            jsch.addIdentity(privateKeyFile.getAbsolutePath(), passphrase);
        }
    };
}
 
Example 18
Source File: GitRepo.java    From warnings-ng-plugin with MIT License 4 votes vote down vote up
/**
 * Zip bare repository, copy to Docker container using sftp, then unzip. The repo is now accessible over
 * "ssh://git@ip:port/home/git/gitRepo.git"
 *
 * @param host
 *         IP of Docker container
 * @param port
 *         SSH port of Docker container
 */
public void transferToDockerContainer(String host, int port) {
    try {
        Path zipPath = Files.createTempFile("git", "zip");
        File zippedRepo = zipPath.toFile();
        String zippedFilename = zipPath.getFileName().toString();
        ZipUtil.pack(new File(dir.getPath()), zippedRepo);

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

        JSch jSch = new JSch();
        jSch.addIdentity(privateKey.getAbsolutePath());

        Session session = jSch.getSession("git", host, port);
        session.setConfig(props);
        session.connect();

        ChannelSftp channel = (ChannelSftp) session.openChannel("sftp");
        channel.connect();
        channel.cd("/home/git");
        channel.put(new FileInputStream(zippedRepo), zippedFilename);

        ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
        InputStream in = channelExec.getInputStream();
        channelExec.setCommand("unzip " + zippedFilename + " -d " + REPO_NAME);
        channelExec.connect();

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;
        int index = 0;
        while ((line = reader.readLine()) != null) {
            System.out.println(++index + " : " + line);
        }

        channelExec.disconnect();
        channel.disconnect();
        session.disconnect();
        // Files.delete(zipPath);
    }
    catch (IOException | JSchException | SftpException e) {
        throw new AssertionError("Can't transfer git repository to docker container", e);
    }
}
 
Example 19
Source File: GitClient.java    From flow-platform-x with Apache License 2.0 4 votes vote down vote up
@Override
protected JSch createDefaultJSch(FS fs) throws JSchException {
    JSch defaultJSch = super.createDefaultJSch(fs);
    defaultJSch.addIdentity(tmpPrivateKeyFile.toString());
    return defaultJSch;
}
 
Example 20
Source File: GitConfigStore.java    From vertx-config with Apache License 2.0 4 votes vote down vote up
public GitConfigStore(Vertx vertx, JsonObject configuration) {
  this.vertx = vertx;

  String path = Objects.requireNonNull(configuration.getString("path"),
    "The `path` configuration is required.");
  this.path = new File(path);
  if (this.path.isFile()) {
    throw new IllegalArgumentException("The `path` must not be a file");
  }

  JsonArray filesets = Objects.requireNonNull(configuration
      .getJsonArray("filesets"),
    "The `filesets` element is required.");

  for (Object o : filesets) {
    JsonObject json = (JsonObject) o;
    FileSet set = new FileSet(vertx, this.path, json);
    this.filesets.add(set);
  }

  // Git repository
  url = Objects.requireNonNull(configuration.getString("url"),
    "The `url` configuration (Git repository location) is required.");
  branch = configuration.getString("branch", "master");
  remote = configuration.getString("remote", "origin");

  if (Objects.nonNull(configuration.getString("user")) &&
      Objects.nonNull(configuration.getString("password"))) {
    credentialProvider = new UsernamePasswordCredentialsProvider(
      configuration.getString("user"), configuration.getString("password"));
  } else {
    credentialProvider = null;
  }
  if(Objects.nonNull(configuration.getString("idRsaKeyPath"))){
    SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
      @Override
      protected void configure(OpenSshConfig.Host host, Session session ) {
      }
      @Override
      protected JSch createDefaultJSch(FS fs ) throws JSchException {
        JSch defaultJSch = super.createDefaultJSch( fs );
        defaultJSch.setConfig("StrictHostKeyChecking", "no");
        defaultJSch.addIdentity(configuration.getString("idRsaKeyPath"));
        return defaultJSch;
      }
    };
    transportConfigCallback = new TransportConfigCallback() {
      @Override
      public void configure( Transport transport ) {
        SshTransport sshTransport = ( SshTransport )transport;
        sshTransport.setSshSessionFactory( sshSessionFactory );
      }
    };
  }else {
    transportConfigCallback = null;
  }

  try {
    git = initializeGit();
  } catch (Exception e) {
    throw new VertxException("Unable to initialize the Git repository", e);
  }
}