GithubHelp home page GithubHelp logo

lipkau / winscp.ahk Goto Github PK

View Code? Open in Web Editor NEW
18.0 4.0 3.0 10.76 MB

Lib allows the use of WinSCP in AHK

Home Page: http://lipkau.github.io/WinSCP.ahk

License: GNU General Public License v2.0

AutoHotkey 98.58% Batchfile 1.42%
winscp ahk ftp

winscp.ahk's Introduction

Description

This Lib allows the use of WinSCP in AHK by creating a wrapper class for WinSCPnet.dll (can be donwloaded here).

WinSCP .NET & COM Library Documentation

Table of Contents

Example

Loading WinSCP.ahk

  1. The DLL file has to be registered. This is done with

    %WINDIR%\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe WinSCPnet.dll /codebase <path_to>WinSCPnet.dll %WINDIR%\Microsoft.NET\Framework64\v4.0.30319\RegAsm.exe WinSCPnet.dll /codebase <path_to>WinSCPnet.dll

or by running the included WinSCP_regDLL.cmd file
The commands must be run with Admin permissions (elevated)
2. The library can be included using #Inclulde or by placing the file inside Library Folders.

Connecting to Server

Using normal FTP

  FTPSession := new WinSCP
  try
    FTPSession.OpenConnection("ftp://myserver.com","username","password")
  catch e
    msgbox % "Oops. . . Something went wrong``n" e.Message

Using FTP with SSL

  FTPSession := new WinSCP
  try
  {
    FTPSession.Hostname		:= "ftp://myserver.com"
    FTPSession.Protocol 		:= WinSCPEnum.FtpProtocol.Ftp
    FTPSession.Secure 		:= WinSCPEnum.FtpSecure.ExplicitSsl
    FTPSession.User			:= "MyUserName"
    FTPSession.Password		:= "P@ssw0rd"
    FTPSession.Fingerprint    := "xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx" ;set to false to ignore server certificate
	FTPSession.OpenConnection()
  } catch e
    msgbox % "Oops. . . Something went wrong``n" e.Message

Handling files

