use of com.jcraft.jsch.JSch in project incubator-gobblin by apache.
the class GitMonitoringService method getSshSessionFactory.
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;
}
use of com.jcraft.jsch.JSch in project mybatis-generator-gui by zouzg.
the class DbUtil method getSSHSession.
public static Session getSSHSession(DatabaseConfig databaseConfig) {
if (StringUtils.isBlank(databaseConfig.getSshHost()) || StringUtils.isBlank(databaseConfig.getSshPort()) || StringUtils.isBlank(databaseConfig.getSshUser()) || (StringUtils.isBlank(databaseConfig.getPrivateKey()) && StringUtils.isBlank(databaseConfig.getSshPassword()))) {
return null;
}
Session session = null;
try {
// Set StrictHostKeyChecking property to no to avoid UnknownHostKey issue
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Integer sshPort = NumberUtils.createInteger(databaseConfig.getSshPort());
int port = sshPort == null ? 22 : sshPort;
session = jsch.getSession(databaseConfig.getSshUser(), databaseConfig.getSshHost(), port);
if (StringUtils.isNotBlank(databaseConfig.getPrivateKey())) {
// 使用秘钥方式认证
jsch.addIdentity(databaseConfig.getPrivateKey(), StringUtils.defaultIfBlank(databaseConfig.getPrivateKeyPassword(), null));
} else {
session.setPassword(databaseConfig.getSshPassword());
}
session.setConfig(config);
} catch (JSchException e) {
// Ignore
}
return session;
}
use of com.jcraft.jsch.JSch in project navajo by Dexels.
the class SFTPMap method send.
private void send() throws UserException {
// String SFTPWORKINGDIR = "file/to/transfer";
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
logger.debug("preparing the host information for sftp.");
InputStream data = null;
try {
JSch jsch = new JSch();
session = jsch.getSession(this.username, this.server, this.remotePort);
if (this.password != null) {
session.setPassword(this.password);
}
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
logger.debug("Host connected.");
channel = session.openChannel("sftp");
channel.connect();
logger.debug("sftp channel opened and connected.");
channelSftp = (ChannelSftp) channel;
if (this.path != null) {
channelSftp.cd(this.path);
}
File f = new File(this.filename);
data = content.getDataAsStream();
channelSftp.put(data, f.getName());
logger.info("File transfered successfully to host.");
} catch (Exception ex) {
ex.printStackTrace();
throw new UserException("SFTP problem", ex);
} finally {
if (data != null) {
try {
data.close();
} catch (IOException e) {
}
}
if (channelSftp != null) {
channelSftp.exit();
}
logger.info("sftp Channel exited.");
if (channel != null) {
channel.disconnect();
}
logger.info("Channel disconnected.");
if (session != null) {
session.disconnect();
}
logger.info("Host Session disconnected.");
}
}
use of com.jcraft.jsch.JSch in project che by eclipse.
the class JGitConnection method executeRemoteCommand.
/**
* Execute remote jgit command.
*
* @param remoteUrl
* remote url
* @param command
* command to execute
* @return executed command
* @throws GitException
* @throws GitAPIException
* @throws UnauthorizedException
*/
@VisibleForTesting
Object executeRemoteCommand(String remoteUrl, TransportCommand command, @Nullable String username, @Nullable String password) throws GitException, GitAPIException, UnauthorizedException {
File keyDirectory = null;
UserCredential credentials = null;
try {
if (GitUrlUtils.isSSH(remoteUrl)) {
keyDirectory = Files.createTempDir();
final File sshKey = writePrivateKeyFile(remoteUrl, keyDirectory);
SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
@Override
protected void configure(OpenSshConfig.Host host, Session session) {
session.setConfig("StrictHostKeyChecking", "no");
}
@Override
protected JSch getJSch(final OpenSshConfig.Host hc, FS fs) throws JSchException {
JSch jsch = super.getJSch(hc, fs);
jsch.removeAllIdentity();
jsch.addIdentity(sshKey.getAbsolutePath());
return jsch;
}
};
command.setTransportConfigCallback(transport -> {
if (transport instanceof SshTransport) {
((SshTransport) transport).setSshSessionFactory(sshSessionFactory);
}
});
} else {
if (remoteUrl != null && GIT_URL_WITH_CREDENTIALS_PATTERN.matcher(remoteUrl).matches()) {
username = remoteUrl.substring(remoteUrl.indexOf("://") + 3, remoteUrl.lastIndexOf(":"));
password = remoteUrl.substring(remoteUrl.lastIndexOf(":") + 1, remoteUrl.indexOf("@"));
command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password));
} else {
if (username != null && password != null) {
command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password));
} else {
credentials = credentialsLoader.getUserCredential(remoteUrl);
if (credentials != null) {
command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(credentials.getUserName(), credentials.getPassword()));
}
}
}
}
ProxyAuthenticator.initAuthenticator(remoteUrl);
return command.call();
} catch (GitException | TransportException exception) {
if ("Unable get private ssh key".equals(exception.getMessage())) {
throw new UnauthorizedException(exception.getMessage(), ErrorCodes.UNABLE_GET_PRIVATE_SSH_KEY);
} else if (exception.getMessage().contains(ERROR_AUTHENTICATION_REQUIRED)) {
final ProviderInfo info = credentialsLoader.getProviderInfo(remoteUrl);
if (info != null) {
throw new UnauthorizedException(exception.getMessage(), ErrorCodes.UNAUTHORIZED_GIT_OPERATION, ImmutableMap.of(PROVIDER_NAME, info.getProviderName(), AUTHENTICATE_URL, info.getAuthenticateUrl(), "authenticated", Boolean.toString(credentials != null)));
}
throw new UnauthorizedException(exception.getMessage(), ErrorCodes.UNAUTHORIZED_GIT_OPERATION);
} else {
throw exception;
}
} finally {
if (keyDirectory != null && keyDirectory.exists()) {
try {
FileUtils.delete(keyDirectory, FileUtils.RECURSIVE);
} catch (IOException exception) {
throw new GitException("Can't remove SSH key directory", exception);
}
}
ProxyAuthenticator.resetAuthenticator();
}
}
use of com.jcraft.jsch.JSch in project azure-sdk-for-java by Azure.
the class TestVirtualMachineSsh method createResource.
@Override
public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exception {
final String vmName = "vm" + this.testId;
final String sshKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD azjava@javalib.com";
final String publicIpDnsLabel = vmName;
PublicIPAddress pip = pips.define(publicIpDnsLabel).withRegion(Region.US_EAST).withNewResourceGroup().withLeafDomainLabel(publicIpDnsLabel).create();
VirtualMachine vm = virtualMachines.define(vmName).withRegion(pip.regionName()).withExistingResourceGroup(pip.resourceGroupName()).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withExistingPrimaryPublicIPAddress(pip).withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_14_04_LTS).withRootUsername("testuser").withRootPassword("12NewPA$$w0rd!").withSsh(sshKey).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
pip.refresh();
Assert.assertTrue(pip.hasAssignedNetworkInterface());
JSch jsch = new JSch();
Session session = null;
if (!MockIntegrationTestBase.IS_MOCKED) {
try {
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
// jsch.addIdentity(sshFile, filePassword);
session = jsch.getSession("testuser", publicIpDnsLabel + "." + "eastus.cloudapp.azure.com", 22);
session.setPassword("12NewPA$$w0rd!");
session.setConfig(config);
session.connect();
} catch (Exception e) {
Assert.fail("SSH connection failed" + e.getMessage());
} finally {
if (session != null) {
session.disconnect();
}
}
Assert.assertNotNull(vm.inner().osProfile().linuxConfiguration().ssh());
Assert.assertTrue(vm.inner().osProfile().linuxConfiguration().ssh().publicKeys().size() > 0);
}
return vm;
}
Aggregations