downloading file using SFTP with VBA - vba

My objective is to download, not upload a file from an SFTP server, and I am trying to adapt the code from another question on this site to do so (I pasted the code below for your convenience).
I downloaded PSFTP from Putty. PSFTP closes when I try to connect using the following command line:
open username:password#server.com.port:1111
I have three questions:
Is something wrong with my command line? If not then what could be the problem?
As far as I know SFTP would normally utilize get/put commands, but i don't see a put command in the code below, so I don't understand where I should enter the get command to download the file instead of uploading it (which is what the code below is supposed to be doing).
Is it correct that pRemotePath is the location of the file on the SFTP server, and pFile is the location I want the file downloaded to?
A simple explanation would be very much appreciated.
Public Sub SftpGet()
Const cstrSftp As String = """C:\Users\Ron\UtilityTools\psftp.exe"""
Dim strCommand As String
Dim pUser As String
Dim pPass As String
Dim pHost As String
Dim pFile As String
Dim pRemotePath As String
pUser = "uid"
pPass = "PW"
pHost = "dns"
pFile = "C:\Users\Ron\activity.txt"
pRemotePath = "Z:/activity.log"
strCommand = cstrSftp & " -sftp -l " & pUser & " -pw " & pPass & _
" " & pFile & " " & pHost & ":" & pRemotePath
Debug.Print strCommand
Shell strCommand, 1 ' vbNormalFocus '
End Sub

I think you should start with a Windows command prompt session. Work out the details of your command line there, as I suggested in an answer to a similar question: SFTP upload with VBA. Once you have a command line which works there, it will be very easy to execute that same command from VBA.
I've never used Putty's psftp.exe tool, only pscp.exe, so I can't offer help about how to construct your psftp.exe command line. One thing I noticed in Putty's documentation is that PSFTP (pscp.exe) can only work with a SSH-2 server --- if your target server supports only SSH-1, PSFTP will not work.
I think it would be worthwhile for you to review the Putty documentation at that link.

Related

Is there is any way to unzip the password protected pkzip files using vba [duplicate]

i am facing a trouble here,Could you please tell me how to unzip a password protected field in vbscript?
I have a code which runs perfectly,but it asking password each time when it runs
pathToZipFile="C:\folder.zip"
extractTo="C:\"
set sa = CreateObject("Shell.Application")
set filesInzip=sa.NameSpace(pathToZipFile).items
sa.NameSpace(extractTo).CopyHere(filesInzip)
I need a code which will not ask password in run,Please help,Thank you!!
AFAIK the Shell.Application object doesn't support providing a password. Try 7-zip instead:
pass = "..."
zipfile = "your.zip"
CreateObject("WScript.Shell").Run "7za.exe x -p" & pass & " " & zipfile, 0, True
If necessary add the path to 7za.exe and/or file.zip. If the path contains spaces, you'll also need to put double quotes around it, e.g. like this:
Function qq(str) : qq = Chr(34) & str & Chr(34) : End Function
zipfile = qq("C:\path\with spaces\to\your.zip")

How to execute Batch File while passing parameters from Excel

I am trying run a batch file placed at a particular path. The file requires user inputs for which I want the parameters to be passed from Excel cells. This execution of the batch file within Excel should happen by usage of click command button.
I am new to VBA. I tried the following code, but on clicking the button nothing is happening.
Private Sub CommandButton2_Click()
sid = Excel.Worksheets("Sheet1").Range("I8").Value
user = Excel.Worksheets("Sheet1").Range("I9").Value
Password = Excel.Worksheets("Sheet1").Range("I10").Value
msg = "hi"
Shell ("CMD.EXE /c C:\Users\shashank.b03\Desktop\test_CMD.bat" & sid &" "& user &" "& password &" ")
End Sub
Here is an example which I have tested and should work fine for you. It just calls the shell command and passes it a command string.
You can change the path where your batch file is in the string & if you don't want to show the shell window when you're running this use vbHide instead of vbNormalFocus.
You'll just have to change this a bit to put the cell values into the sid, user and password variables.
Hope this helps.
Dim sid As String
Dim user As String
Dim password As String
CommandString = "c:\test.bat" + " " + sid + " " + user + " " + password
Call Shell("cmd.exe /c" & CommandString, vbNormalFocus)
Here is a more basic example of using parameters and a batch file from shell.
Save the following as test.bat
set arg1=%1
echo HELLO %1!
pause
Put this code inside a button or some other component in excel;
Private Sub CommandButton1_Click()
Dim sid As String
sid = "Shashank"
CommandString = "c:\test.bat" + " " + sid
Call Shell("cmd.exe /c" & CommandString, vbNormalFocus)
End Sub
Make sure that the path where the batch file is saved is the same as the one in commandstring.
When this is run, you'll see the string held in the variable sid is passed to the batch file and used. You should be able to get it working from here.
Hope this helps

