从 Python 在控制台中运行 WinSCP 命令

From Python run WinSCP commands in console(从 Python 在控制台中运行 WinSCP 命令)

本文介绍了从 Python 在控制台中运行 WinSCP 命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用子进程从 Python 类运行一些 WinSCP 命令.

I have to run a few commands of WinSCP from a Python class using subprocess.

目标是连接本地 Windows 计算机和未安装 FTP 的 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.

I also tried replacing winscp.exe /console for 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 开关 指定commands 在 WinSCP 命令行上;
  • winscp.com 而不是 winscp.exe,因为winscp.com是一个控制台应用程序,所以它的输出可以被Python读取.
  • /command switch to specify commands on WinSCP command-line;
  • winscp.com instead of winscp.exe, as winscp.com is a console application, so its output can be read by Python.

虽然使用数组作为参数是行不通的,但如果命令参数中有空格(如文件名).然后你必须自己格式化完整的命令行.请参阅Python 双引号在 subprocess.Popen 在执行 WinSCP 脚本时不起作用.

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 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:从 Python 在控制台中运行 WinSCP 命令

基础教程推荐