Upload a single file

  FTPSession := new WinSCP
  try
  {
    FTPSession.OpenConnection("ftp://myserver.com","username","password")
    
    fName := "Windows10_InsiderPreview_x64_EN-US_10074.iso"
    fPath := "C:\temp"
	tPath := "/Win10beta/"
	if (!FTPSession.FileExists(tPath))
	  FTPSession.CreateDirectory(tPath)
    FTPSession.PutFiles(fPath "\" fName, tPath)
  } catch e
    msgbox % "Oops. . . Something went wrong``n" e.Message  

Download file

  FTPSession := new WinSCP
  try
  {
    FTPSession.OpenConnection("ftp://myserver.com","username","password")
    
    fName := "Windows10_InsiderPreview_x64_EN-US_10074.iso"
    lPath := "C:\temp"
	rPath := "/Win10beta/"
	if (FTPSession.FileExists(rPath "/" fName))
      FTPSession.GetFiles(rPath "/" fName, lPath)
  } catch e
    msgbox % "Oops. . . Something went wrong``n" e.Message  

Get File Information

  FTPSession := new WinSCP
  try
  {
    FTPSession.OpenConnection("ftp://myserver.com","username","password")
    
    FileCollection := t.ListDirectory("/")
    for file in FileCollection.Files {
	  if (file.Name != "." && file.Name != "..")
        msgbox % "Name: " file.Name "``nPermission: " file.FilePermissions.Octal "``nIsDir: " file.IsDirectory "``nFileType: " file.FileType "``nGroup: " file.Group "``nLastWriteTime: " file.LastWriteTime "``nLength: " file.Length "``nLength32: " file.Length32 "``nOwner: " file.Owner
  } catch e
    msgbox % "Oops. . . Something went wrong``n" e.Message 

More

More example will be available in the wiki once it's set up

Authors/Contributors

Documentation

Git Repo Wiki yet to be written

winscp.ahk's People

Contributors

lipkau avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

winscp.ahk's Issues

Function for the registration of WinSCPnet.dll

Hello Lipkau,

thank you for your library.
I did not find a problem, I found an idea, and so I have designed a function that solves the registration of WinSCPnet.dll via Autohotkey and the Windows scripting shell.

A simple user prompt is integrated in the function, which outputs everything necessary for the registration process and asks the user for confirmation. The function can also be executed silently, e.g. because the registration of the assembly must be cancelled after use.
There is no parameter to switch on the silent mode. It is automatically recognised if the user dialogue is not to be displayed (user_dialog := false) and the path to WinSCPnet.DLL is correct.
The function was designed for external calls. But it could also be placed as a method in your library.
I could not test all individualities so far. Therefore, there may well be some programme errors.

Greetings, hope you find necessary,
Ixiko

; to test the registration of WinSCP, remove the commenting of the next line
;~ result := RegisterWinSCP()


RegisterWinSCP(dllpath:="", user_dialog:=true, unregister:=false) {  	; WinSCPnet.dll COM registration/unregistration helper

	/*	This can be used to register or deregister WinSCP with .NET.

		The function can be called in two modes.
		The first mode with simple user guidance.
		The second is a silent mode, if registration and deregistration are to be carried out without prompting.
		The modes are recognised by the parameter values passed (dllpath, user_dialog or unregister).

		The user mode has two dialogs. Each dialogue is displayed separately to enable individual dialogue design.
		Unless the dialogue display is suppressed with the parameter value of unregister.

	*/

	__ := Chr(0x22)

	batch =
		(LTRIM
			echo register WinSCPnet.dll 32bit
			`%WINDIR`%\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe #WinSCPnet.dll# /codebase /verbose ## /tlb
			echo.
			echo - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
			echo register WinSCPnet.dll 64bit
			`%WINDIR`%\Microsoft.NET\Framework64\v4.0.30319\RegAsm.exe #WinSCPnet.dll# /codebase /verbose ## /tlb
			echo.
			echo.
		)

  ; needed to save the state of the action
	SetRegView, % (A_PtrSize=8 ? 64 : 32)
	RegRead, isRestarted, % "HKEY_CURRENT_USER\SOFTWARE\" A_ScriptName, runAsAdmin

  ; prerecogniton of silentmode
	silentmode := (unregister || (!user_dialog && FileExist(dllpath))) 
					&& (A_IsAdmin || full_command_line~=" /restart(?!\S)") ? true : false

  ; script must be executed in administrator mode
	full_command_line := DllCall("GetCommandLine", "str")
	if !(A_IsAdmin || RegExMatch(full_command_line, " /restart(?!\S)")) {

		runasAdmin := "`n!  !   Run as administrator   !  !`n"
					. "Administrator privileges are`nrequired to register the assembly. `n`n"

	   ; return if silentmode is enabled
		If silentmode
			return -1
	}

  ; check the WinSCP registration
	try winscp := ComObjCreate("WinSCP.Session")
	catch {

	  ; User dialogs
		If !silentmode {


		  ; user dialog
			If  !isRestarted && (user_dialog||!FileExist(dllpath)||!A_IsAdmin||full_command_line~=" /restart(?!\S)")  {

				MsgBox, 0x1024, % RegExReplace(A_ScriptName, "\.ah.*$")
							 , % 	"--------------------------------------`n"
							 .    	"              WinSCP Class`n"
							 .	"--------------------------------------`n"
							 .	"`n"
				 			 .	"The WinSCP.DLL file has to be`n"
							 . 	"registered for use with COM.`n"
							 .	runasAdmin
							 .	"Perform the registration now?"
				IfMsgBox, No
					ExitApp

			}

		  ; run as Admin
			If runasAdmin {
				RegWrite REG_SZ, % "HKEY_CURRENT_USER\SOFTWARE\" A_ScriptName, runAsAdmin, It must! It must!
				try {
				Run % A_IsCompiled ? ("*RunAs " . __ .  A_ScriptFullPath . __ . " /restart") 
						   : ("*RunAs " . __ . A_AhkPath . __ . " /restart " . __ . A_ScriptFullPath . __)
				}
				ExitApp
			}

		 ; deletes registry key, if available
			else {
				If isRestarted
					RegDelete % "HKEY_CURRENT_USER\SOFTWARE\" A_ScriptName, runAsAdmin
			}

		  ; get the file path
			If !FileExist(dllpath) {

				FileSelectFile, ffp, 1, % A_ScriptDir "\..\dll", % "Path to WinSCPnet.dll", WinSCPnet.dll
				If (!ffp || !FileExist(ffp)) {

					MsgBox, 0x1024, % RegExReplace(A_ScriptName, "\.ah.*$")
						  , % 	"----------------------------------------------------------------n"
						  .    	"                          WinSCP Class`n"
						  .		"---------------------------------------------------------------`n"
						  .		"`n"
						  .		"You have not selected a valid path to WinSCPnet.dll.`n"
						 .		"Do you want to cancel the COM registration?"
					IfMsgBox, Yes
						ExitApp

					RegisterWinSCP(dllpath, user_dialog, unregister)

				}

				dllpath := ffp

			}

		}

	 ; close winscp Connection
		If isObject(winscp)
			winscp.CloseConnection()

	  ; for the registration process
		batch := StrReplace(batch, "##", "")
		batch := StrReplace(batch, "#WinSCPnet.dll#", __ dllpath __)

	}

 ; for the unregistration process
	If unregister {
		batch := StrReplace(batch, "##", "/unregister")
		batch := StrReplace(batch, "#", "")
	}
	
  ; a console gui
	If !silentmode {
		Gui, +hwndhOut
		Gui, Color, 0x0, 0x0
		Gui, Margin, 0, 0
		Gui, Font, s10 q5 bold, Consolas
		Gui, Add, Edit, xm ym w800 h350 c00D500 hwndhEdit
		WinSet, Style 	, 0x500110C4, % "ahk_id " hEdit
		WinSet, ExStyle	, 0x00000000, % "ahk_id " hEdit
		Gui, Show,, Console output
		EditAppend(hEdit, cmdline)
	}

  ; execute batch line by line
	shell := ComObjCreate("WScript.Shell")
	For each, line in StrSplit(batch, "`n", "`r") {
		exec 	:= shell.Exec(ComSpec " /C " line)
		txt 	:= exec.StdOut.ReadAll()
		out 	.= txt
		!silentmode ? EditAppend(hEdit, txt) : ""
		sleep 100
	}

  ; check WinSCP registration
	try winscp := ComObjCreate("WinSCP.Session")
	catch {
		failure := true
		; get error message for returning
		If !silentmode {
			EditAppend(hEdit, "The registration process was successful.")
			SetTimer, MoveConsole, -50
			MsgBox, 0x1030, % RegExReplace(A_ScriptName, "\.ah.*$")
				  , % 	"--------------------------------------------`n"
				  .    	"                 WinSCP Class`n"
				  .		"--------------------------------------------`n"
				  .		"`n"
				  .		"The registration of WinSCPnet.dll`n"
				  . 		"was not successful. The error output`n"
				  . 		" can be found in the console."
		}
	}

		clipboard := batch . out
  ; Registration was successful - show it!
	If !failure && !silentmode {
		EditAppend(hEdit, "The registration process was not successful.")
		sleep 15000
	}

  ; close all
	shell := ""
	DllCall("FreeConsole")
	Process, Close, %cPid%
	Gui, Destroy

return failure ? 0 : 1

MoveConsole:
	hMB := WinExist(RegExReplace(A_ScriptName, "\.ah.*$") " ahk_class #32770")
	WinGetPos, mx, my, mw, mh	, % "ahk_id " hMB
	WinGetPos, wx, wy, ww, wh	, % "ahk_id " hOut
	WinMove, % "ahk_id " hOut	,, % wx-ww//2
	WinMove, % "ahk_id " hMB	,, % mx+mw//2
return
}

EditAppend(hEdit, txt) {
	L :=	DllCall("SendMessage", "Ptr",hEdit, "UInt",0x0E, "Ptr",0 , "Ptr",0)     	; WM_GETTEXTLENGTH
			DllCall("SendMessage", "Ptr",hEdit, "UInt",0xB1, "Ptr",L , "Ptr",L)       	; EM_SETSEL
			DllCall("SendMessage", "Ptr",hEdit, "UInt",0xC2, "Ptr",0, "Str",txt )   	; EM_REPLACESEL
}

Fantastic job here

Regular FTP works great. Your examples are simple to understand and implement. I was wondering if you have any plans to add Sftp implementation? Is the dll file your creation or from WinSCP site? If you believe Sftp implementation is already available in this build, can you add an example for that? I have had no luck here. Thanks! Jules Again, great job!

How to implement Cancel from the filetransferprogresseventargs Class in file_upload_with_progressbar.ahk Example

I'm trying to add in a cancel option to the example you provided by using the example that Martin (the WinSCP dev) suggested here for C#. StackoverflowLink However, it does not seem to work here. Example of what I've added.

session_FileTransferProgress(sender, e)
{
	;Parse e Properties
	RegExMatch(e.FileName, ".*\\(.+?)$", match)
	FileName        := match1
	CPS             := Round(e.CPS / 1024)
	FileProgress    := Round(e.FileProgress * 100)
	OverallProgress := Round(e.OverallProgress * 100)
	action          := (e.Side==0) ? "Uploading" : "Downloading"
	
	;Change GUI elements
	GuiControl,, txtTitle, % action " @ " CPS " kbps"
	GuiControl,, edtFileName, % FileName
	GuiControl,, proFileName, % FileProgress
	GuiControl,, proOverall, % OverallProgress
        if (FileProgress > 50)
        {
            try {
                        e.Cancel := "true" ; I've tried boolean values of 0 and 1. I've tried true as both a string and an expression.
                      ; e.Cancel           ; I've also tried this. commented out here to avoid confusion.
             } catch e {
                       ; unfortunately I haven't been able to catch the error either. Not sure if there even is a way to view the error as ahk debug doesn't show a message.
           }
        }
	if (OverallProgress==100)
		GuiControl, Enable, btnClose
	
	;Show GUI
	Gui, Show, , File Transfere
}

This is obviously just a simple test, once FileProgress is over half way done, cancel the transfer. Unfortunately, this does not cancel the transfer.

Any thoughts on what I'm doing wrong?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.