概述
最近做了一个需求,需要从内网访问外网sftp服务器,上传文件至SFTP。所以需要使用到代理服务器,从代理服务器进行中转。
核心代码
/**
* Description: 连接SFTP
*
* @param ip
* FTP服务器ip
* @param port
* FTP服务器端口
* @param user
* FTP登录账号
* @param pwd
* FTP登录密码
* @param path
* FTP服务器根目录
*
*/
public void connect(String ip, int port, String user, String pwd,
String root) throws Exception {
if (isConnect) {
return;
}
if (root == null)
root = "";
if (root.length() != 0 && !root.endsWith("/")) {
root += "/";
}
this.root = root;
JSch jsch = new JSch();
//支持密钥的方式登陆,只需在jsch.getSession之前设置一下密钥的相关信息就可以了
if (org.apache.commons.lang3.StringUtils.isNotEmpty(privateKey)) {
if (passphrase != null && "".equals(passphrase)) {
//设置带口令的密钥
jsch.addIdentity(privateKey, passphrase);
} else {
//设置不带口令的密钥
jsch.addIdentity(privateKey);
}
}
sshSession = jsch.getSession(user, ip, port);// 登录
sshSession.setProxy(new ProxyHTTP(proxyIp,proxyPort));
if (org.apache.commons.lang3.StringUtils.isNotEmpty(pwd)) {
sshSession.setPassword(pwd);
}
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
Channel channel = sshSession.openChannel("sftp");
channel.connect();// 连接
sftp = (ChannelSftp) channel;
if (root.length() != 0) {
try {
sftp.cd(root);
} catch (Exception e) {
throw new Exception("dirErr:" + root, e);
}
}
isConnect = true;
}
这里处理的代理的核心就是
sshSession.setProxy(new ProxyHTTP(proxyIp,proxyPort));
因为我这边的代理服务器是http的,所以使用的是ProxyHTTP,jsch官网也有example可以参考一下http://www.jcraft.com/jsch/examples/ViaHTTP.java.html
如果是Socket的就改成
sshSession.setProxy(new ProxySOCKS4(proxyIp,proxyPort));
相对于jsch官网的examplehttp://www.jcraft.com/jsch/examples/ViaSOCKS.java.html