Coding comments/suggestions - first python script - sshd/ftpd blocking

bruno modulix onurb at xiludom.gro
Tue May 10 07:58:49 EDT 2005


avinashc at yahoo.com wrote:
> If anyone is interested in a /etc/hosts.deny automatic update script
> (Unix only) based on sshd/vsftpd attacks, here's a python script:
> http://www.aczoom.com/tools/blockhosts/
> 
> This is a beta release, and my first attempt at Python coding.
> Any comments, suggestions, pointers on using more common Python idioms
> or example coding snippets, etc, welcome!

First thing: I had *many* indentation errors (emacs + python_mode on a 
linux-box). *Please* take care of this.

I just gave a quick glance, not even pretending to really understand 
what the code do, so what follow are just some general advices:

***
def die(msg, ex=None):
     print msg
     if ex: print ex
     sys.exit(1)

- errors messages (including usage) should be written to stderr (stdout 
is for normal output)
- you may want to use positional arguments (*args) instead of 'ex'

def die(msg, *args):
     print >> sys.stderr, msg
     for ex in args:
        print >> sys.stderr, ex
     sys.exit(1)

***
class LockFile:
     (...)
     def lock(self):
         try:
	    try:
		self.fp = open(self.path, "r+")
                 # r+ prevents trashing the file!
	    except Exception, e :

You should use IOError instead of Exception here.
*Always* use the most specific exception class possible.

		if e.errno == errno.ENOENT: # no such file

Here if you have anything else than an IOError (well, anything that 
doesn't have a 'errno' attribute), you'll get an AttributeError...
(...)

		    if DEBUG: print " ... first r+ lock file open failed, so opened 
with w+ mode"

You may want to define a 'debug_trace' function (or use an existing 
trace/log lib) that encapsulate the test...

***
class BlockHosts:
     (...)
     def load_hosts_deny(self, logoffsets):
         self.__remaining_lines = []

	if self.__verbose: print " ... hosts.deny: loading from ", self.__denyfile

Same as for DEBUG : you may want to encapsulate the test in a method.

HTH
Bruno
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for 
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list