我可以使用以下代码在CMD
窗口中从SFTP下载文件:
WinSCP.com
# Connect to the host and login using password
open user:pw@address
# get all the files in the remote directory and download them to a specific local directory
lcd C:\Users\xx\Desktop
get *.xlsx
# Close and terminate the session
exit
我在线搜索并发现我可以将这些代码放在bat
文件中并使用
Call Shell("cmd.exe /c C:\Users\xx\Desktop\WinSCPGet.bat", 1)
但是,只有bat文件WinSCP.com
的第一行正在执行。它将弹出cmd
窗口,显示此信息,而不执行任何其他操作。
如何一次执行所有行?
由于
答案 0 :(得分:4)
您拥有的代码不是Windows批处理文件。这是一个Windows命令,后跟WinSCP命令。第一个命令运行winscp.com
应用程序,然后它坐下并等待输入。如果你最终关闭它,Windows命令解释器(cmd.exe
)将继续执行剩余的命令,失败最多,因为它们不是Windows命令。另请参阅WinSCP script not executing in batch file和WinSCP常见问题解答Why are some WinSCP scripting commands specified in a batch file not executed/failing?
因此,您必须将命令(open
保存到exit
)保存到WinSCP脚本文件(例如script.txt
)并使用/script
switch执行脚本:< / p>
Call Shell("C:\path\winscp.com /ini=nul /script=c:\path\script.txt")
或者,使用/command
switch:
Call Shell("C:\path\winscp.com /ini=nul /command ""open user:pw@address"" ""lcd C:\Users\xx\Desktop"" ""get *.xlsx"" ""exit""")
关于引号:使用/command
开关,您必须将每个命令括在双引号中。在VBA字符串中,要使用双引号,您必须通过加倍来逃避它。
另请注意,您通常应使用/ini=nul
switch至isolate the WinSCP script run from your WinSCP configuration。这样,您还可以确保脚本将在其他计算机上运行。您的脚本不会,因为它缺少-hostkey
switch到verify the SSH host key fingerprint。使用/ini=nul
将帮助您实现这一目标。
您可以拥有WinSCP GUI generate complete command-line(包括-hostkey
)。
答案 1 :(得分:2)
我喜欢这个小而紧凑的程序,并在我自己的项目中使用它。无需临时文件。快速可靠。
将字符串src
(绝对文件路径)解析为uploadImageByFTP
。等等C:\ Users \ user \ Desktop \ image.jpg,文件将被上传。
替换:
<username>
<password>
使用FTP密码<hostname>
使用FTP-hostname(等example.com)<WinSCP.com path>
在WinSCP客户端上有路径(等等C:\ Program Files(x86)\ WinSCP \ WinSCP.com。警告:WinSCP.com
而不是{ {1}})WinSCP.exe
在您的FTP客户端上有路径(等等/ httpdocs / wp-content / uploads)-
<FTP-path>
-
Sub uploadImageByFTP(src As String)
Dim script As Object: Set script = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
'Not empty
If (src <> vbNullString) Then
'Execute script
script.Run _
"""<WinSCP.com path>"" " + _
"/ini=nul " + _
"/command " + _
"""open ftp://<username>:<password>@<hostname>/"" " + _
"""cd <FTP-path>"" " + _
"""put " & """""" & src & """""" & """ " + _
"""close"" " + _
"""exit""", windowStyle, waitOnReturn
End If
End Sub
比默认WScript.Shell
更强大,因为您可以追加Shell()
- 命令;这告诉VBA,在文件上传到FTP服务器之前不允许进一步执行。
如果您不希望在每次执行时打开命令提示符,请将waitOnReturn
更改为0.