最近接到一个需求,需要在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());
两行核心代码---完活。