Skip to content

Instantly share code, notes, and snippets.

@Igosuki
Created February 9, 2013 17:01
Show Gist options
  • Save Igosuki/4746052 to your computer and use it in GitHub Desktop.
Save Igosuki/4746052 to your computer and use it in GitHub Desktop.
Test an ssh connection using groovy and and jsch
import org.apache.ivy.plugins.repository.ssh.SshCache.CfUserInfo
import org.junit.Test
import com.jcraft.jsch.Channel
import com.jcraft.jsch.ChannelSftp
import com.jcraft.jsch.JSch
import com.jcraft.jsch.JSchException
import com.jcraft.jsch.Session
import com.jcraft.jsch.SftpException
import com.jcraft.jsch.UserInfo
class SshKeyTest {
@Test
public void testSsh() throws JSchException, SftpException {
JSch jSch = new JSch();
//final byte[] prvkey = new File("src/main/resources/keys/rsa.key").getBytes(); // Private key must be byte array
final byte[] prvkey = new File("src/main/resources/keys/id_rsa-d").getBytes(); // Private key must be byte array
final byte[] emptyPassPhrase = new byte[0]; // Empty passphrase for now, get real passphrase from MyUserInfo
jSch.addIdentity(
"prsadm", // String userName
prvkey, // byte[] privateKey
null, // byte[] publicKey
emptyPassPhrase // byte[] passPhrase
);
Session session = jSch.getSession("prsadm", "legstat-d.internal.epo.org", 22);
UserInfo ui = new CfUserInfo("legstat-d.internal.epo.org", "prsadm", null, null, null, null)
session.setUserInfo(ui);
session.connect();
Channel channel = session.openChannel("sftp");
ChannelSftp sftp = (ChannelSftp) channel;
sftp.connect();
final Vector files = sftp.ls(".");
for (Object obj : files) {
// Do stuff with files
}
sftp.disconnect();
session.disconnect();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment