Jump to content
Graeme

Is FTPS or FTP over SSL possible in AutoIT

Recommended Posts

Graeme

Hi,

I'm trying to download a file from a secure site that doesn't allow ftp. I've been trying to use FTPS but I can't find anything about FTPS (or FTP over SSL) except one reference that was a few years ago. So I'm wondering if things have changed. I've trawled through WinHttp and FF but can't find anything.

If anyone has some good ideas I'd love to hear from you. here is one example of what I tried, and it seemed to work at first but then there was no response at the end:(

#include <string.au3>
#include <inet.au3>
#include <guiconstants.au3>
#include <winhttp.au3>

Dim $hw_connect, $hw_open, $h_openRequest, $LocalIP, $M

$LocalIP = "https://www.example.org"

$hw_open = _WinHttpOpen()

$hw_connect = _WinHttpConnect($hw_open, $LocalIP)

$h_openRequest = _WinHttpOpenRequest($hw_connect, "GET", "programname.exe")
MsgBox(0,"",$hw_connect&@error)
$M = _WinHttpSetCredentials($h_openRequest, $WINHTTP_AUTH_TARGET_SERVER, $WINHTTP_AUTH_SCHEME_BASIC, "username", "password")
MsgBox(0,"",$M)
$M= _WinHttpSendRequest($h_openRequest)
MsgBox(0,"",$M)

$M= _WinHttpReceiveResponse($h_openRequest)
MsgBox(0,"",$M& " " &@error)

Share this post


Link to post
Share on other sites
Melba23

Graeme,

Please pay attention to where you post - the "Examples" section where you started this thread is clearly marked: "This is NOT a general support forum!". I have moved the thread for you, but would ask you to be more careful in future. ;)

M23


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

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites
somdcomputerguy

I don't know if you've searched thru the forums yet, but if not, try it. Use ftps as the keyword.


- Bruce /*somdcomputerguy */  If you change the way you look at things, the things you look at change.

Share this post


Link to post
Share on other sites
Graeme

Melba23 - Thanks for moving my question to the right place. Sorry that I made that error.

SoundComputerguy - Sorry I didn't specifiy that the forums were one of the places I had been also trawling through - my eyes are going square:( Any fresh ideas very welcome.

Blessings

Graeme

Share this post


Link to post
Share on other sites
trancexx

WinHTTP doesn't support FTP protocol in any form.


♡♡♡

.

eMyvnE

Share this post


Link to post
Share on other sites
Graeme

Thanks for that trancexx. Have a good day.

Blessings

Graeme

Share this post


Link to post
Share on other sites
smcan

Don't know if it would get you where you want to go but you could try using psftp.exe (http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html).

Would need to have psftp.exe in the working directory or get it in the path of the script and you would need a separate script file for use by psftp in the working directory as well.

Script file contains the commands you want to run through psftp (example.scr):

cd /home/user

put test.txt

get test2.txt

quit

Would call it via autoit with:

Run(@ComSpec & " /c" & "psftp.exe user@hostname -pw password -b test.scr","",@SW_HIDE)

The -b test.scr is what calls the psftp script.

Share this post


Link to post
Share on other sites
Graeme

Hi Wakillon,

I downloaded the libcurl.au3 etc but I can't make even the example files work? What could I be doing wrong?

Blessings

Graeme

Share this post


Link to post
Share on other sites
wakillon

Hi Wakillon,

I downloaded the libcurl.au3 etc but I can't make even the example files work? What could I be doing wrong?

Blessings

Graeme

 

Try this way :

#include <libcURL.au3>

Global $bCallbackBuffer

_url2file ( 'ftps://...../filename.txt', @DesktopDir & '\filename.txt' )