Vba to call a powershell script or .bat file

I have a line to call a powershell script and it works but the powershell windows gets closed without it working.
the code is, any ideas?
Additionally I would like it to be able to run .bat files (I tried Shell ( & pathcrnt & "\GUI-getuserpropertiesV2.10.ps1" & pathcrnt) bit I get the same error.
Sub CallBatch()
Dim pathcrnt As String
pathcrnt = ActiveWorkbook.Path
Shell ("PowerShell " & pathcrnt & "\GUI-getuserpropertiesV2.10.ps1" & pathcrnt)
End Sub
Please see the link below and make sure you have permissions for the machine.
http://www.tek-tips.com/viewthread.cfm?qid=1585510
I don't know about your setup or security, so if you encounter an error, search for 'PS permissions', or something along those lines. The VBA script will definitely work!
If you insert a space after .ps1 it should work:
Sub CallBatch()
Dim pathcrnt As String
pathcrnt = ActiveWorkbook.Path
Shell "PowerShell " & pathcrnt & "\GUI-getuserpropertiesV2.10.ps1 " & pathcrnt
End Sub
Imagine the resulting string; for pathcrnt C:\Windows it would be this: "PowerShell C:\Windows\GUI-getuserpropertiesV2.10.ps1C:\Windows"
You also might want to enclose the path elements with double quotes to prevent spaces messing with your parameters, like this:
Shell "PowerShell """ & pathcrnt & "\GUI-getuserpropertiesV2.10.ps1"" """ & pathcrnt & """"
Since double quotes also are string delimiters in VBA you have to escape them with another double quote.

Output text File creation/saving VBA code timing issue

Problem Summary: Creating a text file for FTP commands is not finishing by the time the command file needs to be called. It won't trap with a "if file exists". How to make sure the file is created before continuing with the code?
Details: I'm working on an portion of code in my Excel workbook to FTP some files. To do that, I'm creating a FTPcmd.txt file via code containing the FTP commands, closing the file and then shelling the FTP command in the CMD window. It looks like the command file is taking too long to complete the write and, therefore, I'm getting an "Permission Refused" error. The FTP log says "Error opening script file C:\temp\FTPcmd.txt." I am error checking to see if the file exists, but I think the file shows up as existing after the open statement, not the close. I'm not hitting the else statement in the DIR <>"" The IsFileOpen function was found on "http://www.vbaexpress.com/kb/getarticle.php?kb_id=468 VBA Express : Excel - Check If a File Is Already Open"
I don't believe it's a problem ShellWait problem. I need the file to write before I call the Shell.
If I step through it manually, it works, after I see the file appear in the directory.
I'm also piping the FTP output to a file and reading it back in for success/failure messaging in a similar manner and I'm getting the same problem with that.
Anyone have any ideas? Thanks in advance!
Open temppath & "FTPcmd.txt" For Output As #2
Print #2, "user " & FSOUserName
Print #2, FSOpw
Print #2, "lcd " & temppath
Print #2, "cd public_html"
Print #2, "binary"
Print #2, "mput " & Chr(34) & "index.htm" & Chr(34)
Print #2, "cd .."
Print #2, "cd public_ftp"
Print #2, "mput " & Chr(34) & myfilename & Chr(34)
Print #2, "bye"
Close #2
Start = Timer
FTPlooper:
If Timer - Start > 30 Then saveme = 1: Text = Text & " FTP Failure": GoTo failpoint
If Dir(temppath & "FTPcmd.txt") <> "" And IsFileOpen(temppath & "FTPcmd.txt") = False Then
Shell "cmd /c ftp -n -i -g -s:" & temppath & "FtpCmd.txt " & FSOHostURL & ">" & temppath & "ftpout.txt 2>&1"
Else
GoTo FTPlooper
End If
Here's the function I'm using to see if the file is open.
Code:
Function IsFileOpen(FileName As String)'http://www.vbaexpress.com/kb/getarticle.php?kb_id=468
Dim iFilenum As Long
Dim iErr As Long
On Error Resume Next
iFilenum = FreeFile()
Open FileName For Input Lock Read As #iFilenum
Close iFilenum
iErr = Err
On Error GoTo 0
Select Case iErr
Case 0: IsFileOpen = False
Case 70: IsFileOpen = True
Case Else: Error iErr
End Select
End Function
Output of FTPout.txt:
Error opening script file C:\Users\Theresa\Downloads\FTPcmd.txt.
Transfers files to and from a computer running an FTP server service
(sometimes called a daemon). Ftp can be used interactively.
FTP [-v] [-d] [-i] [-n] [-g] [-s:filename] [-a] [-A] [-x:sendbuffer]
[-r:recvbuffer] [-b:asyncbuffers] [-w:windowsize] [host]
-v Suppresses display of remote server responses. -n
Suppresses auto-login upon initial connection. -i Turns
off interactive prompting during multiple file
transfers. -d Enables debugging. -g Disables filename globbing (see GLOB command). -s:filename
Specifies a text file containing FTP commands; the
commands will automatically run after FTP starts. -a Use any local interface when binding data connection. -A login as anonymous. -x:send sockbuf Overrides the default SO_SNDBUF size of 8192. -r:recv sockbuf Overrides the
default SO_RCVBUF size of 8192. -b:async count Overrides the
default async count of 3 -w:windowsize Overrides the default
transfer buffer size of 65535. host Specifies the host
name or IP address of the remote
host to connect to.
Notes:
- mget and mput commands take y/n/q for yes/no/quit.
- Use Control-C to abort commands.

Running powershell scripts from within a .NET windows app

I'm needing to run scripts from within a vb.net windows app.
I've got the scripts running in the background fine;
Using MyRunSpace As Runspace = RunspaceFactory.CreateRunspace()
MyRunSpace.Open()
Using MyPipeline As Pipeline = MyRunSpace.CreatePipeline()
MyPipeline.Commands.AddScript("import-module -name " & moduleName &
vbCrLf &
"(get-module -name " & moduleName & ").version")
Dim results = MyPipeline.Invoke()
'Do something with the results
End Using
MyRunSpace.Close()
End Using
However, i now need to be able to have the powershell run (not in the background) eg. When prompts occur;
Set-ExecutionPolicy unrestricted
I'm currently looking into the Microsoft.PowerShell.ConsoleHost namespace to see if i can use something like;
Dim config = RunspaceConfiguration.Create
ConsoleShell.Start(config, "Windows PowerShell", "", New String() {""})
Can anyone advise me please???
EDIT: I've fudged it a bit with this;
Public Function RunPowershellViaShell(ByVal scriptText As String) As Integer
Dim execProcess As New System.Diagnostics.Process
Dim psScriptTextArg = "-NoExit -Command ""& get-module -list"""
'Dim psScriptTextArg = "-NoExit -Command ""& set-executionPolicy unrestricted"""
'Dim psScriptTextArg = ""-NoExit -Command """ & scriptText & """"
execProcess.StartInfo.WorkingDirectory = Environment.SystemDirectory & "\WindowsPowershell\v1.0\"
execProcess.StartInfo.FileName = "powershell.exe"
execProcess.StartInfo.Arguments = psScriptTextArg
execProcess.StartInfo.UseShellExecute = True
Return execProcess.Start
End Function
But there's gotta be a better way??
There is a distinction between the PowerShell engine and its host. What you're wanting is to run the engine within your application but then fire up a separate host (which also is hosting the PowerShell engine) to handle prompts. You might want to look into modifying your application to act as a host itself. You could then react to prompts (read-host) and pop dialog boxes or whatever. Take a look at this relevant PowerShell namespace. Also check out this blog post on creating a simple PSHost.