2023年10月6日 星期五

用Python上傳檔案到FTP伺服器

 1. FTP伺服端程式(黃底部份需要視情況變動):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer

authorizer = DummyAuthorizer()
authorizer.add_user("demo", "1234", "C:/Users/cheng-min/AppData/Local/Programs/Python/Python311/test", perm="elradfmwMT")
authorizer.add_anonymous("C:/Users/cheng-min/AppData/Local/Programs/Python/Python311/test")

handler = FTPHandler
handler.authorizer = authorizer

server = FTPServer(("127.0.0.1", 2121), handler)
server.serve_forever()

2.FTP客戶端程式(黃底部份需要視情況變動):
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
from ftplib import FTP       
import sys,getpass,os.path   
host = '127.0.0.1'       
port = 2121              
timenout = 30                
username = 'demo'           
password = '1234'          
localfile = 'test6.py'   
remotepath = 'C:/Users/cheng-min/AppData/Local/Programs/Python/Python311/test'       
f = FTP()
f.connect(host,port,timenout)  
f.login(username,password)     
#f.cwd(remotepath)             
file = open(localfile,'rb')
if os.path.isfile(localfile):
    print ('上傳 %s to %s'%(localfile, remotepath))
    f.storbinary('STOR %s' % localfile,file)  
file.close()   
f.quit() 


沒有留言:

張貼留言