簡體   English   中英

如何使用 Python 在 FTP 服務器中運行 Python 腳本?

[英]How to run Python script in FTP server using Python?

我想使用另一個 Python 腳本和 FTP 運行位於服務器上的 Python 腳本。

下面是我要運行的 ( hello.py ) 文件位置。

在此處輸入圖像描述

from ftplib import FTP

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

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

在此處輸入圖像描述

您可以使用 system() 調用:

system('python hello.py')

注意:使用 hello.py 腳本的完整路徑。

另一種方法是使用 subprocess 模塊。

無論如何,您都無法在 FTP 服務器上運行任何東西。
看到一個類似的問題: Run a script via FTP connection from PowerShell
是關於 PowerShell,而不是 Python,但沒關系。


您將必須擁有其他訪問權限。 就像 SSH shell 訪問一樣。


如果您真的想從 FTP 服務器下載腳本並在本地機器上運行它,請使用:

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

如果您不想將腳本存儲到本地文件,這也可能有效:

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

更好地使用 runpy 模塊

import runpy

runpy.run_path("code.py")

有關更多詳細信息,請參閱文檔頁面runpy 模塊文檔

這是一個單行代碼(不需要模塊:):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM