AutoHotkey&&CuteFTPPro&&Synology_DS920+_SFTP 2022.04.12

 

  AutoHotkey&&CuteFTPPro&&Synology_DS920+_SFTP

 2022.04.12

 

AutoHotkey&&CuteFTPPro&&Synology_DS920+_SFTP  2022.04.12

AutoHotkey&&CuteFTPPro&&Synology_DS920+_SFTP  2022.04.12

 

https://www.likecs.com/show-305727625.html

 

 

Set MySite = CreateObject("CuteFTPPro.TEConnection")

MySite.Protocol = "FTP"

MySite.Host = "ftp.cuteftp.net"

MySite.Login = "username"

MySite.Password = "password"

MySite.Connect

MySite.CreateRemoteFolder("/dir") 'creates /dir (because absolute path was used)

MySite.RemoteFolder = "/dir" 'now change to the newly create 'dir' folder

MySite.CreateRemoteFolder("dir2") 'creates /dir/dir2 (because Relative path was used)


Set MySite = CreateObject("CuteFTPPro.TEConnection")

MySite.TransferURLAsync

MySite.Disconnect

MySite.RemoteFolder = "/c:/Inetpub/ftproot/Temp/Temp/"

MsgBox (MySite.RemoteFolder) 'display current remote folder

MySite.Download "agent.ini", "c:\temp\agent1.ini"




Set MySite = CreateObject("CuteFTPPro.TEConnection")

MySite.Host = "ftp.cuteftp.com"

MySite.Connect

MySite.DownloadAsync "/pub/cuteftp/english/*", "c:\temp" 'downloads all Files in the pub/cuteftp folder







;Examples
;FTPDownload("FTP",21,"ftp.someplace.com", "login", "pass", "/remoteserver/somefolder", "\\localserver\someshare", "*.txt")
; How to use variables
;loginVariable:= "loginName"
;passwordVariable:= "myPass"
;FTPDownload("SFTP", 22, "ftp.anotherplace.com", loginVariable, passwordVariable, remoteFolderVariable, localFolderVariable, "thisonefile.txt")
;
;Any parts of the functions that have default values, like 'fTransferType="AUTO"' do not have to be explicitly ;stated unless the value that is set is required to be changed.

;Downloads one or many files (if wildcards are involved), the last 2 parameters are optional.
FTPDownload(fProtocol, fPort, fHost, fLogin, fPassword, fRemote, fLocal, fFile, fTransferType="AUTO", fDataChannel="DEFAULT") {

	oFTP := ComObjCreate("CuteFTPPro.TEConnection")
	oFTP.Option("ThrowError") := false
	oFTP.Option("AutoCloseMethod") := 1
	oFTP.Option("AutoCloseDelay") := 1
	oFTP.Retries := 3
	oFTP.Delay := 5
	oFTP.Protocol := fProtocol
	oFTP.Port := fPort
	oFTP.Host := fHost
	oFTP.DataChannel := fDataChannel
	oFTP.Login := fLogin
	oFTP.Password := fPassword

	oFTP.Connect

	oFTP.TransferType := fTransferType
	oFTP.RemoteFolder := fRemote
	oFTP.LocalFolder := fLocal
	oFTP.Download(fFile)

	oFTP.Close
	oFTP = ""
	ObjRelease(oFTP)
	Process,WaitClose,ftpte.exe
}

;Downloads a file and saves it as another name
FTPDownloadRename(fProtocol, fPort, fHost, fLogin, fPassword, fRemote, fLocal, fRemoteFile, fLocalFile, fTransferType="AUTO", fDataChannel="DEFAULT") {

	oFTP := ComObjCreate("CuteFTPPro.TEConnection")
	oFTP.Option("ThrowError") := false
	oFTP.Option("AutoCloseMethod") := 1
	oFTP.Option("AutoCloseDelay") := 1
	oFTP.Retries := 3
	oFTP.Delay := 5
	oFTP.Protocol := fProtocol
	oFTP.Port := fPort
	oFTP.Host := fHost
	oFTP.DataChannel := fDataChannel
	oFTP.Login := fLogin
	oFTP.Password := fPassword

	oFTP.Connect

	while !oFTP.IsConnected {
		Sleep 1000
}

oFTP.TransferType := fTransferType
oFTP.RemoteFolder := fRemote
oFTP.LocalFolder := fLocal
oFTP.Download(fRemoteFile,fLocalFile)

oFTP.Close
oFTP = ""
ObjRelease(oFTP)
Process,WaitClose,ftpte.exe
}

;Download up to 3 distinct separate files, can be altered to suit needs
FTPDownloadMulti(fProtocol, fPort, fHost, fLogin, fPassword, fRemote, fLocal, fFile1, fFile2, fFile3, fTransferyType="AUTO", fDataChannel="DEFAULT") {
	oFTP := ComObjCreate("CuteFTPPro.TEConnection")
	oFTP.Option("ThrowError") := false
	oFTP.Option("AutoCloseMethod") := 1
	oFTP.Option("AutoCloseDelay") := 1
	oFTP.Retries := 3
	oFTP.Delay := 5
	oFTP.Protocol := fProtocol
	oFTP.Port := fPort
	oFTP.Host := fHost
	oFTP.DataChannel := fDataChannel
	oFTP.Login := fLogin
	oFTP.Password := fPassword

	oFTP.Connect

	while !oFTP.IsConnected {
		Sleep 1000
}

oFTP.TransferType := fTransferType
oFTP.RemoteFolder := fRemote
oFTP.LocalFolder := fLocal
oFTP.Download(fFile)

oFTP.TransferType := fTransferType
oFTP.RemoteFolder := fRemote
oFTP.LocalFolder := fLocal
oFTP.Download(fFile2)

oFTP.TransferType := fTransferType
oFTP.RemoteFolder := fRemote
oFTP.LocalFolder := fLocal
oFTP.Download(fFile3)

oFTP.Close
oFTP = ""
ObjRelease(oFTP)
Process,WaitClose,ftpte.exe
}

