import java.util.Properties;
import com.cloudibpm.core.util.SystemConfig;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public class SFTPUtils {
protected static String host = SystemConfig.getProp("hostIp");
protected static String username = SystemConfig.getProp("username");
protected static String password = SystemConfig.getProp("password");
protected static String str = SystemConfig.getProp("port");
protected static String privateKey = SystemConfig.getProp("privateKey");
protected static String passphrase = SystemConfig.getProp("passphrase");
static Session session = null;
static Channel channel = null;
public static ChannelSftp connectSFTP() throws JSchException {
int port = Integer.parseInt(str);
JSch jsch = new JSch();
if (privateKey != null && !"".equals(privateKey)) {
//使用密钥验证方式,密钥可以使有口令的密钥,也可以是没有口令的密钥
if (passphrase != null && "".equals(passphrase)) {
jsch.addIdentity(privateKey, passphrase);
} else {
jsch.addIdentity(privateKey);
}
}
Session session = jsch.getSession(username, host, port);
if(password!=null){
session.setPassword(password);//设置密码
}
Properties conf = new Properties();
conf.put("StrictHostKeyChecking","no");
session.setConfig(conf);//为session对象设置properties
session.setTimeout(1000);
session.connect();
channel = session.openChannel("sftp");
channel.connect();
return (ChannelSftp) channel;
}
}