sftp测试小程序

2 篇文章 0 订阅
1 篇文章 0 订阅

本程序将代码打包成jar,使用bat脚本调起运行,测试目标服务器和本机是否相通,传输文件能否成功

文件列表截图:
文件列表截图

LoadProperties:用于读取properties参数文件里的数据

public class LoadProperties {
    public static Properties getProperties() {
        File file = new File("/properties.properties");

        InputStream inputStream = null;

        try {
//          inputStream = new FileInputStream(file);
            inputStream = Object.class.getResourceAsStream("/properties.properties");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Properties properties = new Properties();
        try {
            properties.load(inputStream);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return properties;
    }
}

Login.java:用户连接sftp服务,推送文件

public class Login {
    public static void login(Properties properties) {
        String ip = properties.getProperty("ip");
        String user = properties.getProperty("user");
        String pwd = properties.getProperty("pwd");
        String port = properties.getProperty("port");
        String privateKeyPath = properties.getProperty("privateKeyPath");
        String passphrase = properties.getProperty("passphrase");
        String sourcePath = properties.getProperty("sourcePath");
        String destinationPath = properties.getProperty("destinationPath");

        if (ip != null && !ip.equals("") && user != null && !user.equals("")
                && port != null && !port.equals("") && sourcePath != null
                && !sourcePath.equals("") && destinationPath != null
                && !destinationPath.equals("")) {

            if (privateKeyPath != null && !privateKeyPath.equals("")) {
                sshSftp2(ip, user, Integer.parseInt(port), privateKeyPath,
                        passphrase, sourcePath, destinationPath);
            } else if (pwd != null && !pwd.equals("")) {
                sshSftp(ip, user, pwd, Integer.parseInt(port), sourcePath,
                        destinationPath);
            } else {
                Console console = System.console();
                System.out.print("Enter password:");
                char[] readPassword = console.readPassword();
                sshSftp(ip, user, new String(readPassword), Integer
                        .parseInt(port), sourcePath, destinationPath);
            }
        } else {
            System.out.println("请先设置配置文件");
        }
    }

    /**
     * 密码方式登录
     * 
     * @param ip
     * @param user
     * @param psw
     * @param port
     * @param sPath
     * @param dPath
     */
    public static void sshSftp(String ip, String user, String psw, int port,
            String sPath, String dPath) {
        System.out.println("password login");
        Session session = null;

        JSch jsch = new JSch();
        try {
            if (port <= 0) {
                // 连接服务器,采用默认端口
                session = jsch.getSession(user, ip);
            } else {
                // 采用指定的端口连接服务器
                session = jsch.getSession(user, ip, port);
            }

            // 如果服务器连接不上,则抛出异常
            if (session == null) {
                throw new Exception("session is null");
            }

            // 设置登陆主机的密码
            session.setPassword(psw);// 设置密码
            // 设置第一次登陆的时候提示,可选值:(ask | yes | no)
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            session.setConfig(sshConfig);
            // 设置登陆超时时间
            session.connect(60000);
            UpLoadFile.upLoadFile(session, sPath, dPath);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("success");
    }

    /**
     * 密匙方式登录
     * 
     * @param ip
     * @param user
     * @param port
     * @param privateKey
     * @param passphrase
     * @param sPath
     * @param dPath
     */
    public static void sshSftp2(String ip, String user, int port,
            String privateKey, String passphrase, String sPath, String dPath) {
        System.out.println("privateKey login");
        Session session = null;
        JSch jsch = new JSch();
        try {
            // 设置密钥和密码
            // 支持密钥的方式登陆,只需在jsch.getSession之前设置一下密钥的相关信息就可以了
            if (privateKey != null && !"".equals(privateKey)) {
                if (passphrase != null && "".equals(passphrase)) {
                    // 设置带口令的密钥
                    jsch.addIdentity(privateKey, passphrase);
                } else {
                    // 设置不带口令的密钥
                    jsch.addIdentity(privateKey);
                }
            }
            if (port <= 0) {
                // 连接服务器,采用默认端口
                session = jsch.getSession(user, ip);
            } else {
                // 采用指定的端口连接服务器
                session = jsch.getSession(user, ip, port);
            }
            // 如果服务器连接不上,则抛出异常
            if (session == null) {
                throw new Exception("session is null");
            }
            // 设置第一次登陆的时候提示,可选值:(ask | yes | no)
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            session.setConfig(sshConfig);
            // 设置登陆超时时间
            session.connect(300000);
            UpLoadFile.upLoadFile(session, sPath, dPath);
            System.out.println("success");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

UpLoadFile .java: 上传文件到sftp文件的具体实现类

public class UpLoadFile {
    public static void upLoadFile(Session session, String sPath, String dPath) {

        Channel channel = null;
        try {
            channel = (Channel) session.openChannel("sftp");
            channel.connect(10000000);
            ChannelSftp sftp = (ChannelSftp) channel;
            try {
                sftp.cd(dPath);
                Scanner scanner = new Scanner(System.in);
                System.out.println(dPath + ":此目录已存在,文件可能会被覆盖!是否继续y/n?");
                String next = scanner.next();
                if (!next.toLowerCase().equals("y")) {
                    return;
                }

            } catch (SftpException e) {

                sftp.mkdir(dPath);
                sftp.cd(dPath);

            }
            File file = new File(sPath);
            copyFile(sftp, file, sftp.pwd());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.disconnect();
            channel.disconnect();
        }
    }

    public static void copyFile(ChannelSftp sftp, File file, String pwd) {

        if (file.isDirectory()) {
            File[] list = file.listFiles();
            try {
                try {
                    String fileName = file.getName();
                    sftp.cd(pwd);
                    System.out.println("正在创建目录:" + sftp.pwd() + "/" + fileName);
                    sftp.mkdir(fileName);
                    System.out.println("目录创建成功:" + sftp.pwd() + "/" + fileName);
                } catch (Exception e) {
                    // TODO: handle exception
                }
                pwd = pwd + "/" + file.getName();
                try {

                    sftp.cd(file.getName());
                } catch (SftpException e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            for (int i = 0; i < list.length; i++) {
                copyFile(sftp, list[i], pwd);
            }
        } else {

            try {
                sftp.cd(pwd);

            } catch (SftpException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            System.out.println("正在复制文件:" + file.getAbsolutePath());
            InputStream instream = null;
            OutputStream outstream = null;
            try {
                outstream = sftp.put(file.getName());
                instream = new FileInputStream(file);

                byte b[] = new byte[1024];
                int n;
                try {
                    while ((n = instream.read(b)) != -1) {
                        outstream.write(b, 0, n);
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            } catch (SftpException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                try {
                    outstream.flush();
                    outstream.close();
                    instream.close();

                } catch (Exception e2) {
                    // TODO: handle exception
                    e2.printStackTrace();
                }
            }
        }
    }
}

Ftp.java 主函数,用于调起程序执行

public class Ftp {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Properties properties = LoadProperties.getProperties();
        Login.login(properties);
    }

}

properties文件中的内容,用于配置主要参数

#sftp服务器地址
ip=127.0.0.1  
user=wasadmin
pwd=wasadmin
port=22
privateKeyPath=
passphrase=
sourcePath=C://testFile
destinationPath=/sftpTest/test

MANIFEST.MF文件内容:(用于打包成Jar的文件)

Manifest-Version: 1.0
Main-Class: com.client.Ftp
Class-Path: .  lib\com.jcraft.jsch_0.1.31.jar 

注:com.jcraft.jsch_0.1.31.jar 这个jar包放在同级目录lib的下面

cmd指令文件命令:

java -jar FtpClient.jar
pause

这里写图片描述
本地和服务器创建好对应用于测试的目录后,使用eclipse将程序打包成jar包后就可以执行cmd指令文件来运行了

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值