1.要准备的jar包:ant.jar,ant-jsch.jar
code:
package com.test.utils;import org.apache.tools.ant.Project;import org.apache.tools.ant.taskdefs.optional.ssh.Scp;public class SCPHandler { private String keyFilePath; private String ip; private String user; private String psw; private int port; public SCPHandler(String keyFilePath, String ip, String user, String psw, int port) { this.keyFilePath = keyFilePath; this.ip = ip; this.user = user; this.psw = psw; this.port = port; } public boolean scpHandler(String toDir, String srcFile) { boolean flag = false; try { Project project = new Project(); Scp scp = new Scp(); scp.setProject(project); scp.setKeyfile(keyFilePath); if (psw != null) scp.setPassword(psw); scp.setPort(port); scp.setFile(srcFile); scp.setTodir(user + "@" + ip + ":" + toDir); scp.setTrust(true); scp.execute(); flag = true; } catch (Exception e) { e.printStackTrace(); } return flag; } public static void main(String[] args) { SCPHandler sh = new SCPHandler( "C:/192.168.1.1.ppk", "192.168.1.2", "user", null, 22); sh.scpHandler("/home/user", "C:/test.zip"); }}
2.如果用Ant的build.xml:
备注:上面的ppk文件是一个keyfile,如果没有的话,可以适当修改代码或xml文件即可。