以下是使用.pem文件获取与amazon实例的连接的代码。
import com.jcraft.jsch.*; public class JConnectEC2shell{ public static void main(String[] arg){ try{ JSch jsch=new JSch(); String user = "ec2-user"; String host = "Enter Ip address of your instance"; int port = 22; String privateKey = "D:\\privateKeyFile.pem"; jsch.addIdentity(privateKey); System.out.println("identity added "); Session session = jsch.getSession(user, host, port); System.out.println("session created."); // disabling StrictHostKeyChecking may help to make connection but makes it insecure // see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no // java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); Channel channel=session.openChannel("shell"); // Enable agent-forwarding. //((ChannelShell)channel).setAgentForwarding(true); channel.setInputStream(System.in); /* // a hack for MS-DOS prompt on Windows. channel.setInputStream(new FilterInputStream(System.in){ public int read(byte[] b, int off, int len)throws IOException{ return in.read(b, off, (len>1024?1024:len)); } }); */ channel.setOutputStream(System.out); /* // Choose the pty-type "vt102". ((ChannelShell)channel).setPtyType("vt102"); */ /* // Set environment variable "LANG" as "ja_JP.eucJP". ((ChannelShell)channel).setEnv("LANG", "ja_JP.eucJP"); */ //channel.connect(); channel.connect(3*1000); } catch(Exception e){ System.out.println(e); } } }
我想将.pem文件( jsch.addIdentity(privateKey);
)中的私钥设置为来自数据库的string。 现在它是一个文件名。 这是可能的,任何帮助将是可观的。 我已经从链接得到这个代码点击这里
Jsch
类提供了将私钥和公钥都作为字节数组的方法:
addIdentity(String name, byte[]prvkey, byte[]pubkey, byte[] passphrase)
所以你可以读你的数据库字段到一个字符串,然后通过它,例如
// read db columns String privateKey = ... String publicKey = ... String passphrase = ... final JSch jsch = new JSch(); jsch.addIdentity("my key", privateKey.getBytes(), publicKey.getBytes(), passphrase.getBytes());
我只是把pem文件名作为“my key”,并将pem文件的内容作为byte []传递,如下所示。 jsch.addIdentity(“privateKeyFile.pem”,pemString.getBytes(),null,null);
请注意,我必须在pem内容的第一行添加“+ System.getProperty(”line.separator“)”。 其他行不需要行分隔符,但除非第一行以分隔符结束,否则会出错。 例如“—– BEGIN RSA PRIVATE KEY —–”+ System.getProperty(“line.separator”)