FTPUpload(fProtocol, fPort, fHost, fLogin, fPassword, fRemote, fLocal, fFile, fTransferType="AUTO", fDataChannel="DEFAULT") {
	oFTP := ComObjCreate("CuteFTPPro.TEConnection")
	oFTP.Option("ThrowError") := false
	oFTP.Option("AutoCloseMethod") := 1
	oFTP.Option("AutoCloseDelay") := 1
	oFTP.Retries := 3
	oFTP.Delay := 5
	oFTP.Protocol := fProtocol
	oFTP.Port := fPort
	oFTP.Host := fHost
	oFTP.DataChannel := fDataChannel
	oFTP.Login := fLogin
	oFTP.Password := fPassword

	oFTP.Connect

	while !oFTP.IsConnected {
		Sleep 1000
}

oFTP.TransferType := fTransferType
oFTP.RemoteFolder := fRemote
oFTP.LocalFolder := fLocal

oFTP.Upload(fFile)

oFTP.Close
oFTP = ""
ObjRelease(oFTP)
Process,WaitClose,ftpte.exe
}

FTPDelete(fProtocol, fPort, fHost, fLogin, fPassword, fRemote, fFile, fDataChannel="DEFAULT") {
	oFTP := ComObjCreate("CuteFTPPro.TEConnection")
	oFTP.Option("ThrowError") := false
	oFTP.Option("AutoCloseMethod") := 1
	oFTP.Option("AutoCloseDelay") := 1
	oFTP.Retries := 3
	oFTP.Delay := 5
	oFTP.Protocol := fProtocol
	oFTP.Port := fPort
	oFTP.Host := fHost
	oFTP.DataChannel := fDataChannel
	oFTP.Login := fLogin
	oFTP.Password := fPassword

	oFTP.Connect

	while !oFTP.IsConnected {
		Sleep 1000
}
oFTP.RemoteFolder := fRemote
oFTP.RemoteRemove(fFile)

oFTP.Close
oFTP = ""
ObjRelease(oFTP)
Process,WaitClose,ftpte.exe
}

FTPCheckExists(fProtocol, fPort, fHost, fLogin, fPassword, fRemote, fFile, fTransferType="AUTO", fDataChannel="DEFAULT") {

	oFTP := ComObjCreate("CuteFTPPro.TEConnection")
	oFTP.Option("ThrowError") := false
	oFTP.Option("AutoCloseMethod") := 1
	oFTP.Option("AutoCloseDelay") := 1
	oFTP.Retries := 3
	oFTP.Delay := 5
	oFTP.Protocol := fProtocol
	oFTP.Port := fPort
	oFTP.Host := fHost
	oFTP.DataChannel := fDataChannel
	oFTP.Login := fLogin
	oFTP.Password := fPassword

	oFTP.Connect

	while !oFTP.IsConnected {
		Sleep 1000
}

oFTP.TransferType := fTransferType
oFTP.RemoteFolder := fRemote
FileExists := oFTP.RemoteExists(fFile)

oFTP.Close
oFTP = ""
ObjRelease(oFTP)
Process,WaitClose,ftpte.exe
return FileExists
}






















Function cuteftp_Upload(Dir,Filename,ToDir)
Dim MySite
Dim strFileList
Dim strFileName
Dim i, j
Dim objFSO, objFolder, objFile

Set MySite = CreateObject("CuteFTPPro.TEConnection")

MySite.Option("ThrowError") = false

MySite.Host = "FTP服务器IP"
MySite.Protocol = "SFTP" '链接模式
MySite.Port = ftp端口
MySite.Retries = 30
MySite.Delay = 30
MySite.MaxConnections = 1
MySite.TransferType = "AUTO"
MySite.DataChannel = "default"
MySite.AutoRename = "OFF"
MySite.FileOverWriteMethod = "OVERWRITE"

MySite.Login = "账号名"
MySite.Password = "密码"
MySite.SocksInfo = ""
MySite.ProxyInfo = ""

if CBool(MySite.Connect) Then
	MySite.RemoteFilterInclude = ""
MySite.RemoteFilterExclude = ""
MySite.RemoteSiteFilter = ""

MySite.RemoteFolder = ToDir
MySite.LocalFolder = Dir
if CBool(MySite.RemoteExists(MySite.RemoteFolder)) Then
	if CBool(MySite.LocalExists(MySite.LocalFolder)) Then
		MySite.Upload Filename
cuteftp_Upload = "OK"
Set objFolder = nothing
Set objFSO = nothing
else
	cuteftp_Upload = "错误! 本地上载目录不存在"
MsgBox "错误! 本地上载目录不存在"
End If
else
	cuteftp_Upload = "错误! 远程上载目录不存在"
MsgBox "错误! 远程上载目录不存在"
End If
else
	cuteftp_Upload = "错误! " & MySite.ErrorDescription
MsgBox "错误! " & MySite.ErrorDescription
End If
MySite.Disconnect
End Function





主程序:

	'运行程序初始配置
	cuteftpfile = "cuteftp.vbs"
	configfile = "配置文件.confing"
	IfinD_src = "xxx.exe"
	EMFunc_src = "yyy.xla"
	log_file = "update.log"
	'On Error Resume Next '忽略所有错误
	'关闭EXCEL进程

	Set fs_log = CreateObject("Scripting.FileSystemObject")
	if fs_log.fileExists(log_file) = false Then
		Set flog = fs_log.CreateTextFile(log_file, false)
	else
		Set flog = fs_log.opentextfile(log_file, 8)
	End If
	Set fso1 = CreateObject("Scripting.FileSystemObject")
	if fso1.fileExists(cuteftpfile) = false Then
		MsgBox "cuteftpfile文件不存在,请重新配置"
	wscript.quit
	End If
	if fso1.fileExists(configfile) = false Then
		MsgBox "configfile文件不存在,请重新配置"
	wscript.quit
	End If
	if fso1.fileExists(IfinD_src) = false Then
		MsgBox "xxx路径配置错误,请重新配置"
	wscript.quit
	End If
	if fso1.fileExists(EMFunc_src) = false Then
		MsgBox "yyy.xla路径配置错误,请重新配置"
	wscript.quit
	End If

	opentext = fso1.opentextfile("cuteftp.vbs", 1).readall
	ExecuteGlobal opentext
	Set fso1 = Nothing

	MsgBox "请确定excel都已关闭!,点击确定后将强制关闭所有EXCEL进程!"
	strComputer ="."
	Set objWMIService = GetObject("winmgmts://" & strComputer & "/root/cimv2")
	Set colProcess = objWMIService.ExecQuery("Select * from Win32_PerfFormattedData_PerfProc_Process",,48)
	For Each objItem in colProcess
		if objItem.Name = "EXCEL" then
			'MsgBox "准备关闭"
	CreateObject("WScript.Shell").Run "taskkill /f /im EXCEL.EXE", 0
	end If
	Next
	Wscript.Sleep 3000


	Dim WshShell
	set WshShell = CreateObject("WScript.Shell")
	Dim oExcel
	Set oExcel= CreateObject("Excel.Application")
	oExcel.DisplayAlerts = false
	oExcel.visible = true
	sPath = createobject("Scripting.FileSystemObject").GetFolder(".").Path
	Set fso = CreateObject("Scripting.FileSystemObject")
	Set file = fso.OpenTextFile(configfile,1, false)

	DO while file.AtEndOfStream <> true
	conf_line = cstr(file.ReadLine)
	'MsgBox str
	if len(conf_line) > 3 Then
		arr = Split(conf_line,",")
	if arr(0) = "txt_file_up" Then
		cuteftp_Upload sPath,arr(1),arr(2)
	flog.WriteLine cstr(date) & " " & cstr(time) & "|" & cstr(arr(1)) & ",成功上传至" & arr(2)
	Wscript.Sleep 30000
	else
		file_path = arr(0)& "/" &arr(1)
	rowcount_before = 0
	rowcount_after = 0
	if Right(file_path,4) = "xlsx" Then
		'IfinD_check(IfinD_src)
	oExcel.Workbooks.Open file_path,3,false
	rowcount_before = oExcel.ActiveSheet.UsedRange.Rows.Count
	'MsgBox rowcount_before
	Wscript.Sleep 3000
	WshShell.Run(EMFunc_src),1,false
	Wscript.Sleep 10000
	oExcel.ActiveWorkBook.Save
	Wscript.Sleep 3000
	rowcount_after = oExcel.ActiveSheet.UsedRange.Rows.Count
	'MsgBox rowcount_after
	oExcel.WorkBooks.Close
	Wscript.Sleep 3000
	'MsgBox rowcount_after-rowcount_before
	addcount = rowcount_after - rowcount_before
	'If addcount > 0 then
	cuteftp_Upload arr(0),arr(1),arr(2)
	flog.WriteLine cstr(date) & " " & cstr(time) & "|" & file_path & ",成功上传至" & arr(2) &",新增" & cstr(addcount) & "行数据," & "总行数为" & cstr(rowcount_before)
	'Else
	' flog.WriteLine cstr(date) & " " & cstr(time) & "|" & file_path & ",未更新,总行数为" & cstr(rowcount_before) & ",无新数据更新."
	'End If
	End If
	End IF
	End If
	loop
		flog.WriteLine cstr(date) & " " & cstr(time) & "|" & "完成" & configfile & "配置文件中对应Excel更新."
	set flog = Nothing
	Set fso = Nothing
	oExcel.Quit
	Wscript.Sleep 1000
	MsgBox "完成" & configfile & "配置文件中对应Excel更新."


	Function IfinD_check(IfinD_src)
	strComputer ="."
	Set objWMIService = GetObject("winmgmts://" & strComputer & "/root/cimv2")
	Set colProcess = objWMIService.ExecQuery("Select * from Win32_PerfFormattedData_PerfProc_Process",,48)

	DIM isIfinD
	isIfinD = 0
	For Each objItem in colProcess
		if objItem.Name = "xxx" then
			isIfinD = 1
	end If
	Next

	if isIfinD <>1 then
		WshShell.Run(xxx),1,false
	Wscript.Sleep 5000
	WshShell.SendKeys "{Enter}"
	Wscript.Sleep 5000
	End If
	End Function











用VB6基于Cuteftp的传输引擎作了个东东,已能实现文件的上传,代码如下:

Set MySite = CreateObject("CuteFTPPro.TEConnection")
MySite.Protocol = "FTP"
MySite.Host = FTPServerIP
MySite.Login = FTPServerUser
MySite.Password = FTPServerPass
MySite.Connect
MySite.RemoteFolder = "download"
MySite.Upload cd.FileName
Label7.Caption = "进度: " & MySite.TransferredSize & "/" & MySite.TotalSize & ", 速度: " & MySite.Speed & ", 已用时: " & MySite.TimeElapsed & ", 已用时: " & MySite.TimeLeft MySite.RemoteRename "/download/" & cd.FileTitle, "/download/" & alltrim(cd.FileTitle)
MySite.Disconnect
但有一问题,上述红色代码是将传输过程中的各类进度信息显示出来,按上述代码,就只能上传完后才显示进度信息,能否实现上传过程中实时显示进度信息呢?也就说现在是要等MySite.Upload cd.FileName这个方法执行完上传操作后才能显示进度信息,能否实现在MySite.Upload cd.FileName方法开始执行时就能实时获取label7所赋的各属性。







'This default template script is in VBScript. You can write scripts in your language of choice and save them with the proper extension, or use your an editor specific to that language.

'See the TESDK help file for more details on how the scripting feature works and for information on each supported method and property.

'You must have Windows Scripting Host installed for the COM enabled engine to work. Run the Transfer Engine once to register it (as a COM object) on the target system.

'If you're having problems with running scripts while not logged in, or when trying to run them using MS scheduler, refer to our online knowledgebase for help (http://www.globalscape.com/support)

'Look into c:\temp folder to observe local activity (for testing purposes) or right click on the Transfer Engine icon in the systray and select "show current transfers"

'This sample script performs an anonymous login to ftp://ftp.globalscape.net

   'First declare a variable called Mysite. This will hold the reference to the TE COM object.

   Dim MySite

   'Create a connection object and assign it to the variable

   Set MySite = CreateObject("CuteFTPPro.TEConnection")
	
   ' Now set each property for the site connection 
   ' You can omit this section to use the default values, but you should at least specify the Host
   'The default Protocol is FTP, however SFTP (SSH2), FTPS (SSL), HTTP, and HTTPS can also be used)

   MySite.Protocol = "FTP"
   MySite.Host = "ftp.globalscape.com"

   'following lines are optional since the default is anonymous if no login and password are defined

   MySite.Login = "anonymous"
   MySite.Password = "user@user.com"

   'if necessary, use the UseProxy method and ProxyInfo or SocksInfo properties to connect through a proxy server

   MySite.UseProxy = "BOTH"

   'now connect to the site (also called called implicitly when most remote methods are called)

   MySite.Connect

	
   'perform some logic to verify that the connection was made successfully

   If (Not Cbool(MySite.IsConnected)) Then	
      MsgBox "Could not connect to: " & MySite.Host & "!"
      Quit(1)
   End If

   'The script will now check to see if the local folder c:\temp exists and will create it if necessary

   If (Not (MySite.LocalExists("c:\temp"))) Then
      MySite.CreateLocalFolder "c:\temp"
   End If

   'Change TE's local working folder to to c:\temp
   MySite.LocalFolder = "c:\temp"

   'Check for existence of remote folder "/pub/cuteftp"
   b = MySite.RemoteExists("/pub/cuteftp/")

   If (Not CBool(b)) Then
      'Verify existence of remote folder
      MsgBox "Remote folder not found!. Please make sure that the Pub folder exists on the remote site"
      Quit(1)
   End If

   'Now download the index file to the local destination folder
   MySite.Download "/pub/cuteftp/index.txt"

   'Complete.  Show the status of this transfer.
   MsgBox "Task done, final status is '" + MySite.Status + "'"

  MySite.Disconnect
  MySite.Close

'End of sample script. You can save you script and then run it by either selecting it from the Tools > Run Script menu or by double clicking on the script file in Windows






CuteFTP上传脚本(VBS)
2013年08月29日 ⁄ 综合 ⁄ 共 3716字 ⁄ 字号 小 中 大 ⁄ 评论关闭
Option Explicit    ' 强制显式声明变量。

'********************************************************************
'* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-
'* CuteFTP Pro Script
'* -=-=-=-=-=-=-=-=-=-=-=-=-=-=-
'*
'* 作者:张博
'*
'CuteFTP脚本(VBScript),上传到多个服务器
'必须首先安装CuteFTP软件的较新版本(早期版本存在严重BUG,6.0版没有问题)
'运行脚本时可能需要首先关闭CuteFTP窗口(某些版本有此问题)
'需要配置的内容:
'变量appname 应用的名字,脚本执行过程中会显示
'变量LocalDir 用作中转的本地绝对路径,若不存在会自动创建
'数组RemoteInfo 目标服务器的信息,包括域名(IP)、用户、口令、基本路径
'对象MySite MySite2 的各项属性,连接源FTP和目标FTP的CuteFTP对象,需要配置站点域名或IP、用户名、口令
'数组JobInfo 要传输的文件的相对路径和文件名
'   相对路径可以为""或多级目录"dir1/dir2"
'   文件名可以带通配符,带通配符可能会连子目录一起操作,UNIX机要区分大小写
'执行时第一次提示任务名称,第二次提示要执行的任务(此时可以取消任务),确定后实际执行任务,最后提示任务完成

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'通用函数
'改变本地工作路径
Function lChangeDir(varTE,vardir)
 If ""=vardir Then Exit Function
    If (Not (varTE.LocalExists(vardir))) Then
        varTE.CreateLocalFolder vardir
    End If
    varTE.LocalFolder = vardir
End Function
'改变远程工作路径
Function rChangeDir(varTE,vardir)
 Dim b
 If ""=vardir Then Exit Function
    b = varTE.RemoteExists(vardir)
    If (Not Cbool(b)) Then
        varTE.CreateRemoteFolder vardir
    End If
    varTE.RemoteFolder = vardir
End Function
'同时改变本地和远程工作路径
Function lrChangeDir(varTE,lbasedir,rbasedir,lrdir)
 lChangeDir varTE , lbasedir
 lChangeDir varTE , lrdir
 'varTE.RemoteCommand "CD"
 rChangeDir varTE , rbasedir
 rChangeDir varTE , lrdir
End Function

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'属于特定应用的函数
Function AddRemoteInfo(infoarray,host,login,pass,basedir)
 if infoarray(0,0) >= UBound(infoarray) then
  MsgBox "AddRemoteInfo : array fulled"
  Quit 1
 End If
 infoarray(0,0) = infoarray(0,0) + 1
 
 infoarray(infoarray(0,0),0)=host
 infoarray(infoarray(0,0),1)=login
 infoarray(infoarray(0,0),2)=pass
 infoarray(infoarray(0,0),3)=basedir
End Function
Function AddJobInfo(infoarray,reldir,file)
 if infoarray(0,0) >= UBound(infoarray) then
  MsgBox "AddRemoteInfo : array fulled"
  Quit 1
 End If
 infoarray(0,0) = infoarray(0,0) + 1
 
 infoarray(infoarray(0,0),0)=reldir
 infoarray(infoarray(0,0),1)=file
End Function
Function InitTEObj(teobj,infoarray,i)
 teobj.Protocol = "FTP"
    teobj.Host = infoarray(i,0)
    teobj.Login = infoarray(i,1)
    teobj.Password = infoarray(i,2)
    teobj.UseProxy = "OFF"
    teobj.MaxConnections = 5
    teobj.TransferType = "ASCII"
End Function

 Dim appname '应用名称
 Dim report '报告
 Dim i,j '通用循环变量
 appname = "省集中 文件发布"
 report = ""
 MsgBox "CuteFTP pro VBS 脚本 启动 - " & appname

    Dim MySite 'FTP站点
    Dim LocalDir '本地基本路径 必须是绝对路径
    '创建CuteFtp 对象
    Set MySite = CreateObject("CuteFTPPro.TEConnection")
 
 '下标0用于记录有效数据的个数
 Dim RemoteInfo(100,3) '数组下标基于0并且定义的是最大下标,因此可用的为(0-100,0-3)
      '第二维依次为主机名、登录名、口令、基础路径,不使用第一维的0
 Dim JobInfo(100,1) '不使用第一维的0,第二维依次为相对路径、文件名
 RemoteInfo(0,0)=0
 JobInfo(0,0)=0
 
 '本地基本路径
 LocalDir="本地根目录" '必须是绝对路径
 
 '站点信息,只能添加一个远程站点,添加多个未经测试
 AddRemoteInfo RemoteInfo,"ip地址","用户名","密码","远程根目录"

 

 '任务信息
 'AddJobInfo JobInfo,"相对路径","文件名,可带通配符,递归的"
'AddJobInfo JobInfo,"相对路径","文件名,可带通配符"
'AddJobInfo JobInfo,"相对路径","文件名,可带通配符"
'AddJobInfo JobInfo,"相对路径","文件名,可带通配符"

 report = "即将执行下列任务:" & Chr(13) & Chr(10)
 For i=1 To JobInfo(0,0)
  report = report & Chr(13) & Chr(10) & JobInfo(i,0) & " - " & JobInfo(i,1)
 Next
 report = report & Chr(13) & Chr(10) & Chr(13) & Chr(10) & "本地路径: " & Chr(13) & Chr(10) & LocalDir
 report = report & Chr(13) & Chr(10) & "目的: "
 For i=1 To RemoteInfo(0,0)
  report = report & Chr(13) & Chr(10) & RemoteInfo(i,0) & ":" & RemoteInfo(i,3)
 Next
 If vbCancel = MsgBox(report,vbOKCancel) Then
  Quit 1
 End If

 report = ""
 For i=1 To RemoteInfo(0,0)
  InitTEObj MySite,RemoteInfo,i
  '连接到站点
  MySite.Connect
  If (Not Cbool(MySite.IsConnected)) Then 
   MsgBox "Could not connect to: " & MySite.Host & " Aborting!" &MySite.ErrorDescription
   Quit(1)
  End If
  
  For j=1 To JobInfo(0,0)
   lrChangeDir MySite,LocalDir,RemoteInfo(i,3),JobInfo(j,0)
   MySite.Upload JobInfo(j,1)
  Next
  '关闭连接
     MySite.Close
     report = report & Chr(13) & Chr(10) & RemoteInfo(i,0)
 Next
 
 MsgBox "CuteFTP pro VBS 脚本 结束 - " & appname & Chr(13) & Chr(10) & report











使用VBS对CuteFTP进行二次开发
Roger Yang

近日,需要编写一个FTP客户端程序,用于定时同步本地和远端的下载和上传目录。虽说原来使用BCB开发过FTP客户端程序。但这次时间紧,而且,日后须由不熟悉BCB的开发人员来维护源码。所以,想利用现有FTP客户端软件的功能来实现需求。

起初,试用了SMARTFTP,基本能满足下载和上传得需求,而且能通过计划任务功能实现定时效果。但不足之处是自定义上还不够灵活,不能对整个处理流程进行随意控制。

    之后,试用了老牌ftp客户端软件cuteFTP(我使用的版本是CuteFTP 6.0 Professinal)。果然,姜还是老的辣,CuteFTP内置的Transfer Engine,使它从一个FTP客户端软件升级为一个开发平台。



 

 

 

What is the Transfer Engine?


Built on a modular design platform, CuteFTP 6 Professional's FTP Transfer Engine (TE) is completely independent of the main application's interface. You can control the TE through an industry standard COM (Component Object Model) interface using your favorite programming or scripting language, such as Visual Basic, Perl, ASP or JavaScript.



 

 

 

需要了解更多有关Transfer Engine的信息,可以访问CuteFTP的在线知识库


http://help.globalscape.com/help/cuteftppro6/



 

 

 

    我使用VBScript来编写TE的控制代码,不仅能实现上传下载的需求,还能把日志等信息写入数据库或本地文件。


准备过程中参考了如下的信息:


a)       TE的方法:
    http://help.globalscape.com/help/cuteftppro6/finding_a_method_by_category.htm


b)       TE的属性:
    http://help.globalscape.com/help/cuteftppro6/finding_a_property_by_category.htm

c)       VBS的数据库操作类:
    http://dev.csdn.net/article/31/31454.shtm

d)       VBS 函数与对象:
    http://rivuletblog.blogchina.com/1598901.html

e)       遍历一个文件夹里的文件:
    http://www.yingku.com/info/187.htm

f)       用 FileSystemObject 访问文件:
    http://msdn.microsoft.com/library/chs/default.asp?url=/library/CHS/vbcn7/html/vbconintroductiontofilesystemobjectmodel.asp

g)       FileSystemObject 示例代码:
    http://www.clde.net/Document/VBS/page/2005819/VBS_2005819164447.shtml


通过使用Windows计划任务来执行脚本,就能够实现定时的功能。具体的设置方法可以参考如下连接:

http://help.globalscape.com/help/cuteftppro7/running_scripts_from_the_windows_scheduled_tasks_folder.htm



   使用WinXP的计划任务来实现定时运行脚本的功能,实现方法如下:
   To schedule a task

1.       In Windows, click Start.

2.       Choose Programs > Accessories > System Tools > Scheduled Tasks.

3.       Double-click Add Scheduled Task. The Scheduled Task Wizard appears.

4.       Click Next.

5.       Click Browse. The Select Program to Schedule window appears.

6.       Select your script and click Open. You are returned to the Scheduled Task Wizard.

7.       Choose how often to run the script and click Next.

8.       Select a starting time, recurrence, and starting date and click Next.

9.       Enter a user name and password for the account that will run the script, and click Next.

10.    Click Finish.


1.       In Windows, click Start.

2.       Choose Programs > Accessories > System Tools > Scheduled Tasks.

3.       Double-click Add Scheduled Task. The Scheduled Task Wizard appears.

4.       Click Next.

5.       Click Browse. The Select Program to Schedule window appears.

6.       Select your script and click Open. You are returned to the Scheduled Task Wizard.

7.       Choose how often to run the script and click Next.

8.       Select a starting time, recurrence, and starting date and click Next.

9.       Enter a user name and password for the account that will run the script, and click Next.

10.    Click Finish.


   使用WinXP的计划任务来实现定时运行脚本的功能,实现方法如下:
   To schedule a task

1.       In Windows, click Start.

2.       Choose Programs > Accessories > System Tools > Scheduled Tasks.

3.       Double-click Add Scheduled Task. The Scheduled Task Wizard appears.

4.       Click Next.

5.       Click Browse. The Select Program to Schedule window appears.

6.       Select your script and click Open. You are returned to the Scheduled Task Wizard.

7.       Choose how often to run the script and click Next.

8.       Select a starting time, recurrence, and starting date and click Next.

9.       Enter a user name and password for the account that will run the script, and click Next.

10.    Click Finish.


1.       In Windows, click Start.

2.       Choose Programs > Accessories > System Tools > Scheduled Tasks.

3.       Double-click Add Scheduled Task. The Scheduled Task Wizard appears.

4.       Click Next.

5.       Click Browse. The Select Program to Schedule window appears.

6.       Select your script and click Open. You are returned to the Scheduled Task Wizard.

7.       Choose how often to run the script and click Next.

8.       Select a starting time, recurrence, and starting date and click Next.

9.       Enter a user name and password for the account that will run the script, and click Next.

10.    Click Finish.

 

实现代码如下:



' -----------------------------------------------------------------------------
'   下载远程目录下的所有文件,并删除远端已下载的文件
'   上载本地目录下的所有文件,并删除本地已上传的文件
'  
'   把错误日志写入数据库的方式未定
'   过滤器的处理方式未定
'   文件已存在时的处理策略未定
'
'   Edit History:
'
'       2005/09/01 - Created by RogerYang.
'
' -----------------------------------------------------------------------------

Dim MySite

Dim strFileList     '文件列表
Dim strFileName     '文件名
Dim i, j

Dim objFSO, objFolder, objFile

Dim objConn         ' 数据库连接

' Create TEConnection object
Set MySite = CreateObject("CuteFTPPro.TEConnection")

'disable ATL exceptions
MySite.Option("ThrowError") = false

' Initialize remote server host name, protocol, port, etc.
MySite.Host = "172.16.11.129"
MySite.Protocol = "FTP"
MySite.Port = 21
MySite.Retries = 30
MySite.Delay = 30
MySite.MaxConnections = 2
MySite.TransferType = "AUTO"
MySite.DataChannel = "DEFAULT"
MySite.AutoRename = "OFF"

' WARNING!!! SENSITIVE DATA: user name and password.
MySite.Login = "yang"
MySite.Password = "123456"
MySite.SocksInfo = ""
MySite.ProxyInfo = ""

' Connect to remote server
If CBool(MySite.Connect) Then

    ' 设置远程包含过滤器
    MySite.RemoteFilterInclude = ""
    ' 设置远程排斥过滤器
    MySite.RemoteFilterExclude = ""
    MySite.RemoteSiteFilter = ""

    ' -----------------------------------------------------------------------------
    ' 下载
    ' -----------------------------------------------------------------------------
    ' 设置远程下载目录和本地下载目录
    MySite.RemoteFolder = "/e:/private/download"
    MySite.LocalFolder = "D:/ftpdown/download"
   
    ' 判断远程下载目录是否存在
    If CBool(MySite.RemoteExists(MySite.RemoteFolder)) Then
       
        ' 判断本地下载目录是否存在
        If CBool(MySite.LocalExists(MySite.LocalFolder)) Then

            ' 获取远程下载目录的文件列表,以"|||"作为分隔符
            MySite.GetList "", "", "%NAME|||"
            strFileList = MySite.GetResult

            '  判断远程下载目录中是否有文件
            If Len(strFileList) <> 0 Then
                ' 远程下载目录中有文件,进行下载操作

                'MsgBox strFileList

                ' 通过循环,下载并删除全部文件
                i = 1
                Do While true

                    j = InStr(i, strFileList, "|||")

                    'MsgBox "i=[" & i & "]"
                    'MsgBox "j=[" & j & "]"

                    If j <= 0 Then
                        ' 从文件列表中获取文件名完毕,退出循环
                        Exit Do
                    End If

                    ' 从文件列表中得到文件名
                    strFileName = Mid(strFileList, i, j - i)

                    'MsgBox "strFileName=[" & strFileName & "]"

                    ' 下载指定文件
                    MySite.Download strFileName

                    ' 从服务器上删除指定文件
                    MySite.RemoteRemove strFileName

                    ' 加5,因为分隔符"|||"的长度为3个字符,另外还有回车和换行2个字符
                    i = j + 5

                Loop

            Else
                ' 远程下载目录中没有文件

            End If

        Else
            ' 本地下载目录不存在
            MsgBox "错误! 本地下载目录不存在"
        End If
       
    Else
        ' 远程下载目录不存在
        MsgBox "错误! 远程下载目录不存在"
    End If

    ' -----------------------------------------------------------------------------
    ' 上传
    ' -----------------------------------------------------------------------------
    ' 设置远程上传目录和本地上传目录
    MySite.RemoteFolder = "/e:/private/upload"
    MySite.LocalFolder = "D:/ftpdown/upload"

    ' 判断远程上载目录是否存在
    If CBool(MySite.RemoteExists(MySite.RemoteFolder)) Then

        ' 判断本地上载目录是否存在
        If CBool(MySite.LocalExists(MySite.LocalFolder)) Then

            Set objFSO = CreateObject("Scripting.FileSystemObject")
            Set objFolder = objFSO.GetFolder(MySite.LocalFolder)
       
            '通过循环,上载并删除全部文件
            For Each objFile in objFolder.Files
       
                'MsgBox objFile.Name
       
                ' 上载文件
                MySite.Upload objFile.Name
       
                ' 文件上载之后,就删除
                objFile.Delete
            Next
       
            Set objFolder = nothing
            Set objFSO = nothing        ' 释放FileSystemObject对象实例内存空间
        Else
            ' 本地上载目录不存在
            MsgBox "错误! 本地上载目录不存在"
        End If
       
    Else
        ' 远程上载目录不存在
        MsgBox "错误! 远程上载目录不存在"
    End If

    ' 使用如下代码可以进行数据库操作,从而把日志等信息存入数据库。
    'Set objConn = CreateObject("ADODB.Connection")
    'objConn.Open "Driver={sql server};server=172.16.11.134;database=yang;uid=sa;pwd=123456;"
    'objConn.Execute "INSERT INTO error_log(error_date,error_log) VALUES('aaa','bbb')"
    '
    'Set objConn = nothing

    ' 使用如下代码可以进行文件操作,从而把日志等信息存入本地文件。
    'Set FSO = CreateObject("Scripting.FileSystemObject")
    'Set TextStream = FSO.CreateTextFile("C:/ftptest.txt")
    'TextStream.WriteLine("FTP TEST")
    'TextStream.Close
Else
    ' 与FTP服务器连接失败
    MsgBox "错误! " & MySite.ErrorDescription
End If

MySite.Disconnect













Set MySite = CreateObject("CuteFTPPro.TEConnection")
MySite.Host = "test.com"
MySite.Protocol = "SFTP"
MySite.Port = 22
MySite.Retries = 30
MySite.Delay = 30
MySite.MaxConnections = 4
MySite.TransferType = "AUTO"
MySite.DataChannel = "DEFAULT"
MySite.AutoRename = "OFF"
MySite.Login = "test"
MySite.Password = "test"
MySite.SocksInfo = ""
MySite.ProxyInfo = ""
MySite.Connect
MySite.Upload "C:\test\test.csv", "/incoming/testOrders/test.csv"
MySite.Download "/incoming/testOrders/test.csv", "C:\test\test.csv2"
MySite.Disconnect
MySite.Close
Everything is working fine and files are also transferred properly.

Only thing the client is telling us is that the connection to their SFTP server is left open after the file transfer. But you can see in the scripts above that I am disconnecting and closing the connection here. Am I missing anything here?
















示例代码主要通过VBScript实现对SFTP的上传下载功能

' Return yyyyMM base on current date
Function FormatCurrentDate()
    CurrentDate = Formatdatetime(Date,2)
    FormatCurrentDate = right("0000" & year(CurrentDate),4) & right("00" & month(CurrentDate),2)
End Function

' Upload and Backup files in given folder
Sub UploadAndBackupFiles(MySite,fs,outFile,localFolder,bakLocalFolder)
    Dim oFolder,oFiles, fileName
    set oFolder = fs.GetFolder(localFolder)
    set oFiles = oFolder.Files 
    for each file in oFiles
        fileName = file.Name  
        
        ' Check bak folder, if not exist, then create it
        If(Not(MySite.LocalExists(bakLocalFolder))) Then
            MySite.CreateLocalFolder bakLocalFolder
        End If
        
        If(MySite.LocalExists(localFolder & fileName)) Then
            ' Upload file
            If(Not(MySite.RemoteExists("/inbound/" & fileName))) Then
                outFile.WriteLine FormatDateTime(Now()) & ": [UPLOAD] " & fileName
                MySite.Upload localFolder & fileName, "/inbound/" & fileName
            End If
            ' Backup file to bak folder
            outFile.WriteLine FormatDateTime(Now()) & ": [BACKUP] " & fileName
            MySite.LocalRename localFolder & fileName, bakLocalFolder & fileName
        End If
    Next
End Sub

' Download files from remote SFTP
Sub DownloadFilesFromSFTP(MySite,outFile,localFolder,remoteFolder)
    Dim strFileList,strFileName,i,j
    MySite.LocalFolder = localFolder
    MySite.RemoteFolder = remoteFolder
    If CBool(MySite.RemoteExists(MySite.RemoteFolder)) Then
         If CBool(MySite.LocalExists(MySite.LocalFolder)) Then
             ' 获取远程下载目录的文件列表,以"|||"作为分隔符
             MySite.GetList "", "", "%NAME|||"
             strFileList = MySite.GetResult
             If Len(strFileList) <> 0 Then
                 i = 1
                Do While true
                    j = InStr(i, strFileList, "|||")
                    If j <= 0 Then
                        Exit Do
                    End If
                    strFileName = Mid(strFileList, i, j - i)
                    outFile.WriteLine FormatDateTime(Now()) & ": [DOWNLOAD] " & strFileName
                    MySite.Download strFileName
                    outFile.WriteLine FormatDateTime(Now()) & ": [*REMOVE*] " & strFileName
                    MySite.RemoteRemove strFileName
                    '加5,因为分隔符"|||"的长度为3个字符,另外还有回车和换行2个字符
                    i = j + 5
                 Loop
            Else
                outFile.WriteLine "Message! There is no file in remote sftp"
            End If
        Else
            outFile.WriteLine "Error! Local directory doesn't existing"
        End If
    Else
        outFile.WriteLine "Error! Remote directory doesn't existing"
    End If      
End Sub

Dim MySite, fos, outFile

On Error Resume Next

Set fos = WScript.CreateObject("scripting.filesystemobject")
Set outFile = fos.OpenTextFile("\\10.7.11.103\cusdec_edi\Schedule\VBS_CUSDEC_Log.txt", 8, True)

outFile.WriteLine "=========================================================================================="
outFile.WriteLine "Start Time: " & FormatDateTime(Now())

' Create TEConnection object
Set MySite = CreateObject("CuteFTPPro.TEConnection")

' Initialize remote server host name, protocol, port, etc.
MySite.Host = "xx.xx.xx.xx"
MySite.Protocol = "SFTP"
MySite.Port = 22
MySite.Retries = 30
MySite.Delay = 30
MySite.MaxConnections = 2
MySite.TransferType = "AUTO"
MySite.DataChannel = "DEFAULT"
MySite.AutoRename = "OFF"
' WARNING!!! SENSITIVE DATA: user name and password.
MySite.Login = "user"
MySite.Password = "pwd"
MySite.SocksInfo = ""
MySite.ProxyInfo = ""
' Connect to remote server
'MySite.Disconnect
MySite.Connect

If Cbool(MySite.IsConnected) Then
    outFile.WriteLine "Connected to server: " & MySite.Host
End If

If Err.Number > 0 Then
    outFile.WriteLine "Error: " & Err.Description
    Err.Clear
End If

Call UploadAndBackupFiles(MySite,fos,outFile,"\\10.7.11.103\cusdec_edi\ZB1\","\\10.7.11.103\cusdec_edi\Archive\ZB1\" & FormatCurrentDate() & "\")
Call UploadAndBackupFiles(MySite,fos,outFile,"\\10.7.11.103\cusdec_edi\ZB2\","\\10.7.11.103\cusdec_edi\Archive\ZB2\" & FormatCurrentDate() & "\")
Call DownloadFilesFromSFTP(MySite,outFile,"\\10.7.11.103\cusdec_edi\ZBack","/outbound/")

' Close
outFile.WriteLine "End Time: " & FormatDateTime(Now())
outFile.WriteLine "==========================================================================================" & vbCrLf & vbCrLf
outFile.Close
Set fos = Nothing
MySite.Disconnect
'MySite.Close
WScript.Quit

给TA捐赠
共{{data.count}}人
人已捐赠
其他

聚合搜索工具2.0版本

2022-4-12 11:29:13

其他

easyini库的使用详细说明(1)

2022-4-18 0:34:57

2 条回复 A文章作者 M管理员
个人中心
购物车
优惠劵
有新私信 私信列表
搜索