Jump to content

Sky Slate Blueberry Blackcurrant Watermelon Strawberry Orange Banana Apple Emerald Chocolate
Photo

FTP-uploading with the help of AHK


  • Please log in to reply
19 replies to this topic
Benny-D
  • Members
  • 1485 posts
  • Last active: Sep 27 2016 11:23 PM
  • Joined: 29 Feb 2008
I have a website where I keep some of my documents. So far I’ve been using IE6 to upload my files there in FTP mode manually, but I wonder if there is any command or a combination of commands in AHK that would make it possible to upload them automatically?

Let’s say my folder’s path on the website (its URL) is: <!-- m -->ftp://ftp.mysite.com/myfolder<!-- m --> ,
my login there is: mylogin ,
and my password there is: mypassword ,
Can anyone here, please, direct me as to which commands I should use?

Frankie
  • Members
  • 2930 posts
  • Last active: Feb 05 2015 02:49 PM
  • Joined: 02 Nov 2008
<!-- m -->http://www.autohotke... ... hlight=ftp<!-- m -->
aboutscriptappsscripts
Request Video Tutorials Here or View Current Tutorials on YouTube
Any code ⇈ above ⇈ requires AutoHotkey_L to run

Z_Gecko
  • Guests
  • Last active:
  • Joined: --
http://www.autohotke.../FileAppend.htm , the last example.

Benny-D
  • Members
  • 1485 posts
  • Last active: Sep 27 2016 11:23 PM
  • Joined: 29 Feb 2008
Thank you, Frankie and Z_Gecko! But now I am a little bit confused about which one to use. In the link given by Frankie there is even another link to a third option ( http://www.autohotke...pic.php?t=15203), which is also a kind of FTP uploader. So, which option is the best?

Frankie
  • Members
  • 2930 posts
  • Last active: Feb 05 2015 02:49 PM
  • Joined: 02 Nov 2008
Gecko's idea will be the easiest to uses. I think my link would work a little faster though.
aboutscriptappsscripts
Request Video Tutorials Here or View Current Tutorials on YouTube
Any code ⇈ above ⇈ requires AutoHotkey_L to run

Benny-D
  • Members
  • 1485 posts
  • Last active: Sep 27 2016 11:23 PM
  • Joined: 29 Feb 2008
I see. Thank you.

interms
  • Members
  • 25 posts
  • Last active: Sep 07 2009 11:00 PM
  • Joined: 01 Jan 2009
hmm, i've been working on this for the last few days.
who knows.
FTP_Connect(host,user,pass,commands)
{
  FTPCommandFile = %A_ScriptDir%\FTPCommands2.txt
  FTPLogFile = %A_ScriptDir%\FTPLog.txt
  FileDelete %FTPCommandFile%  ; In case previous run was terminated prematurely.

  FileAppend,
(
open %host%
%user%
%pass%
binary
%commands%
ls -l
quit
), %FTPCommandFile%

  RunWait %comspec% /c ftp.exe -s:"%FTPCommandFile%" >"%FTPLogFile%",, min
  
  ;Run %FTPLogFile%  ; Display the log for review.
}

host = ftp.wherever.com
user = username
pass = passwurd
commands = 

(ltrim
   put KLapps.spdr ; Upload example
   get KLapps.spdr ; Download example
   cd dir ;move directories
   )
FTP_Connect(host,user,pass,commands)

i kinda built it based on this:
<!-- m -->http://www.autohotke... ... 269#240269<!-- m -->
ya nevermind. already posted above me lol.

Benny-D
  • Members
  • 1485 posts
  • Last active: Sep 27 2016 11:23 PM
  • Joined: 29 Feb 2008
Well, I decided to take the path of least resistense and chose the simplest code from the help file (http://www.autohotke.../FileAppend.htm):
; The following example demonstrates how to automate FTP uploading using the operating 
; system's built-in FTP command. This script has been tested on Windows XP and 98se.

FTPCommandFile = %A_ScriptDir%\FTPCommands.txt
FTPLogFile = %A_ScriptDir%\FTPLog.txt
FileDelete %FTPCommandFile%  ; In case previous run was terminated prematurely.

FileAppend,
(
open host.domain.com
username
password
binary
cd htdocs
put %VarContainingNameOfTargetFile%
delete SomeOtherFile.htm
rename OldFileName.htm NewFileName.htm
ls -l
quit
), %FTPCommandFile%

RunWait %comspec% /c ftp.exe -s:"%FTPCommandFile%" >"%FTPLogFile%"
FileDelete %FTPCommandFile%  ; Delete for security reasons.
Run %FTPLogFile%  ; Display the log for review.
and got stuck right away. I don't understand what I need to do here. Let's say my domain is my.domain.com, my username is myusername, my password is mypassword, and on the disk C of my computer I have a notepad file named cars (so the path is C:\cars.txt) that I want to upload. After I insert all this data into the script it looks like this:
; The following example demonstrates how to automate FTP uploading using the operating 
; system's built-in FTP command. This script has been tested on Windows XP and 98se.

FTPCommandFile = %A_ScriptDir%\FTPCommands.txt
FTPLogFile = %A_ScriptDir%\FTPLog.txt
FileDelete %FTPCommandFile%  ; In case previous run was terminated prematurely.

FileAppend,
(
open [color=red]my.domain.com[/color]
[color=red]myusername[/color]
[color=red]mypassword[/color]
binary
cd htdocs
put [color=red]C:\cars.txt[/color]
delete SomeOtherFile.htm
rename OldFileName.htm NewFileName.htm
ls -l
quit
), %FTPCommandFile%

RunWait %comspec% /c ftp.exe -s:"%FTPCommandFile%" >"%FTPLogFile%"
FileDelete %FTPCommandFile%  ; Delete for security reasons.
Run %FTPLogFile%  ; Display the log for review.
But when I try to run it here is what I get in the "FTPlog" file:

ftp> Connected to my.domain.com.

ftp> open my.domain.com
Invalid command.

ftp> myusername
Invalid command.

ftp> mypassword
Not connected.

ftp> binary
Not connected.

ftp> cd htdocs
Not connected.

ftp> put C:\cars.txt
Not connected.

ftp> delete SomeOtherFile.htm
Not connected.

ftp> rename OldFileName.htm NewFileName.htm
Not connected.

ftp> ls -l
quit

Can anyone please tell me what I am doing wrong here and what I should do to do it right.

tank
  • Administrators
  • 4345 posts
  • AutoHotkey Foundation
  • Last active: Oct 13 2016 01:04 AM
  • Joined: 21 Dec 2007
Use the other method provided by olfen
Never lose.
WIN or LEARN.

Benny-D
  • Members
  • 1485 posts
  • Last active: Sep 27 2016 11:23 PM
  • Joined: 29 Feb 2008
Can you please tell me where this other method provided by olfen is?

Frankie
  • Members
  • 2930 posts
  • Last active: Feb 05 2015 02:49 PM
  • Joined: 02 Nov 2008

http://www.autohotkey.com/forum/viewtopic.php?t=10393&highlight=ftp

That one.
aboutscriptappsscripts
Request Video Tutorials Here or View Current Tutorials on YouTube
Any code ⇈ above ⇈ requires AutoHotkey_L to run

Benny-D
  • Members
  • 1485 posts
  • Last active: Sep 27 2016 11:23 PM
  • Joined: 29 Feb 2008
Oops, I didn't notice it was by olfen. Thank you.

Benny-D
  • Members
  • 1485 posts
  • Last active: Sep 27 2016 11:23 PM
  • Joined: 29 Feb 2008
That code is so big! And I don't understand anything there. Plus, there are so many DllCalls ( I am afraid of them as if they were fire and I were a wolf). Where do I need to insert my password, username, the host name and the file name there? Can you please tell me?

Here is that code:
/*
http://msdn.microsoft.com/library/en-us/wininet/wininet/ftp_sessions.asp
http://msdn.microsoft.com/library/en-us/wininet/wininet/internetopen.asp
http://msdn.microsoft.com/library/en-us/wininet/wininet/internetconnect.asp
*/

FtpCreateDirectory(DirName) {
global ic_hInternet
r := DllCall("wininet\FtpCreateDirectoryA", "uint", ic_hInternet, "str", DirName)
If (ErrorLevel != 0 or r = 0)
return 0
else
return 1
}

FtpRemoveDirectory(DirName) {
global ic_hInternet
r := DllCall("wininet\FtpRemoveDirectoryA", "uint", ic_hInternet, "str", DirName)
If (ErrorLevel != 0 or r = 0)
return 0
else
return 1
}

FtpSetCurrentDirectory(DirName) {
global ic_hInternet
r := DllCall("wininet\FtpSetCurrentDirectoryA", "uint", ic_hInternet, "str", DirName)
If (ErrorLevel != 0 or r = 0)
return 0
else
return 1
}

FtpPutFile(LocalFile, NewRemoteFile="", Flags=0) {
;Flags:
;FTP_TRANSFER_TYPE_UNKNOWN = 0 (Defaults to FTP_TRANSFER_TYPE_BINARY)
;FTP_TRANSFER_TYPE_ASCII = 1
;FTP_TRANSFER_TYPE_BINARY = 2
If NewRemoteFile=
NewRemoteFile := LocalFile
global ic_hInternet
r := DllCall("wininet\FtpPutFileA"
, "uint", ic_hInternet
, "str", LocalFile
, "str", NewRemoteFile
, "uint", Flags
, "uint", 0) ;dwContext
If (ErrorLevel != 0 or r = 0)
return 0
else
return 1
}

FtpGetFile(RemoteFile, NewFile="", Flags=0) {
;Flags:
;FTP_TRANSFER_TYPE_UNKNOWN = 0 (Defaults to FTP_TRANSFER_TYPE_BINARY)
;FTP_TRANSFER_TYPE_ASCII = 1
;FTP_TRANSFER_TYPE_BINARY = 2
If NewFile=
NewFile := RemoteFile
global ic_hInternet
r := DllCall("wininet\FtpGetFileA"
, "uint", ic_hInternet
, "str", RemoteFile
, "str", NewFile
, "int", 1 ;do not overwrite existing files
, "uint", 0 ;dwFlagsAndAttributes
, "uint", Flags
, "uint", 0) ;dwContext
If (ErrorLevel != 0 or r = 0)
return 0
else
return 1
}

FtpGetFileSize(FileName, Flags=0) {
;Flags:
;FTP_TRANSFER_TYPE_UNKNOWN = 0 (Defaults to FTP_TRANSFER_TYPE_BINARY)
;FTP_TRANSFER_TYPE_ASCII = 1
;FTP_TRANSFER_TYPE_BINARY = 2
global ic_hInternet
fof_hInternet := DllCall("wininet\FtpOpenFileA"
, "uint", ic_hInternet
, "str", FileName
, "uint", 0x80000000 ;dwAccess: GENERIC_READ
, "uint", Flags
, "uint", 0) ;dwContext
If (ErrorLevel != 0 or fof_hInternet = 0)
return -1

FileSize := DllCall("wininet\FtpGetFileSize", "uint", fof_hInternet, "uint", 0)
DllCall("wininet\InternetCloseHandle",  "UInt", fof_hInternet)
return, FileSize
}


FtpDeleteFile(FileName) {
global ic_hInternet
r :=  DllCall("wininet\FtpDeleteFileA", "uint", ic_hInternet, "str", FileName)
If (ErrorLevel != 0 or r = 0)
return 0
else
return 1
}

FtpRenameFile(Existing, New) {
global ic_hInternet
r := DllCall("wininet\FtpRenameFileA", "uint", ic_hInternet, "str", Existing, "str", New)
If (ErrorLevel != 0 or r = 0)
return 0
else
return 1
}

FtpOpen(Server, Port=21, Username=0, Password=0 ,Proxy="", ProxyBypass="") {
IfEqual, Username, 0, SetEnv, Username, anonymous
IfEqual, Password, 0, SetEnv, Password, anonymous

If (Proxy != "")
AccessType=3
Else
AccessType=1
;#define INTERNET_OPEN_TYPE_PRECONFIG                    0   // use registry configuration
;#define INTERNET_OPEN_TYPE_DIRECT                       1   // direct to net
;#define INTERNET_OPEN_TYPE_PROXY                        3   // via named proxy
;#define INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY  4   // prevent using java/script/INS

global ic_hInternet, io_hInternet, hModule
hModule := DllCall("LoadLibrary", "str", "wininet.dll")

io_hInternet := DllCall("wininet\InternetOpenA"
, "str", A_ScriptName ;lpszAgent
, "UInt", AccessType
, "str", Proxy
, "str", ProxyBypass
, "UInt", 0) ;dwFlags

If (ErrorLevel != 0 or io_hInternet = 0) {
FtpClose()
return 0
}

ic_hInternet := DllCall("wininet\InternetConnectA"
, "uint", io_hInternet
, "str", Server
, "uint", Port
, "str", Username
, "str", Password
, "uint" , 1 ;dwService (INTERNET_SERVICE_FTP = 1)
, "uint", 0 ;dwFlags
, "uint", 0) ;dwContext

If (ErrorLevel != 0 or ic_hInternet = 0)
return 0
else
return 1
}

FtpClose() {
global ic_hInternet, io_hInternet, hModule
DllCall("wininet\InternetCloseHandle",  "UInt", ic_hInternet)
DllCall("wininet\InternetCloseHandle",  "UInt", io_hInternet)
DllCall("FreeLibrary", "UInt", hModule)
}


Bjalf
  • Members
  • 11 posts
  • Last active: Nov 15 2009 11:13 AM
  • Joined: 26 Nov 2008

That code is so big! And I don't understand anything there.

I went with INet.ahk. I wanted to create and upload a redirection html script located in 2 different versions (spellings) of a directory on my home page. I basically tacked INet.ahk onto this code (scroll down to Ace_NoOne, Posted: Sun May 27, 2007 8:17 pm)

If the directories don't exist, they will be created.


#NoEnv

Server = home.blahblah.net
Port = 21
User = xxx
Pwd = xxx
LocalFile = %1%
Directory1 = /Directory
Directory2 = /directory



; Check that the redirection file actually exists before we try to upload it
IfNotExist, %LocalFile%
{
    MsgBox, Local File %LocalFile% does not exist.
    Exit, 1
}



; Initialize Internet resources and make Internet functions available
if (not INetStart())
{
    MsgBox, Failed to initialize.
    Exit, 1
}



; Open a connection to the FTP server
hConnection := INetConnect(Server, Port, User, Pwd, "ftp", 1)
if (hConnection)
{
    Error = 0
    if (not UploadFile(hConnection, Directory1, LocalFile))
        Error = 1
    if (not UploadFile(hConnection, Directory2, LocalFile))
        Error = 1

    INetCloseHandle(hConnection)
    INetStop()
    Exit, Error
}
else
{
    MsgBox, Failed to create a connection to the FTP server.
    INetStop()
    Exit, 1
}



UploadFile(hConnection, Directory, LocalFile)
{
    if (ChangeDirectory(hConnection, Directory))
    {
        SplitPath, LocalFile, RemoteFile
        if (FtpPutFile(hConnection, LocalFile, RemoteFile))
        {
            Return, true
        }
        else
        {
            MsgBox, Cannot upload file into %Directory%.
            Return, false
        }
    }
    else
    {
        MsgBox, Could not create or change to remote directory %Directory%.
        Return, false
    }
}



ChangeDirectory(hConnection, Directory)
{
    if (FtpSetCurrentDirectory(hConnection, Directory))
    {
        Return, true
    }
    else
    {
        if (FtpCreateDirectory(hConnection, Directory))
        {
            if (FtpSetCurrentDirectory(hConnection, Directory))
            {
                Return, true
            }
            else
            {
                MsgBox, Cannot change to remote directory %Directory%.
                Return, false
            }
        }
        else
        {
            MsgBox, Cannot create remote directory %Directory%.
            Return, false
        }
        MsgBox, Cannot change to remote directory %Directory%.
        Return, false
    }
}



; ******************************************************************************



; ------------------------------------------------------------------------------
; This function loads and tells the Internet DLL to initialize internal data structures
; and prepare for future calls from the application.
;
; Internet functions are not available before this function is called.
;
; param Proxy [in]
;   Specifies an optional name of a proxy server.
; param ProxyBypass [in]
;   Specifies an optional list of host names or IP addresses, or both, that should not be routed
;   through the proxy when a proxy is used.
; param Agent [in]
;    Specifies the name of the application or entity calling the WinINet functions.
;    This name is used as the user agent in the HTTP protocol.
;    When empty, the name of the script is used
; return
;   [bool] true if the function succeeds, otherwise false
;
INetStart(Proxy="", ProxyBypass="", Agent="")
{
   global
   ; get a handle to the WinINet library
   inet_hModule := DllCall("LoadLibrary", "str", "wininet.dll")
   if(!inet_hModule) {
      inet_hModule = 0
      return false
   }

;   INTERNET_OPEN_TYPE_PRECONFIG                    0   // use registry configuration
;   INTERNET_OPEN_TYPE_DIRECT                       1   // direct to net
;   INTERNET_OPEN_TYPE_PROXY                        3   // via named proxy
;   INTERNET_OPEN_TYPE_PRECONFIG_WITH_NO_AUTOPROXY  4   // prevent using java/script/INS
   inet_hInternet := DllCall("wininet\InternetOpenA"
      , "str", (Agent != "" ? Agent : A_ScriptName)
      , "UInt", (Proxy != "" ? 3 : 1)
      , "str", Proxy
      , "str", ProxyBypass
      , "UInt", 0)
   If(!inet_hInternet) {
      INetCloseHandle(inet_hModule)
      return false
   }
   return true
}

; ------------------------------------------------------------------------------
; Terminates the application's use of WinINet functions and unloads the Internet DLL.
;
; Internet functions are not available after this function call is called.
;
INetStop()
{
   global
   INetCloseHandle(inet_hInternet)
   DllCall("FreeLibrary", "UInt", inet_hModule)
   inet_hModule = inet_hInternet = 0
}

; ------------------------------------------------------------------------------
; Closes a single Internet handle, previously opened by INetConnect, FtpOpenFile, ...
;
; param hConnection [in]
;   The connection handle to be closed.
; return
;   [bool] true if the function succeeds, otherwise false
;
INetCloseHandle(hInternet)
{
   return DllCall("wininet\InternetCloseHandle", "UInt", hInternet)
}

; ------------------------------------------------------------------------------
; Opens an File Transfer Protocol (FTP), Gopher, or HTTP session for a given site.
;
; FtpPassive [in]
;   The value 1 causes the application to use passive FTP semantics
;
; param Server [in]
;   The host name or IP number of a server.
; param Server [in]
;   The TCP/IP port to connect to.
; param Username [in]
;   The name of the user to log on (default is anonymous)
; param Password [in]
;   The password to use to log on (default is anonymous)
; param Service [in]
;   Type of service to access. Must be of the following value: http (default), ftp, url or gopher
; param FtpPassive [in]
;   Option specific to ftp service. Setting 1 causes the application to use passive FTP semantics.
; return
;   the handle of the opened connection
;
INetConnect(Server, Port, Username="anonymous", Password="anonymous", Service="http", FtpPassive=0)
{
   global inet_hInternet
   hConnection := DllCall("wininet\InternetConnectA"
      , "uint", inet_hInternet
      , "str", Server
      , "uint", Port
      , "str", Username
      , "str", Password
      , "uint", (Service = "ftp" ? 1 : (Service = "gopher" ? 2 : 3)) ; INTERNET_SERVICE_xxx
      , "uint", (FtpPassive != 0 ? 0x08000000 : 0) ; INTERNET_FLAG_PASSIVE
      , "uint", 0)
   return hConnection
}

; ------------------------------------------------------------------------------
; Creates a directory on a FTP server.
;
; param hConnection [in]
;   A valid connection handle returned by an INetConnect call (using Type="ftp").
; param Directory [in]
;   The name of the directory to be created. This can be a fully qualified path
;   or a name relative to the current directory.
; return
;   [bool] true if the function succeeds, otherwise false
;
FtpCreateDirectory(hConnection, Directory)
{
   return DllCall("wininet\FtpCreateDirectoryA", "uint", hConnection, "str", Directory)
}

; ------------------------------------------------------------------------------
; Sets the current working directory for a specified FTP session.
;
; param hConnection [in]
;   A valid connection handle returned by an INetConnect call (using Type="ftp").
; param Directory [in]
;   The name of the directory to become the current working directory. This can be a fully qualified path
;   or a name relative to the current directory.
; return
;   [bool] true if the function succeeds, otherwise false
;
FtpSetCurrentDirectory(hConnection, Directory)
{
   return DllCall("wininet\FtpSetCurrentDirectoryA", "uint", hConnection, "str", Directory)
}

; ------------------------------------------------------------------------------
; Gets the current working directory of a specified FTP session.
;
; param hConnection [in]
;   a valid connection handle returned by an INetConnect call (using Type="ftp")
; param Directory [in]
;   a variable that receives the absolute path of the current directory
; return
;   [bool] true if the function succeeds, otherwise false
;
FtpGetCurrentDirectory(hConnection, ByRef @Directory)
{
   len := 261   ; MAX_PATH 260
   VarSetCapacity(@Directory, len)

   result := DllCall("wininet\FtpGetCurrentDirectoryA", "uint", hConnection, "str", @Directory, "uint*", len)
   VarSetCapacity(@Directory, -1)
   return result
}

; ------------------------------------------------------------------------------
; Uploads a file to a FTP server (the remote file is overwritten if it already exists).
;
; param hConnection [in]
;   a valid connection handle returned by an INetConnect call (using Type="ftp")
; param LocalFile [in]
;   name of the local file to upload
; param RemoteFile [in]
;   name of the remote file to create (when empty, the remote file created will have the same name than the local one)
; param TransferType [in]
;   "A" for ascii transfert or "B" (default) for binary mode
; return
;   [bool] true if the function succeeds, otherwise false
;
FtpPutFile(hConnection, LocalFile, RemoteFile="", TransferType="B")
{
   return DllCall("wininet\FtpPutFileA"
      , "uint", hConnection
      , "str", LocalFile
      , "str", (RemoteFile != "" ? RemoteFile : LocalFile)
      , "uint", (TransferType == "A" ? 1 : 2)   ; FTP_TRANSFER_TYPE_ASCII or FTP_TRANSFER_TYPE_BINARY
      , "uint", 0)
}

; ------------------------------------------------------------------------------
; Deletes a file stored on a FTP server
;
; param hConnection [in]
;   a valid connection handle returned by an INetConnect call (using Type="ftp")
; param File [in]
;   the name of the file to be deleted
; return
;   [bool] true if the function succeeds, otherwise false
;
FtpDeleteFile(hConnection, File)
{
   return DllCall("wininet\FtpDeleteFileA", "uint", hConnection, "str", File)
}

I didn't really try to understand INet.ahk, I just mercilessly deleted the functions I didn't use. The script expects the filename (and path) to be uploaded.

Not particularly elegant, but it works! 8)

Benny-D
  • Members
  • 1485 posts
  • Last active: Sep 27 2016 11:23 PM
  • Joined: 29 Feb 2008
Thank you Bjalf. I'll try your way.