Pythonで開発用のftpサーバを用意してみた。
Pythonで開発用のftpサーバを簡単に作る方法を探していると,以下のようなコードが上がった。
ユーザ名 user
パスワード password
でダミーのユーザを作成。
import pyftpdlib.authorizers
import pyftpdlib.handlers
import pyftpdlib.servers
import os
# スクリプトのファイルのあるフォルダのfolderフォルダを
# ユーザルートにする
srvRoot = os.path.dirname(__file__) + '\\folder';
auth = pyftpdlib.authorizers.DummyAuthorizer()
auth.add_user('user', 'password', srvRoot, perm='elradfmw')
hndler = pyftpdlib.handlers.FTPHandler
hndler.authorizer = auth
server = pyftpdlib.servers.FTPServer(("0.0.0.0", 21), hndler)
try:
    server.serve_forever();
except KeyboardInterrupt:
    print('interrupted!')
クライアントを作成してみる。といっても接続してファイルをアップロードしてみるだけのプログラムだけど…
from ftplib import FTP
ftp = FTP(
    "localhost",
    "user",
    passwd="password"
)
# ファイルのアップロード(テキスト).
with open("test2.txt", "rb") as f:
    ftp.storlines("STOR /test2.txt", f)
ftp.quit();
例えば,このプログラムを定期的にプログラムを実行すれば定期的にアップロードできる。
ただし,この例ではtest2.txtファイルを一度用意しないといけない。
そこでいwith open......の部分は以下のように変えておくと,文字列を直接ftpサーバのtest3.txtファイルに書き込むことができる。
from io import BytesIO
sample_bytes=bytes('これはテストのバイト列です','utf-8')
f = BytesIO(sample_bytes)
ftp.storlines("STOR /test3.txt", f)
        