Sunday, 10 May 2009

Firewall port testing #3

Here is an update to my Firewall port testing script. You can find more about it in my first two epsiodes about it (one and two). I have made some changes to it nothing big just some comments and should now get the host name on Linux systems for placing in the results file name. This code is released under a do what ever you want with it license.

#!/usr/bin/python

"""PortTester will test to see if the machine that this script is running
on has access to another server on a given port. The servers to test are
outlined in input.txt and the results are placed in the
results_<servername>_<YYYYMMDD>-<HH24MMSS>.txt file. This output file is
CSV.

The input file should look like:
Info,Host,Port
Router Web Admin,10.0.0.1,80
Blog,blog.karit.geek.nz,80
Won't work,www.example.com,12345
"""

import telnetlib
import thread
import os
import datetime
import platform


class PortTester(object):

thread_count = 0

def __init__(self, input, log):

for row in input:
thread.start_new(self.testPort, (row['info'], row['host'], row['port'], log))
self.thread_count = self.thread_count + 1
while self.thread_count > 0:
pass


def testPort(self, info, host, port, log):
print 'Testing %s. host %s on port %s' % (info, host, port)
try:
connection = telnetlib.Telnet(host, port, 5)
connection.close()
log.write('%s,%s,%s,pass\n' % (info,host,port))
log.flush()
except:
log.write('%s,%s,%s,fail\n' % (info,host,port))
log.flush()
self.thread_count = self.thread_count - 1

def main():
test_list = readCSV('input.txt', ',', 1)
hostname = ''
if os.name == 'posix':
hostname = platform.node()
else:
hostname = os.getenv('COMPUTERNAME')
output = open('results_%s_%s.txt'%(hostname,datetime.datetime.now().strftime('%Y%m%d-%H%M%S')), 'w')
output.write('info,host,port,result\n')
output.flush()
PortTester(test_list, output)

def readCSV(path, delimiter, header_row):
text = open(path, 'r').read()
text = text.replace('%s%s' % (delimiter, delimiter), '%s %s' % (delimiter, delimiter))
lines = text.split('\n')
rows = []
if header_row:
headers = []
if lines[0] != '':
headers = lines[0].split(delimiter)
tmp = []
for head in headers:
tmp.append(head.strip().lower())
headers = tmp
del lines[0]
for line in lines:
if line != '':
values = line.split(delimiter)
row = {}
for i in range(0, len(headers)):
row[headers[i]] = values[i].strip()
rows.append(row)
else:
for line in lines:
if line != '':
values = line.split(delimiter)
rows.append(values)
return rows

if __name__ == '__main__':
main()

0 comments: