上面已经验证了通过密钥方式访问SSH Server是可行的,并且给自己搭建了一个测试环境,下面就开始我最终的目的:java程序通过密钥访问。 1、工程引入jsch-0.1.42.jar,可以到http://www.jcraft.com/jsch/官方下载。 2、在官方的example中,有一个demo,类UserAuthPubKey,是使用密钥访问的,参考了下,我对其进行了修改,改为自动连接并使用SFTP协议显示当前路径,代码如下: package Test.sftp; import com.jcraft.jsch.*; public class TestKeyAcc { String keyFile = "./id_rsa"; Session session = jsch.getSession(user, host, port); // username and passphrase will be given via UserInfo interface. Channel channel = session.openChannel("sftp"); public static class MyUserInfo implements UserInfo { public MyUserInfo(String passphrase) { public String getPassphrase() { public String getPassword() { public boolean promptPassphrase(String s) { public boolean promptPassword(String s) { public boolean promptYesNo(String s) { public void showMessage(String s) {
This is a private computer system. This computer system, including all Use of this computer system, authorized or unauthorized, constitutes consent
/cygdrive/d/opensshhome/username ok,good,问题解决了,如果不是密钥方式,与普通FTP一样的用户名及密码访问又是怎样的呢,那就比较简单了 去掉 jsch.addIdentity(keyFile); 及 UserInfo ui = new MyUserInfo(passphrase); 在Session sshSession = jsch.getSession(userStr, serverIp, port);下增加 如果在生成私钥时没有使用密码,那又是怎样的呢?其实很简单,如果不需要密码访问,你提供了密码也是通过的( new MyUserInfo(passphrase);中密码不null或空),大概过程是,先看是否需要密码,如果不需要,那么就直接过去,所以即便设置了密码也没问题。
在使用该API进行密钥及非密钥访问SFTP时,感觉不是很惬意,试验了许久才通过。 以上文字但愿对后来者有所帮助 |
java程序通过密钥方式使用JSch API访问SSH(转帖)
最新推荐文章于 2024-08-15 17:43:43 发布
java程序通过密钥方式使用JSch API访问SSH
2010-05-20 14:51