Python#Twistedでftp Serverを立ち上げよう

実はS7-1500からFTP Protocolを使ってFTP Serverからデータをダウンロードすると思いますが、まず最初は自力でサーバーを立ち上げようと思います。なので、一回めはFTPのServerとClientのやり方を紹介したいと思います。

ubuntu のパージョン

cat /etc/os-release

Twistedライブラリ

https://pypi.org/project/Twisted/
pip install Twisted

ftpServer.py

そこにServerを立ち上げるのサンプルCodeが入っています。

https://docs.twistedmatrix.com/en/twisted-16.6.0/_downloads/ftpserver.py
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

“””
An example FTP server with minimal user authentication.
“””

from twisted.protocols.ftp import FTPFactory, FTPRealm
from twisted.cred.portal import Portal
from twisted.cred.checkers import AllowAnonymousAccess, FilePasswordDB
from twisted.internet import reactor

#
# First, set up a portal (twisted.cred.portal.Portal). This will be used
# to authenticate user logins, including anonymous logins.
#
# Part of this will be to establish the “realm” of the server – the most
# important task in this case is to establish where anonymous users will
# have default access to. In a real world scenario this would typically
# point to something like ‘/pub’ but for this example it is pointed at the
# current working directory.
#
# The other important part of the portal setup is to point it to a list of
# credential checkers. In this case, the first of these is used to grant
# access to anonymous users and is relatively simple; the second is a very
# primitive password checker.  This example uses a plain text password file
# that has one username:password pair per line. This checker *does* provide
# a hashing interface, and one would normally want to use it instead of
# plain text storage for anything remotely resembling a ‘live’ network. In
# this case, the file “pass.dat” is used, and stored in the same directory
# as the server. BAD.
#
# Create a pass.dat file which looks like this:
#
# =====================
#   jeff:bozo
#   grimmtooth:bozo2
# =====================
#
p = Portal(FTPRealm(‘./’),
          [AllowAnonymousAccess(), FilePasswordDB(“pass.dat”)])

#
# Once the portal is set up, start up the FTPFactory and pass the portal to
# it on startup. FTPFactory will start up a twisted.protocols.ftp.FTP()
# handler for each incoming OPEN request. Business as usual in Twisted land.
#
f = FTPFactory(p)

#
# You know this part. Point the reactor to port 21 coupled with the above factory,
# and start the event loop.
#
reactor.listenTCP(21, f)
reactor.run()

ftpClient.py

最初にはこのExampleをやりたいと思いますが、ちょっとエラーが出てきてPythonのftplibを使うことにしました。

もともとのftpclient.py↓

https://docs.twistedmatrix.com/en/twisted-16.6.0/_downloads/ftpclient.py

Pythonのftplib

https://docs.python.org/3.8/library/ftplib.html

Code

from ftplib import FTP

File=’pass.dat’
DownFiles=open(File,’wb’).write

FTP_HOST=”192.168.3.12″

ftp=FTP(FTP_HOST)
ftp.login()

print(‘Listing up the Content..’)

print(ftp.retrlines(‘LIST’))
ftp.retrbinary(‘RETR ‘+File,DownFiles)

このようなFileがダウンロードができました。

最後の解説

ftp.login(user=”, passwd=”, acct=”)

loginはFTP ClassのFunctionでFTP ServerにLoginすることをやってくれます。そしてそのFunctionは必要な認証情報も含めてFTP Serverへ贈ります。もしUsernameはanonymous,

Passwordが空であれば‘anonymous@’をLoginさせます。

流れとしては、

  • LoginのSessionを初期化します。 
  • FTP Commands USER, PASSに変換
  • USER情報を贈り、認証OKなら接続可能と判断
  • FTP Sessionを作ります。

余談になりますが、Fileを転送などするにはConnectionが必要ですね?イメージからするとAくんがBくんと電話するとき、Aくんがまず番号入力>電話かける>会話>電話切るの流れですね。FTPは2つのConnectionを使用しています。

  • 制御用のControl Connection:Login,Password,file転送Formatなどの命令・応答
  • データ転送用のData Connection:転送されるデータの送受信のために

ちなみに、FTPにセキュリティ加えたSFTPじゃBinary Modeしかできません。

retrbinary(cmd, callback, blocksize=8192, rest=None)

  • cmd: つまりFTPのコマンド
  • callback:FTPとやりとりするとき使うのFunction。書き込む・読み込むもこできます。
  • blocksize:最大サイズ(Bytes)
  • rest:あまりわからない、ごめん。

FTPでデータを転送などするにはASCII ModeとBinary Modeがあります。

  • ASCII Mode:FilesをテキストFormatで送信します。OSのバージョンによってCR・LineFeedなどのFormatも違いますので、ASCII Modeでは自動で直します。
  • Binary Mode:Binary Formatで送信。データの修正を加えずに。

先の例ではFTPからデータをダウンロードするので、RETRのコマンドを使います。そして二番目のパラメータはCallBackです。

コマンドの詳細はGoogleしてくださいね。

はーい、お疲れ様。

Footer_Basic

Please Support some devices for my blog

Amazon Gift List

Find ME

Twitter:@3threes2
Email:soup01threes*gmail.com (* to @)
YoutubeChannel:https://www.youtube.com/channel/UCQ3CHGAIXZAbeOC_9mjQiWQ

シェアする

  • このエントリーをはてなブックマークに追加

フォローする