java 程序在windows上传输文件/目录(文件夹)到linux(centOS7)

最近接到一个需求,需要在windows上传输文件或文件夹到linux的nginx web目录中。

首先想到的是ftp,百度一下果然有现成方案。窃喜之后发现java使用“commons-net”死活上传不了文件到ntp服务器(能够与ntp建立连接)总是报超时的错误。百度上说是ntp PORT(主动模式)与PASV(被动模式)的差异。要在linux上配置对外暴露端口的范围。这不是开玩笑吗?生产服务器大批量对外暴露端口显然不行。

又看到有人用jsch来上传文件到linux。好家伙光操作类就100多行代码。我就上传个文件要这么复杂吗?又花了一个上午的时间找更快捷的方案,反复百度无果!

午饭时想到linux有个scp可以很方便的在服务器间传输文件,就阿里云的centos7而言无需多余操作直接 scp local_file remote_username@remote_ip:remote_folder 然后输入一下有写权限的用户密码就好。配了RSA类型的密钥(免密登录配置)后连密码都不用输就能进行文件传/文件夹传输了。这么好的东东windows上没有?

又百度找了一下,果然有。pscp

使用说明

使用 pscp,您可以将文件在 Windows 和 Linux之间传递。

将pscp.exe可执行文件复制到你windows机器的system32目录下。 该文件夹通常存在于 C:\Windows\System32 路径中。

pscp.exe下载地址https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html

pscp -pw yourPassword C:\Users\Admin\Desktop\test.txt  \
user@192.168.33.10:/home/vagrant

完美,在pscp命令参数中加 -r 就能传递文件夹了。

pscp参数说明如下:

C:\Users\admin>pscp
PuTTY Secure Copy client
Release 0.75
Usage: pscp [options] [user@]host:source target
       pscp [options] source [source...] [user@]host:target
       pscp [options] -ls [user@]host:filespec
Options:
  -V        print version information and exit
  -pgpfp    print PGP key fingerprints and exit
  -p        preserve file attributes
  -q        quiet, don't show statistics
  -r        copy directories recursively
  -v        show verbose messages
  -load sessname  Load settings from saved session
  -P port   connect to specified port
  -l user   connect with specified username
  -pw passw login with specified password
  -1 -2     force use of particular SSH protocol version
  -ssh -ssh-connection
            force use of particular SSH protocol variant
  -4 -6     force use of IPv4 or IPv6
  -C        enable compression
  -i key    private key file for user authentication
  -noagent  disable use of Pageant
  -agent    enable use of Pageant
  -hostkey keyid
            manually specify a host key (may be repeated)
  -batch    disable all interactive prompts
  -no-sanitise-stderr  don't strip control chars from standard error
  -proxycmd command
            use 'command' as local proxy
  -unsafe   allow server-side wildcards (DANGEROUS)
  -sftp     force use of SFTP protocol
  -scp      force use of SCP protocol
  -sshlog file
  -sshrawlog file
            log protocol details to a file
  -logoverwrite
  -logappend
            control what happens when a log file already exists

接下来java执行windows cmd命令。

Runtime rt = Runtime.getRuntime();
Process p = rt.exec("pscp -pw yourPassword C:\Users\Admin\Desktop\test.txt  \
user@192.168.33.10:/home/vagrant");
System.out.println(p.toString());

两行核心代码---完活。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值