Func _url2file($sURL, $sFilePath)
    ConsoleWrite ( '$sURL : ' & $sURL & @Crlf )
    Local $hcurl = _curl_easy_init()
    If $hcurl Then
        Local $tCURLSTRUCT_URL = DllStructCreate("char[" & StringLen($sURL) + 1 & "]")
        DllStructSetData($tCURLSTRUCT_URL, 1, $sURL)
        _curl_easy_setopt($hcurl, $CURLOPT_URL, DllStructGetPtr($tCURLSTRUCT_URL))
        _curl_easy_setopt($hcurl, $CURLOPT_VERBOSE, 1)
        _curl_easy_setopt($hcurl, $CURLOPT_FOLLOWLOCATION, 1)
        _curl_easy_setopt($hcurl, $CURLOPT_NOPROGRESS, 1)

        _curl_easy_setopt ( $hcurl, $CURLOPT_PORT, 990 ) ; Port 990 for the FTPS control channel, and 989 for the FTPS data channel
        _curl_easy_setopt ( $hcurl, $CURLOPT_SSL_VERIFYPEER, 0 )
        _curl_easy_setopt ( $hcurl, $CURLOPT_SSL_VERIFYHOST, 1 )
        _curl_easy_setopt ( $hcurl, $CURLOPT_USE_SSL, $CURLOPT_FTPSSLAUTH )
        _curl_easy_setopt ( $hcurl, $CURLOPT_USERPWD, 'username:password' ) ; set your username and password
        _curl_easy_setopt ( $hcurl, $CURLOPT_SSLVERSION, 3 )

        $bCallbackBuffer = ""
        Local $handle = DllCallbackRegister("_my_fwrite", "uint:cdecl", "ptr;uint;uint;ptr")
        _curl_easy_setopt($hcurl, $CURLOPT_WRITEFUNCTION, DllCallbackGetPtr($handle))
        _curl_easy_setopt($hcurl, $CURLOPT_WRITEDATA, 0)
        _curl_easy_perform($hcurl)
        DllCallbackFree($handle)
        _curl_easy_cleanup($hcurl)
        If $bCallbackBuffer Then
            ConsoleWrite("+ $bCallbackBuffer: " & $bCallbackBuffer & @CRLF)
            Local $fh = FileOpen($sFilePath, 18)
            If $fh <> -1 Then
                FileWrite($fh, $bCallbackBuffer)
                FileClose($fh)
            EndIf
        EndIf
    EndIf
EndFunc   ;==>_url2file

Func _my_fwrite($buffer, $size, $nmemb, $stream)
    Local $vData = DllStructCreate("byte[" & $size * $nmemb & "]", $buffer)
    $bCallbackBuffer &= DllStructGetData($vData, 1)
    Return $size * $nmemb
EndFunc   ;==>_my_fwrite

Not tested as i do not have access to a ftps server...

Try to adapt it to your needs  :)


AutoIt 3.3.14.2 X86 - SciTE 3.6.0WIN 8.1 X64 - Other Example Scripts

Share this post


Link to post
Share on other sites
anh7codon

Hello

Is there any example for Upload a file via FTPS with libcurl.au3

Share this post


Link to post
Share on other sites
t0nZ

Hi @anh7codon, I share this function from one of my scripts, this piece of code uploads on a secure FTP site some files.PDF.

I worked starting from this post, and  in short you have to use the SFTPEx.au3 UDF and keep in the same folder with your script this executable: psftp.exe (read the post I linked...)

My code for upload:

#include <SFTPEx.au3>

Func loadcorrections() ; carico i pdf invoice da correggere
    GOLLOG("checking corrections 2 send...")
    Local $corrarray = _FileListToArrayRec($folderPDF2correct, "fatt-*-*-*.pdf", 1, 0, 1, 0)
    If @error Then
        If @extended = 9 Then
            GOLLOG("no corrections 2 send !")
        Else
            $ctrlftpesito1 = "error checking corrections: " & @extended
            ExitwithError()
        EndIf
        Return
    EndIf

    ;_ArrayDisplay($corrarray) ; DEBUG
    ;ftp connessione
    Local $Open
    Local $conta = 0
    $Open = _SFTP_Open($psftp) ; inoltre apro e chiudo sFTP per ogni singola cartella
    $Conn = _SFTP_Connect($Open, $ftpserver, $ftpuser, $ftppass) ; SFTP 
    If $Conn = 0 Then
        $ctrlftpesito1 = "ftp_connect ERROR"
        ExitwithError()
    Else
        $ctrlftpesito1 = "ftp_connect OK"
        GOLLOG($ctrlftpesito1)
    EndIf
    ; imposto cartella di Upload

    If StringInStr(_SFTP_DirSetCurrent($Conn, $folderFTPcorrezioni), $folderFTPcorrezioni) <> 0 Then ;posiziono a directory ftp
        GOLLOG("dirSetCurrent OK")
    Else
        $ctrlftpesito1 = "error in ftp_dirsetcurrent " & @error
        ExitwithError()
    EndIf

    Do
        $conta += 1 ;contatore files
        If _SFTP_Fileput($Conn, $folderPDF2correct & "\" & $corrarray[$conta]) Then
            GOLLOG("UPLOADED " & $corrarray[$conta])
        Else
            $ctrlftpesito1 = "error" & @error & " uploading " & $corrarray[$conta]
            ExitwithError()
        EndIf

        If Not FileMove($folderPDF2correct & "\" & $corrarray[$conta], $folderPDFcorrectsent & "\" & $corrarray[$conta], 1) Then

            $ctrlftpesito1 = "error" & @error & " moving uploaded corrected file: " & $corrarray[$conta]
            ExitwithError()


        EndIf

    Until $conta = $corrarray[0]
    _SFTP_Close($Conn)

    Local $textcorr = $conta & " Corrected Invoices uploaded and stored "

    GOLLOG($textcorr)
    $textcorr = $textcorr & _ArrayToString($corrarray, "|", 1)
    mail("mail@themail.it", " -info- fatture corrette", $textcorr, "")

EndFunc   ;==>loadcorrections

In this func I search for a bunch of PDF files, I put the names in an array and I upload every file.

Bye

Share this post


Link to post
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

  • Similar Content

    • Sally1801
      By Sally1801
      Hello,
      i need help in deleting files from a server. The function "_FTP_DirDelete" only deletes a directory when its empty. I need to delete a non empty directory. I also can not delete the files in this directory first, because the files are PAG and DIR files in a .DAV directory and FTPEx.au3 doesnt like a directory starting with a ".".
      Any ideas?
      Thx, Sally
    • myspacee
      By myspacee
      Hello,
      at job we have change our old mail servers with Outlook365. We have a lot of scripts that use mail, and i must 'convert' all them to new environment.
      No problem for sending mail. Microsoft staff give us also an open SMPT server listening on port 25.
      I need help to download mail from MS. I have big troubles because can't bypass SSL/TLS wall, using command line.
      Before change, I use a wonderful Command line Pop client.  But it doesn't have SSL support.
      I don't want to reinvent the well but exist, in Autoit, the way to code a POP3 client with SSL/TLS support ?
      (maybe not using OUTLOOK udf, can't install office on our server [ I don't have so many licenses ] )
      Thank you for your time
      m.
    • CharlieH
      By CharlieH
      Hi,
       
      I have written a small script to read a file from an FTP server and check its contents. This can be re-run by the press of a button, however, if the file is deleted from the ftp server between runs (with the .exe still live), the file is still "read" and written locally, which then passes the check.
       
      If I run it initially without the file, it correctly fails and pops up my error message, but if the file is then added, it then seemingly gets cached (or similar) so that the app then always reports a success.
       
      The below code snippet is just the function run when the "test" button is pressed. It includes a load of debug message boxes, and from that I think I've gathered a few (possibly) interesting/relevant things:
      $Open and $Conn are 8 byte values, which increments (not by 1) when the FTP connection is not closed, but if the connection is closed, they stick at the value (presumably windows can re-use that session id if it's been closed e.g:
      1st run (file not present) $Open -> 0x00CC0004 $Conn -> 0x00CC0008
      2nd run (file not present) $Open -> 0x00CC0010 $Conn -> 0x00CC0014
      3rd run (file now present) $Open -> 0x00CC001C $Conn -> 0x00CC0020
      4th run (file still present) $Open -> 0x00CC001C $Conn -> 0x00CC0020
      $Ftp = _FTP_FileGet.... returns a 1 when file not present (in a run after it was present) and "test_transfer.txt" does get created and does contain the correct string This is the key bit I dont understand, I dont know how/where it is getting the data to write this file when it literally no longer exists on the target FTP server...
      resetting every variable used in the function each time it's run does work (in that they become 0), but it doesn't affect the putcome I had thought perhaps some key values were being stored in the variables, but this doesn't seem to be the case
       
       
      Is there any concept of clearing a cache when closing an ftp session? Or deleting any unknown temporary files windows might make?
       
      Thanks all
       
      Func Transfer() Local $connected = 0 $Ftpp = 0 ;Trying to reset these every time function is called $file = 0 $Open = 0 $Conn = 0 $Ftpc = 0 ;Make a new "connecting..." window so that the user has feedback that a transfer is attempting to take place ;Otherwise it just runs in the background and there's no indication its doing anything $connection_window = GUICreate ("Ethernet Switch Test" , 300 , 160 , -1 , -1 , -1 , -1 , 0) GUISetBkColor(0xFFFFFF) GUISetFont(10 * _GDIPlus_GraphicsGetDPIRatio()[0], 400, Default, "Sans Serif") $connecting_label = GUICtrlCreateLabel("Connecting to board...", 0, 25, 300, -1, $SS_Center, "") GUISetState(@SW_SHOW, $connection_window) Sleep(100) ;Connect ;MsgBox(0, "DEBUG", "1" & $Conn) While $connected = 0 $Open = _FTP_Open($count) ;MsgBox(0, "DEBUG", "open " & $Open) $Conn = _FTP_Connect($Open, $server, $username, $password) ;MsgBox(0, "DEBUG", "2" & $Conn) If $Conn = 0 then Local $retry = Msgbox(65, 'FTP Transfer', 'Connection failed' & @CRLF & "Retry?") If $retry = 2 Then MsgBox(0, "FTP Transfer", "Operation aborted") GUISetState(@SW_HIDE, $connection_window) Return EndIf Else $connected_label = GUICtrlCreateLabel("Connected!", 0, 45, 300, -1, $SS_Center, "") $connected = 1 MsgBox(0, "DEBUG", "3" & $connected) Sleep(100) endIf WEnd $transfering_label = GUICtrlCreateLabel("Reading file....", 0, 45, 300, -1, $SS_Center, "") ;Read file from server ;MsgBox(0, "DEBUG", "5" & $Ftpp) ;MsgBox(0, "DEBUG", "flie " & $file) $Ftpp = _FTP_FileGet($Conn, 'test/test.txt', 'test_transfer.txt') ;MsgBox(0, "DEBUG", "6" & $Ftpp) If ($Ftpp) then $transfered_label = GUICtrlCreateLabel("Transfered, checking...", 0, 65, 300, -1, $SS_Center, "") ;MsgBox(0, "DEBUG", "flie " & $file) $file = FileRead("test_transfer.txt") ;MsgBox(0, "DEBUG", "flie " & $file) If Not StringInStr($file, 'this is a test string 12345') Then MsgBox(0, "File check", "Received file incorrect, test failed!") GUISetState(@SW_HIDE, $connection_window) Return Else $tested_label = GUICtrlCreateLabel("Tested and Passed!", 0, 85, 300, -1, $SS_Center, "") $Ftpc = _FTP_Close($Open) ;MsgBox(0, "DEBUG", "close" & $Ftpc) ;$count = $count+1 $ok_button = GUICtrlCreateButton("OK", 125, 105, 50, -1) While 1 Local $pressed = GUIGetMsg() If ($pressed = $ok_button) Then FileDelete("test_transfer.txt") GUISetState(@SW_HIDE, $connection_window) ;$connection_window = 0 Return EndIf WEnd EndIf Else MsgBox(0, "Transfer", "Could not read file " & @error) GUISetState(@SW_HIDE, $connection_window) Return EndIf EndFunc  
    • Sigmac
      By Sigmac
      I have used this code for a long time, but for a week or 2 it stopped working?
      Connection is ok, the put create the file on server if I delete it on the FTP server, but the file is empty and after 30 secondees the function return 0
      I have tested on 2 machines, Filezilla FTP client have no issue to the server.
      Firewall is disabled under test.
        If $writeFTP = True Then
            $Open=_FTPOpen('MyFTP Control')
            $Conn=_FTPConnect($Open, $destinationServer, $destinationUsername, $destinationPass)
       MsgBox(0,"start","start")
            $Ftpp=_FtpPutFile($Conn, $filePath&$name&".json", "httpdocs/p_calender/" & $name & ".json")
      MsgBox(0,"return","return"&$Ftpp)
      Exit
            $Ftpc=_FTPClose($Open)
           EndIf
       
      From the Lib:
      Func _FTPPutFile($l_FTPSession, $s_LocalFile, $s_RemoteFile, $l_Flags = 0, $l_Context = 0)
          Local $ai_FTPPutFile = DllCall('wininet.dll', 'int', 'FtpPutFile', 'long', $l_FTPSession, 'str', $s_LocalFile, 'str', $s_RemoteFile, 'long', $l_Flags, 'long', $l_Context)
          If @error OR $ai_FTPPutFile[0] = 0 Then
              SetError(-1)
              Return 0
          EndIf
          Return $ai_FTPPutFile[0]
      EndFunc ;==> _FTPPutFile()
       
    • mLipok
      By mLipok
      As for now I was using such kind of snippet:
      Local $aFTP_FileList = _FTP_ListToArray($hFTPSession, 2) For $iFTPFileSize_idx = 1 To $aFTP_FileList[0] ConsoleWrite('Pobieram informacje o pliku:' & $aFTP_FileList[$iFTPFileSize_idx] ) $iWielkoscPliku = _FTP_FileGetSize($hFTPSession, $aFTP_FileList[$iFTPFileSize_idx]) ConsoleWrite($iFTPFileSize_idx & ' : ' & $aFTP_FileList[$iFTPFileSize_idx] & ' rozmiar=' & $iWielkoscPliku) Sleep(200) Next  
      But from some time my clients start buying cheap WD MyCloud NAS, and my problems starts.
      On all others NAS there is no problem (Seagate BlackArmour, QNAP, SYNOLOGY .... ).

      When on list there is for example 20 files then first two of them are very fast checked and reported they FileSize.
      After 2 files there is about 20 sec stop....... and next two files are checked with no errors but FileSize == 0 
      again there is about 20 sec stop....... and next two files are checked with no errors but FileSize == 0 
      again there is about 20 sec stop....... and next two files are checked with no errors but FileSize == 0 
      again there is about 20 sec stop....... and next two files are checked with no errors but FileSize == 0 
      again there is about 20 sec stop....... and next two files are checked with no errors but FileSize == 0 
      .......
       
      In time when I process investigation I checked how :  _FTP_ListToArray2D and _FTP_ListToArrayEx works and I was shocked that they works super fast.
       
      Here are the questions:
      Q1: Why does the problem occur only on WD MyCloud NAS?
      Q2: What is the significant difference that makes using _FTP_ListToArray2D and _FTP_ListToArrayEx to retrieve file sizes is still fast?
      Q3: Why _FTP_FileGetSize() not reporting @errors but returned FileSize = 0 
       
      Regards,
      mLipok
       
×