从Python在控制台中运行WinSCP命令 [英] From Python run WinSCP commands in console
问题描述
我必须使用子进程从Python类运行WinSCP的一些命令.
I have to run a few commands of WinSCP from a Python class using subprocess.
目标是连接未安装FTP的本地Windows计算机和Windows服务器并下载一些文件.这就是我尝试过的
The goal is to connect a local Windows machine and a Windows server with no FTP installed and download some files. This is what I tried
python
proc = subprocess.Popen(['WinSCP.exe', '/console', '/WAIT', user:password@ip:folder , '/WAIT','get' ,'*.txt'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
通过此操作,我可以打开WinSCP控制台并连接到服务器,但是它不执行 get
命令.是不是因为 get
是在Windows控制台而不是WinSCP控制台上执行的?
With this I get it to open the WinSCP console and connect to the server, but it doesn't execute the get
command. Is the problem because the get
is executed on the Windows console and not in the WinSCP console?
我还尝试将 winscp.exe/console
替换为 winscp.com/command
.
有什么办法吗?
推荐答案
如果要在不生成脚本文件的情况下执行操作,则可以使用如下代码:
If you want do without generating a script file, you can use a code like this:
import subprocess
process = subprocess.Popen(
['WinSCP.com', '/ini=nul', '/command',
'open ftp://user:password@example.com', 'get *.txt', 'exit'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for line in iter(process.stdout.readline, b''): # replace b'' with '' for Python 2
print(line.decode().rstrip())
代码使用:
-
/command
开关以指定命令; -
winscp.com
而不是winscp.exe
,因为winscp.com
是控制台应用程序,因此Python可以读取其输出.
/command
switch to specify commands on WinSCP command-line;winscp.com
instead ofwinscp.exe
, aswinscp.com
is a console application, so its output can be read by Python.
尽管在命令参数中有空格(例如文件名),但是将数组用作参数是行不通的.然后,您将必须自行格式化完整的命令行.请参见子进程中的Python双引号.执行WinSCP脚本时,Popen不起作用.
Though using the array for the arguments won't work, if there are spaces in command arguments (like file names). Then you will have to format the complete command-line yourself. See Python double quotes in subprocess.Popen aren't working when executing WinSCP scripting.
这篇关于从Python在控制台中运行WinSCP命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!