From Python run WinSCP commands in console

為{幸葍}努か 提交于 2020-12-04 05:32:36

问题


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

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)

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?

I also tried replacing winscp.exe /console for winscp.com /command.

Is there any way to do this?


回答1:


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;
  • winscp.com instead of winscp.exe, as winscp.com is a console application, so its output can be read by Python.



回答2:


So when using the /script option you should specify a file containing the batch commands.

To specify all the commands on the command line as you're doing, use the /command option instead of /script.



来源:https://stackoverflow.com/questions/56449699/from-python-run-winscp-commands-in-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!