環境
- OS : CentOS 5
- Python : 2.4
- 追加パッケージ : なし
- 備考 : OS依存なし
Pythonの標準ライブラリだけでSMTPプロキシサーバーを作成することができるのでそのサンプルプログラムを掲載します。
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # testsmptd.py - サンプル SMTP プロキシ
5 #
6 import asyncore
7 import smtpd
8
9 __all__ = ['TestSmtpd', 'TestSMTPChannel']
10 __version__ = 'Test smtpd 1.0';
11
12 class TestSmtpd(smtpd.PureProxy):
13 """smtpd.PureProxyを継承する。
14 基本的にはOverrideを行うことで機能の追加を実現できる。
15 """
16
17 def handle_accept(self):
18 """Override
19 """
20 conn, addr = self.accept()
21 print >> smtpd.DEBUGSTREAM, 'Incoming connection from %s' % repr(addr)
22 channel = TestSMTPChannel(self, conn, addr) # 任意のオブジェクトで生成する。
23
24 class TestSMTPChannel(smtpd.SMTPChannel):
25 """一つの接続あたり1つのTestSMTPChannelインスタンスが生成される。
26 """
27
28 def smtp_TEST(self, arg):
29 """テスト用のメソッド
30 """
31 self.push('Test print HOGE arg=%s' % arg)
32
33 if __name__ == '__main__':
34 """起動時に実行される処理です。
35 TestSmtpdの説明 : TestSmtpd(('ルックアップするアドレス', ルックアップするポート番号)
36 ,('転送先アドレス', 転送先ポート番号))
37 """
38 test_smtpd = TestSmtpd(('0.0.0.0', 8025), ('localhost', 25))
39 asyncore.loop()
サンプルを試してみる
1. 上記のプログラムをtestsmtpd.pyというファイル名で保存します。
2. 以下のコマンドでプログラムを実行します。(今回のプログラムは常駐型です
# python testsmtpd.py3. 以下のコマンドを実行し動作を試してみてください。
# telnet localhost 8025 Trying 127.0.0.1... Connected to localhost.localdomain (127.0.0.1). Escape character is '^]'. 220 hoge.hde.co.jp Python SMTP proxy version 0.2 test Test print HOGE arg=None test hoge Test print HOGE arg=hoge helo localhost 250 hoge.hde.co.jp mail from: root@localhost 250 Ok rcpt to: root@localhost 250 Ok data 354 End data with4. メールがroot@localhostに届いているか確認してみましょ~。. Subject: test test . 250 Ok quit 221 Bye Connection closed by foreign host.




Leave a comment