[英]From Python run WinSCP commands in console
I have to run a few commands of WinSCP from a Python class using subprocess.我必须使用子进程从 Python 类运行 WinSCP 的一些命令。
The goal is to connect a local Windows machine and a Windows server with no FTP installed and download some files.目标是连接本地 Windows 计算机和未安装 FTP 的 Windows 服务器并下载一些文件。 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)
With this I get it to open the WinSCP console and connect to the server, but it doesn't execute the get
command.有了这个,我可以打开 WinSCP 控制台并连接到服务器,但它不执行
get
命令。 Is the problem because the get
is executed on the Windows console and not in the WinSCP console?问题是因为
get
是在 Windows 控制台上执行的,而不是在 WinSCP 控制台中执行的吗?
I also tried replacing winscp.exe /console
for winscp.com /command
.我还尝试将
winscp.exe /console
替换为winscp.com /command
。
Is there any way to do this?有没有办法做到这一点?
So when using the /script
option you should specify a file containing the batch commands.因此,当使用
/script
选项时,您应该指定一个包含批处理命令的文件。
To specify all the commands on the command line as you're doing, use the /command
option instead of /script
.要在执行时指定命令行上的所有命令,请使用
/command
选项而不是/script
。
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())
The code uses:代码使用:
/command
switch to specify commands on WinSCP command-line; /command
开关来指定命令上的WinSCP命令行;winscp.com
instead of winscp.exe
, as winscp.com
is a console application, so its output can be read by Python . winscp.com
而不是winscp.exe
,因为winscp.com
是一个控制台应用程序,所以它的输出可以被Python 读取。 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 .
请参阅subprocess.Popen 中的 Python 双引号在执行 WinSCP 脚本时不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.