Search code examples
pythonscriptingftpftplib

How to run Python script in FTP server using Python?


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


Solution

  • 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())