use of com.jcraft.jsch.Session 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.Session in project hadoop by apache.
the class SshFenceByTcpPort method tryFence.
@Override
public boolean tryFence(HAServiceTarget target, String argsStr) throws BadFencingConfigurationException {
Args args = new Args(argsStr);
InetSocketAddress serviceAddr = target.getAddress();
String host = serviceAddr.getHostName();
Session session;
try {
session = createSession(serviceAddr.getHostName(), args);
} catch (JSchException e) {
LOG.warn("Unable to create SSH session", e);
return false;
}
LOG.info("Connecting to " + host + "...");
try {
session.connect(getSshConnectTimeout());
} catch (JSchException e) {
LOG.warn("Unable to connect to " + host + " as user " + args.user, e);
return false;
}
LOG.info("Connected to " + host);
try {
return doFence(session, serviceAddr);
} catch (JSchException e) {
LOG.warn("Unable to achieve fencing on remote host", e);
return false;
} finally {
session.disconnect();
}
}
use of com.jcraft.jsch.Session in project hadoop by apache.
the class SFTPConnectionPool method disconnect.
void disconnect(ChannelSftp channel) throws IOException {
if (channel != null) {
// close connection if too many active connections
boolean closeConnection = false;
synchronized (this) {
if (liveConnectionCount > maxConnection) {
--liveConnectionCount;
con2infoMap.remove(channel);
closeConnection = true;
}
}
if (closeConnection) {
if (channel.isConnected()) {
try {
Session session = channel.getSession();
channel.disconnect();
session.disconnect();
} catch (JSchException e) {
throw new IOException(StringUtils.stringifyException(e));
}
}
} else {
returnToPool(channel);
}
}
}
use of com.jcraft.jsch.Session 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;
}
use of com.jcraft.jsch.Session in project azure-sdk-for-java by Azure.
the class TestVirtualMachineCustomData method createResource.
@Override
public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exception {
final String vmName = "vm" + this.testId;
final String publicIpDnsLabel = SdkContext.randomResourceName("abc", 16);
// Prepare the custom data
//
String cloudInitFilePath = getClass().getClassLoader().getResource("cloud-init").getPath();
// In Windows remove leading slash
cloudInitFilePath = cloudInitFilePath.replaceFirst("^/(.:/)", "$1");
byte[] cloudInitAsBytes = Files.readAllBytes(Paths.get(cloudInitFilePath));
byte[] cloudInitEncoded = Base64.encodeBase64(cloudInitAsBytes);
String cloudInitEncodedString = new String(cloudInitEncoded);
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_16_04_LTS).withRootUsername("testuser").withRootPassword("12NewPA$$w0rd!").withCustomData(cloudInitEncodedString).withSize(VirtualMachineSizeTypes.STANDARD_D3_V2).create();
pip.refresh();
Assert.assertTrue(pip.hasAssignedNetworkInterface());
if (!MockIntegrationTestBase.IS_MOCKED) {
JSch jsch = new JSch();
Session session = null;
ChannelExec channel = null;
try {
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session = jsch.getSession("testuser", publicIpDnsLabel + "." + "eastus.cloudapp.azure.com", 22);
session.setPassword("12NewPA$$w0rd!");
session.setConfig(config);
session.connect();
// Try running the package installed via init script
//
channel = (ChannelExec) session.openChannel("exec");
BufferedReader in = new BufferedReader(new InputStreamReader(channel.getInputStream()));
channel.setCommand("pwgen;");
channel.connect();
String msg;
while ((msg = in.readLine()) != null) {
Assert.assertFalse(msg.startsWith("The program 'pwgen' is currently not installed"));
}
} catch (Exception e) {
Assert.fail("SSH connection failed" + e.getMessage());
} finally {
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
}
}
return vm;
}
Aggregations