Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From Python run WinSCP commands in console

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?

like image 251
Diego Avatar asked May 11 '26 11:05

Diego


1 Answers

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:[email protected]', '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.

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.

like image 90
Martin Prikryl Avatar answered May 14 '26 02:05

Martin Prikryl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!