How to run Python script in FTP server using Python?

Viewed 1809

I want to run Python script located on server using another Python script with FTP.

Below is my (hello.py) file location I want to run.

enter image description here

from ftplib import FTP

ftp = FTP('host')
ftp.login(user='user', passwd = 'password')

print("successfully connected")
print ("File List:")
files = ftp.dir()
print (files)

enter image description here

4 Answers

You could use a system() call:

system('python hello.py')

Note: use the full path to the hello.py script.

An alternative is to use the subprocess module.

You cannot run anything on an FTP server, no matter how.
See a similar question: Run a script via FTP connection from PowerShell
It's about PowerShell, not Python, but it does not matter.


You will have to have another access. Like an SSH shell access.


If you actually want to download the script from the FTP server and run it on the local machine use:

with open('hello.py', 'wb') as f
    ftp.retrbinary('RETR hello.py', f.write)
system('python hello.py')

If you do not want to store the script to a local file, this might work too:

r = StringIO()
ftp.retrbinary('RETR hello.py', r.write)
exec(r.getvalue())

Better use the runpy module

import runpy

runpy.run_path("code.py")

Refer to the documentation page for more details runpy module documentation

Here is a one-liner (no modules required!):

exec(open('hello.py','r').read())
Related