天天看點

用腳本實作windows與linux之間檔案的傳輸用腳本實作windows與linux之間檔案的傳輸

用腳本實作windows與linux之間檔案的傳輸

需求

1.在Windows系統上的某個檔案需要傳送到Linux系統的裝置上;

2.因為自動化的要求不能人工操作,需要編寫腳本,然後在程式中調用cmd指令執行這個腳本。

下面總結一下這個需求的實作步驟。

實作

安裝WinSCP工具

因為執行腳本需要用到WinSCP.exe。這個工具擷取位址:http://download.csdn.net/detail/shufac/9581003

安裝完成之後登陸Linux主機,

用腳本實作windows與linux之間檔案的傳輸用腳本實作windows與linux之間檔案的傳輸

圖1 WinSCP登陸配置示意圖

檢視一下待傳送檔案的路徑,用于操作完成之後後面驗證。

編寫腳本

# WinSCP.exe /console /script=sample.txt
# Automatically answer all prompts negatively not to stall
# the script on errors
# option echo  on|off
option echo off
# option batch on|off|abort|continue
option batch on
# option confirm  on|off 
option confirm off
# option transfer  binary|ascii|automatic 
# option synchdelete  on|off
# option exclude clear | [;...]
# option include clear | [;...]
# open [ sftp|ftp|scp:// ][ [ :password ] @ ] [ : ]
# open user:[email protected]
# Connect   
open  scp://root:[email protected]:22
#open [scp:// ][ [ :password ] @ ] [ : ]
# Change remote directory
# cd /home/user              #遠端工作目錄
cd /tmp
# Change local directory
# set to Self's working dir 
#lcd D:\XXXXXX.bin                   #本地工作目錄
put C:\Users\Administrator\Desktop\XXXXXXXXX.bin
# Force binary mode transfer
option transfer binary
# Download file to the local directory d:\
# get examplefile.txt d:\
# option synchdelete  on|off
option synchdelete off       #是否同步删除  
# option include clear | [;...]
# option include /2008-*-*/;/2009-*-*/;/2010-*-*/;/2011-*-*/;/2012-*-*/;/2013-*-*/
# synchronize local|remote|both [ [ ] ] 
# 傳輸方式:Local為遠端至本地,remote為本地到遠端,both雙向傳輸
#使用關鍵字synchronize的話,将會同步本地目錄下的檔案至遠端目錄
#synchronize remote
remote
# Disconnect
close
# Exit WinSCP
exit
           

說明:

我這裡需要傳送的檔案隻有一個二進制檔案,是以後面不需要同步,如果需要操作整個目錄的檔案可以用synchronize remote。

執行腳本

在Windows系統中運作cmd,通過WinSCP.exe執行這個腳本即可。WinSCP預設是安裝在C:\Program Files\WinSCP目錄下的,cmd指令如下:

用腳本實作windows與linux之間檔案的傳輸用腳本實作windows與linux之間檔案的傳輸

圖2 cmd指令示意圖

結果

腳本執行過程如下圖所示,

用腳本實作windows與linux之間檔案的傳輸用腳本實作windows與linux之間檔案的傳輸

圖3  檔案傳送過程示意圖

通過WinSCP登陸Linux主機,在root/tmp目錄下可以看到傳送的那個.bin檔案,如下圖所示,

用腳本實作windows與linux之間檔案的傳輸用腳本實作windows與linux之間檔案的傳輸

圖4 檔案傳送結果示意圖

繼續閱讀