1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
|
import com.jcraft.jsch.AgentIdentityRepository;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.IdentityRepository;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.SSHAgentConnector;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UIKeyboardInteractive;
import com.jcraft.jsch.UserInfo;
import javax.swing.JOptionPane;
public class JSchWithAgentProxy {
public static void main(String[] arg) {
try {
JSch jsch = new JSch();
// IdentityRepository irepo = new AgentIdentityRepository(new PageantConnector());
IdentityRepository irepo = new AgentIdentityRepository(new SSHAgentConnector());
jsch.setIdentityRepository(irepo);
String host = null;
if (arg.length > 0) {
host = arg[0];
} else {
host = JOptionPane.showInputDialog("Enter username@hostname",
System.getProperty("user.name") + "@localhost");
}
String user = host.substring(0, host.indexOf('@'));
host = host.substring(host.indexOf('@') + 1);
Session session = jsch.getSession(user, host, 22);
session.setConfig("PreferredAuthentications", "publickey");
// username and passphrase will be given via UserInfo interface.
UserInfo ui = new MyUserInfo();
session.setUserInfo(ui);
session.connect();
Channel channel = session.openChannel("shell");
((ChannelShell) channel).setAgentForwarding(true);
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
channel.connect();
} catch (Exception e) {
System.out.println(e);
}
}
public static class MyUserInfo implements UserInfo, UIKeyboardInteractive {
String passwd = null;
@Override
public String getPassword() {
return passwd;
}
@Override
public boolean promptYesNo(String str) {
return true;
}
@Override
public String getPassphrase() {
return null;
}
@Override
public boolean promptPassphrase(String message) {
return true;
}
@Override
public boolean promptPassword(String message) {
return true;
}
@Override
public void showMessage(String message) {}
@Override
public String[] promptKeyboardInteractive(String destination, String name, String instruction,
String[] prompt, boolean[] echo) {
String[] response = new String[prompt.length];
response[0] = passwd;
return response;
}
}
}
|