java程序通过密钥方式使用JSch API访问SSH(转帖)
java程序通过密钥方式使用JSch API访问SSH(转帖)
2011-05-09 20:44 297人阅读 评论(0) 收藏 举报
java程序通过密钥方式使用JSch API访问SSH
2010-05-20 14:51
上面已经验证了通过密钥方式访问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 {
public static void main(String[] arg) {
String keyFile = "./id_rsa";
String user = "username";
String host = "127.0.0.1";
String passphrase = "111111";
int port = 22;
try {
JSch jsch = new JSch();
jsch.addIdentity(keyFile);
Session session = jsch.getSession(user, host, port);
// username and passphrase will be given via UserInfo interface.
UserInfo ui = new MyUserInfo(passphrase);
session.setUserInfo(ui);
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftp = (ChannelSftp) channel;
System.out.println(sftp.pwd());
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
}
public static class MyUserInfo implements UserInfo {
private String passphrase = null;
public MyUserInfo(String passphrase) {
this.passphrase = passphrase;
}
public String getPassphrase() {
return passphrase;
}
public String getPassword() {
return null;
}
public boolean promptPassphrase(String s) {
return true;
}
public boolean promptPassword(String s) {
return true;
}
public boolean promptYesNo(String s) {
return true;
}
public void showMessage(String s) {
System.out.println(s);
}
}
}
运行后结果显示:
****USAGE WARNING****
This is a private computer system. This computer system, including all
related equipment, networks, and network devices (specifically including
Internet access) are provided only for authorized use. This computer system
may be monitored for all lawful purposes, including to ensure that its use
is authorized, for management of the system, to facilitate protection against
unauthorized access, and to verify security procedures, survivability, and
operational security. Monitoring includes active attacks by authorized entities
to test or verify the security of this system. During monitoring, information
may be examined, recorded, copied and used for authorized purposes. All
information, including personal information, placed or sent over this system
may be monitored.
Use of this computer system, authorized or unauthorized, constitutes consent
to monitoring of this system. Unauthorized use may subject you to criminal
prosecution. Evidence of unauthorized use collected during monitoring may be
used for administrative, criminal, or other adverse a