1 # vim: set encoding=utf-8 et sw=4 sts=4 :
3 import logging ; log = logging.getLogger('pymin.services.nat')
5 from pymin.service.util import Restorable, ConfigWriter, ReloadHandler, \
6 ServiceHandler, TransactionalHandler, call
8 from portfw import PortForwardHandler
9 from snat import SNatHandler
10 from masq import MasqHandler
12 __all__ = ('NatHandler',)
15 class NatHandler(Restorable, ConfigWriter, ReloadHandler, ServiceHandler,
16 TransactionalHandler):
17 r"""NatHandler([pickle_dir[, config_dir]]) -> NatHandler instance.
19 Handles NAT commands using iptables.
21 pickle_dir - Directory where to write the persistent configuration data.
23 config_dir - Directory where to store de generated configuration files.
25 Both defaults to the current working directory.
28 handler_help = u"Manage NAT (Network Address Translation) service."
30 _persistent_attrs = ('ports', 'snats', 'masqs')
32 _restorable_defaults = dict(
38 def _service_start(self):
39 log.debug(u'NatHandler._service_start(): flushing nat table')
40 call(('iptables', '-t', 'nat', '-F'))
41 for (index, port) in enumerate(self.ports):
42 log.debug(u'NatHandler._service_start: adding port %r', port)
43 call(['iptables'] + port.as_call_list(index+1))
44 for (index, snat) in enumerate(self.snats):
45 log.debug(u'NatHandler._service_start: adding snat %r', snat)
46 call(['iptables'] + snat.as_call_list(index+1))
47 for (index, masq) in enumerate(self.masqs):
48 log.debug(u'NatHandler._service_start: adding masq %r', masq)
49 call(['iptables'] + masq.as_call_list(index+1))
51 def _service_stop(self):
52 log.debug(u'NatHandler._service_stop(): flushing nat table')
53 call(('iptables', '-t', 'nat', '-F'))
55 _service_restart = _service_start
57 def __init__(self, pickle_dir='.'):
58 r"Initialize the object, see class documentation for details."
59 log.debug(u'NatHandler(%r)', pickle_dir)
60 self._persistent_dir = pickle_dir
61 ServiceHandler.__init__(self)
62 self.forward = PortForwardHandler(self)
63 self.snat = SNatHandler(self)
64 self.masq = MasqHandler(self)
67 if __name__ == '__main__':
70 level = logging.DEBUG,
71 format = '%(asctime)s %(levelname)-8s %(message)s',
77 handler = NatHandler()
81 print 'Forwarded ports:'
82 print handler.forward.show()
85 print handler.snat.show()
88 print handler.masq.show()
92 handler.forward.add('eth0','tcp','80', '192.168.0.9', '8080')
93 handler.forward.update(0, dst_net='192.168.0.188/32')
94 handler.forward.add('eth0', 'udp', '53', '192.168.1.0')
98 handler.snat.add('eth0', '192.168.0.9')
99 handler.snat.update(0, src_net='192.168.0.188/32')
100 handler.snat.add('eth0', '192.168.1.0')
104 handler.masq.add('eth0', '192.168.0.9/24')
105 handler.masq.update(0, src_net='192.168.0.188/30')
106 handler.masq.add('eth1', '192.168.1.0/24')
110 os.system('rm -f *.pkl')