Ant scp upload文件至linux server(用java调用Ant api)

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:

<project name= "myproject" basedir= "." default="scp">    
    <target name="scp">      
        <echo message="---------------------------------------"/>  
        <scp file="${basedir}/test.zip" todir="user@192.168.1.2:/home/user" keyfile="${basedir}/192.168.1.1.ppk" trust="yes"/>
    </target>  
</project>

备注:上面的ppk文件是一个keyfile,如果没有的话,可以适当修改代码或xml文件即可。

posted on 2013-09-02 15:23  张飞_  阅读(1148)  评论(0编辑  收藏  举报

导航