sftp同步远程服务器文件

public class SftpTool {
private static LogTool logger = LogTool.getLogger(SftpTool.class.getName());
//出现连接异常时,重复连接三次
public static ChannelSftp getSftpChannel(String host, int port,
String username, String password,int i)throws Exception {
ChannelSftp sftp = null;
JSch jsch = new JSch();
try {
jsch.getSession(username, host, port);
Session sshSession = jsch.getSession(username, host, port);
System.out.println("Session created.");
sshSession.setPassword(password);
Properties sshConfig = new Properties();
sshConfig.put("StrictHostKeyChecking", "no");
sshSession.setConfig(sshConfig);
sshSession.connect();
Channel channel = sshSession.openChannel("sftp");
channel.connect();
sftp = (ChannelSftp) channel;
return sftp;
} catch (JSchException e) {
if(i>=1){
SftpTool.getSftpChannel(host, port, username, password,i-1);
}
e.printStackTrace();
logger.error(e.getMessage());
throw new Exception("Contact remote service failed");
}

}
//ConfigFileTool 用来读取配置文件信息
public void uploadFile() throws Exception {
Document doc = null;
try {
doc = ConfigFileTool.getLocalDocument("sftp_config.xml");
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage());
throw new Exception(e.getMessage());
}
List<Element> eleList = doc.selectNodes("//config/service");
if (null == eleList || 1 < eleList.size()) {
throw new Exception("The node that you select is not exists!");
}
Element ele = eleList.get(0);
String host = ele.element("host").getTextTrim();
int port = Integer.valueOf(ele.element("port").getTextTrim());
String username = ele.element("username").getTextTrim();
String password = ele.element("password").getTextTrim();
String directory = ele.element("remotedir").getTextTrim();
String uploadFile = ele.element("localdir").getTextTrim();
//3,为了采用递归的方式,实现出现异常时,重复连接三次
ChannelSftp sftp = SftpTool.getSftpChannel(host, port, username,
password,3);

try {
sftp.cd(directory);
File file = new File(uploadFile);
sftp.put(new FileInputStream(file), file.getName());
} catch (FileNotFoundException e) {
e.printStackTrace();
logger.error(e.getMessage());
throw new Exception("The file " + uploadFile + " not exists");
} catch (SftpException e) {
logger.error(e.getMessage());
e.printStackTrace();
throw new Exception("Upload file to remote service failed");
}finally {
//关闭连接
   if (sftp != null && sftp.isConnected()) {
   sftp.getSession().disconnect();
   sftp.quit();
   sftp.disconnect();
   }
}

}
}

你可能感兴趣的:(xml)