Skip to content

Instantly share code, notes, and snippets.

@kotenev
Forked from quidryan/build.gradle
Created March 12, 2023 18:52
Show Gist options
  • Select an option

  • Save kotenev/b1cd190b4fd7b67399d56e00861f4b9f to your computer and use it in GitHub Desktop.

Select an option

Save kotenev/b1cd190b4fd7b67399d56e00861f4b9f to your computer and use it in GitHub Desktop.
Code to use ssh-agent when using JGit. Running in Gradle with the gradle-git plugin.
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.ajoberstar:gradle-git:0.5.0' // not used in this example, but it's what brings in JGit
classpath 'com.jcraft:jsch.agentproxy.jsch:0.0.5'
classpath 'com.jcraft:jsch.agentproxy.usocket-jna:0.0.5'
classpath 'com.jcraft:jsch.agentproxy.sshagent:0.0.5'
}
}
import com.jcraft.jsch.*;
import com.jcraft.jsch.agentproxy.usocket.JNAUSocketFactory;
import com.jcraft.jsch.agentproxy.connector.SSHAgentConnector;
import org.eclipse.jgit.transport.JschConfigSessionFactory;
import org.eclipse.jgit.transport.OpenSshConfig;
import org.eclipse.jgit.transport.SshSessionFactory;
import org.eclipse.jgit.util.FS;
import java.io.FileInputStream;
def sessionFactory = new JschConfigSessionFactory() {
@Override
protected void configure(OpenSshConfig.Host host, Session session) {
// This can be removed, but the overriden method is required since JschConfigSessionFactory is abstract
session.setConfig("StrictHostKeyChecking", "false");
}
@Override
protected JSch createDefaultJSch(FS fs) throws JSchException {
Connector con = null;
try {
if(SSHAgentConnector.isConnectorAvailable()){
//USocketFactory usf = new JUnixDomainSocketFactory();
USocketFactory usf = new JNAUSocketFactory();
con = new SSHAgentConnector(usf);
}
} catch(AgentProxyException e){
System.out.println(e);
}
if (con == null) {
return super.createDefaultJSch(fs)
} else {
final JSch jsch = new JSch();
jsch.setConfig("PreferredAuthentications", "publickey");
IdentityRepository irepo = new RemoteIdentityRepository(con);
jsch.setIdentityRepository(irepo);
knownHosts(jsch, fs) // private method from parent class, yeah for Groovy!
return jsch
}
}
}
SshSessionFactory.setInstance(sessionFactory)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment