Jump to content

WinSCP - UDF


mLipok
 Share

Recommended Posts

Hi all.
Today I would like to introduce the beginning of the UDF.

How to get started:

http://winscp.net/eng/docs/library

http://winscp.net/eng/docs/library_install

Original readme_automation.txt:

This is the README file for automation package of WinSCP.



For use of WinSCP automation package see
http://winscp.net/eng/docs/library
http://winscp.net/eng/docs/library_install

To use this package you must unpack it to the WinSCP installation folder
or to a folder, where you have already unpacked the WinSCP standalone package.
http://winscp.net/eng/docs/installation or
http://winscp.net/eng/docs/portable

To use the WinSCP assembly via COM interop, register it using:
%WINDIR%Microsoft.NETFrameworkRegAsm.exe WinSCPnet.dll /codebase /tlb
where is typically either v4.0.30319 or v2.0.50727.
http://winscp.net/eng/docs/library_install#registering

WinSCP homepage is http://winscp.net/

See the file 'license-dotnet.txt' for the license conditions.

 

now I have only one function (standard FTP on standard port) to show the future possibilities:

Local $oErrorHandler = ObjEvent("AutoIt.Error", "_ErrFunc")
Const Enum _
        $__eWSCP_SO_Protocol_Sftp, _
        $__eWSCP_SO_Protocol_Scp, _
        $__eWSCP_SO_Protocol_Ftp
Const Enum _
        $__eWSCP_TO_TransferMode_Binary, _
        $__eWSCP_TO_TransferMode_Ascii, _
        $__eWSCP_TO_TransferMode_Automatic

Example_PutFile('YOUR FTP HOST NAME', 'YOUR USER NAME', 'YOUR PASSWORD')

Func Example_PutFile($sHostName, $sUserName, $sPassword)
    Local $sFileFullPath = StringReplace(@ScriptFullPath, '\', '\\')
    Local $sFilesToPut = StringReplace(@ScriptDir & '\*.au3', '\', '\\')


    ; based on:
    ; http://winscp.net/eng/docs/library_com_wsh#vbscript

    Local $oSessionOptions = ObjCreate("WinSCP.SessionOptions");
    With $oSessionOptions
        .Protocol = $__eWSCP_SO_Protocol_Ftp
        .HostName = $sHostName;
        .UserName = $sUserName;
        .Password = $sPassword;
        ; below not jet tested
        ; .SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
    EndWith

    Local $oSession = ObjCreate("WinSCP.Session");
    With $oSession

        ; Connect: Open sesion with defined options
        .Open($oSessionOptions);

        ; Set TransferOptions
        Local $oTransferOptions = ObjCreate("WinSCP.TransferOptions")
        $oTransferOptions.TransferMode = $__eWSCP_TO_TransferMode_Binary
        ; Upload files: put @ScriptFullPath to the ROOT directory
        Local $oTransferResult = .PutFiles($sFilesToPut, '/');

        ; Throw on any error
        $oTransferResult.Check

        ; Print results
        For $oTransfer In $oTransferResult.Transfers
            ConsoleWrite("Upload of " & $oTransfer.FileName & " succeeded" & @CRLF)
        Next

        ;' Disconnect, clean up
        .Dispose()
    EndWith

    ; CleanUp

    $oSession = ''
    $oSessionOptions = ''

EndFunc   ;==>Example_PutFile

Func _ErrFunc($oError)
    ; Do anything here.
    ConsoleWrite(@ScriptName & " (" & $oError.scriptline & ") : ==> COM Error intercepted !" & @CRLF & _
            @TAB & "err.number is: " & @TAB & @TAB & "0x" & Hex($oError.number) & @CRLF & _
            @TAB & "err.windescription:" & @TAB & $oError.windescription & @CRLF & _
            @TAB & "err.description is: " & @TAB & $oError.description & @CRLF & _
            @TAB & "err.source is: " & @TAB & @TAB & $oError.source & @CRLF & _
            @TAB & "err.helpfile is: " & @TAB & $oError.helpfile & @CRLF & _
            @TAB & "err.helpcontext is: " & @TAB & $oError.helpcontext & @CRLF & _
            @TAB & "err.lastdllerror is: " & @TAB & $oError.lastdllerror & @CRLF & _
            @TAB & "err.scriptline is: " & @TAB & $oError.scriptline & @CRLF & _
            @TAB & "err.retcode is: " & @TAB & "0x" & Hex($oError.retcode) & @CRLF & @CRLF)
EndFunc   ;==>_ErrFunc

EDIT: 2014-06-20 04:47 - script changed

Edited by mLipok

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

Nice start. I use WinScp a lot at work to connect to different AIX-Servers. Go ahead!

Scripts & functions Organize Includes Let Scite organize the include files

Yahtzee The game "Yahtzee" (Kniffel, DiceLion)

LoginWrapper Secure scripts by adding a query (authentication)

_RunOnlyOnThis UDF Make sure that a script can only be executed on ... (Windows / HD / ...)

Internet-Café Server/Client Application Open CD, Start Browser, Lock remote client, etc.

MultipleFuncsWithOneHotkey Start different funcs by hitting one hotkey different times

Link to comment
Share on other sites

Nice to hear that .

What is the connection method you use?
What kind of encryption?

I need someone to test - would you be so kind?

mLipok

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

I would be more than happy to test, as I will most likely this weekend play around with the .NET assembly.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

I just install Filezilla Server

https://wiki.filezilla-project.org/FTPS_using_Explicit_SSL/TLS_howto_(Server)

and starting with testing.

But any feedback would be welcome.

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

I use SFTP with a SSH tunnel. First I have to connect to a jump-server and then go from there to all other servers.

Edited by Xenobiologist

Scripts & functions Organize Includes Let Scite organize the include files

Yahtzee The game "Yahtzee" (Kniffel, DiceLion)

LoginWrapper Secure scripts by adding a query (authentication)

_RunOnlyOnThis UDF Make sure that a script can only be executed on ... (Windows / HD / ...)

Internet-Café Server/Client Application Open CD, Start Browser, Lock remote client, etc.

MultipleFuncsWithOneHotkey Start different funcs by hitting one hotkey different times

Link to comment
Share on other sites

  • 4 years later...
Local $Winscpun = 'Me.xprt.sftp'
Local $Winscpconn = 'transfer.server2.com'
Local $Winscpssh = 'ssh-rsa 4096 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00'
Local $Winscpmask = '/Exports/Data*.*'
Local $Winscplocal = 'S:\Server\User\'
Local $Commongrpname = 'Phrase'

        
        Global $filesdownloaded = False
        Local $sDecrypted = StringEncrypt(False, RegRead("HKEY_LOCAL_MACHINE\SOFTWARE\Key", "SFTP"), $Commongrpname)
        Const Enum $__eWSCP_SO_Protocol_Sftp, $__eWSCP_SO_Protocol_Scp, $__eWSCP_SO_Protocol_Ftp
        Const Enum $__eWSCP_TO_TransferMode_Binary, $__eWSCP_TO_TransferMode_Ascii, $__eWSCP_TO_TransferMode_Automatic
        Loged("Get Files")
        Local $oSessionOptions = ObjCreate("WinSCP.SessionOptions");
        $oSessionOptions.Protocol = $__eWSCP_SO_Protocol_Sftp
        $oSessionOptions.HostName = $Winscpconn;
        $oSessionOptions.UserName = $Winscpun;
        $oSessionOptions.Password = $sDecrypted;
        $oSessionOptions.SshHostKeyFingerprint = $Winscpssh
        Local $oSession = ObjCreate("WinSCP.Session");
        $oSession.Open($oSessionOptions);
        Local $oTransferOptions = ObjCreate("WinSCP.TransferOptions")
        $oTransferOptions.TransferMode = $__eWSCP_TO_TransferMode_Binary
        $oTransferOptions.PreserveTimestamp = True
        $oTransferOptions.Filemask = $Winscpmask
        Local $oTransferResult = $oSession.GetFiles('*', $Winscplocal, False, $oTransferOptions)
        $oTransferResult.Check
        Sleep(1000)
        Local $tmpFilename
        For $oTransfer In $oTransferResult.Transfers
            ;Rename remote files
            $filesdownloaded = True
            Loged("Rename remote files")
            $dt = StringReplace(_NowDate(),"/",".")
            $dt = StringReplace($dt," ","")
            $orgfn = $oTransfer.FileName
            $tmpFilename = $oTransfer.FileName
            ;msg(StringReplace($tmpFilename, "/Exports/", "/Exports/Downloaded_" & $dt & "_" ))
            Local $oTransferResult2 =  $oSession.MoveFile($orgfn,StringReplace($tmpFilename, "/Exports/", "/Exports/Downloaded_" & $dt & "_" ))
        Next
        $oSession.Dispose()
        $oSession = ''
        $oSessionOptions = ''

I used alot of what you posted to figure out how to download alot of similar files and then rename them after download. Take the following with a grain of salt, hope it helps someone...

I encrypted my password in the registry so it's not in plain site, I also have it renaming the remote files so I don't download them again

 


 

Edited by dwalker0229
made into code block(first time)
Link to comment
Share on other sites

  • 5 weeks later...

First, let me say thanks to all who have put time into creating this UDF solution.

Okay, now for my problem... 

I keep getting:
Local $oTransferResult2 =  $oSession.MoveFile($origFN,StringReplace($newFN, $remoteDir, $remoteDir & '/~Loaded'))
Local $oTransferResult2 =  $oSession^ ERROR

I have tried everything I can think of, and still get this error every time.  I include WinSCP.au3 in my script.   my original WinSCP.au3 has this:
Func _sftpMove($oSession, $source, $target)
    $oSession.MoveFile($source, $target)
    Return $oSession.FileExists($target)
EndFunc

When I call it from my other script with _sftpMove($sftpSession,$source,$target), I get the same error.

Can someone please stop me from pulling anymore hair out??

 

Thanks

 

 

Link to comment
Share on other sites

Post your script, and copy/paste the output pane of SciTE so we can see the entire error message.

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

Section of script calling WinSCP.au3:

Func _syncImportFiles()
;~     $sftpAccts: customer_id, hostkey,sftp_host, sftp_port, sftp_username, sftp_password,sftp_download_path,contact_email

    _alert('Beginning sync of import files for customer_id: ' & $customer_id)

    ; Create local directory
    $localDir         = @ScriptDir & '\member_lists\' & $sftpAccts[$row][0]
    DirCreate($localDir)


    ; Sync patient import files sftp with local directory
    $sftpHost        = $sftpAccts[$row][2]
    $sftpUser        = $sftpAccts[$row][4]
    $sftpPassword    = $sftpAccts[$row][5]
    $hostKey        = $sftpAccts[$row][1]
    $sftpPort        = $sftpAccts[$row][3]
    Global $remoteDir        = $sftpAccts[$row][6]
    Global $sftpSession = _sftpOpen($sftpHost, $sftpUser, $sftpPassword, $hostKey, $sftpPort)

    If $sftpSession = False Then
        If $sftpSession Then $sftpSession.Dispose
        _alert('Failed to sync import files', $LOG, $EMAIL)
        Return SetError(-1, 0, False)
    EndIf
    
    If @error Then
        _alert('Failed to sync files.  Error Code: ' & @error, $LOG, $EMAIL)
        Return SetError(-2, 0, False)
    ElseIf UBound($syncedFiles)>0 Then
        _alert('Synced files:' & @CRLF & _ArrayToString($syncedFiles))
        Return True
    Else
        _alert('Synced files: NONE')
        Return True
    EndIf


;~ _ArrayDisplay($syncedFiles)

EndFunc ; _syncImportFiles()
 

Portion of WinSCP.au3 that is running:
Func _sftpSyncMove($session, $localDir, $remoteDir, $direction='Both', $fileMask=Null)

    Switch $direction
        Case 'Local'
            $syncMode = 0
        Case 'Remote'
            $syncMode = 1
        Case 'Both'
            $syncMode = 2
    EndSwitch

    If $fileMask <> Null Then
        $oTransferOptions = ObjCreate("WinSCP.TransferOptions")
        If Not IsObj($oTransferOptions) Then
            SetError(-1)
            Return False
        EndIf
;~         $oTransferOptions.FileMask = $session.EscapeFileMask($fileMask)
        $oTransferOptions.FileMask = $fileMask
    Else
        $oTransferOptions = Null
    EndIf

    $syncResult = $session.SynchronizeDirectories($syncMode, $localDir, $session.EscapeFileMask($remoteDir), False, False, 1, $oTransferOptions)
    If Not IsObj($syncResult) Then
        SetError(-11)
        Return False
    EndIf

    If Not $syncResult.IsSuccess Then
        SetError(-5)
        Return False
    EndIf

    Dim $itemArray[0][3]
    For $transferItem in $syncResult.Downloads
        _ArrayAdd($itemArray, 'Download' & '|' & $transferItem.Destination  & '|' & $transferItem.FileName)
        ;MsgBox(0,"Files",$transferItem.FileName)
        $dt = StringReplace(_NowDate(),"/",".")
        $dt = StringReplace($dt," ","")
        $origFN = $transferItem.FileName
        $newFN = $transferItem.FileName & '_' & $dt

        ;msgBox(0,"",(StringReplace($newFN, $remoteDir, $remoteDir & '/~Loaded')))
        Local $oTransferResult2 =  $sftpSession.MoveFile($origFN,StringReplace($newFN, $remoteDir, $remoteDir & '/~Loaded'))
    Next
    For $transferItem in $syncResult.Uploads
        _ArrayAdd($itemArray, 'Upload' & '|' & $transferItem.Destination  & '|' & $transferItem.FileName)
    Next
    $oSession = ''
    Return $itemArray

EndFunc

 

Output:
--> Press Ctrl+Alt+Break to Restart or Ctrl+Break to Stop
2019/04/05 20:00:53 : Script initializing.
2019/04/05 20:00:53 : SFTP Accounts loaded
2019/04/05 20:00:53 : Beginning sync of import files for customer_id: 864
"C:\SOME\PATH\WinSCP2.au3" (217) : ==> The requested action with this object has failed.:
Local $oTransferResult2 =  $sftpSession.MoveFile($origFN,StringReplace($newFN, $remoteDir, $remoteDir & '/~Loaded'))
Local $oTransferResult2 =  $sftpSession^ ERROR
2019/04/05 20:01:31 : Script exiting
->20:01:31 AutoIt3.exe ended.rc:1
+>20:01:31 AutoIt3Wrapper Finished.
>Exit code: 1    Time: 39.95

Edited by jcobb
removed true path
Link to comment
Share on other sites

  • 4 years later...

Hi to all!

I'm not an expert in COM programming, but I'm always trying to implement it more an more into my coding.

I can't organize file copying files with progress. I will be grateful for any examples how to use FileTransferProgress and FileTransferProgressEventArgs to show the progress. 

 

Edited by RAMzor
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...