I've been writing a basic script to enumerate SMTP users (via a user dictionary) on poorly configured SMTP servers. In scripts like this, I usually see arguments handled as follows:
if (len(sys.argv) != 3:
print "Usage: ..."
sys.exit(0)
I found the if
and print
statement approach irritating, but without a concrete reason why in my mind. I decided to use assertions and combine argument handling with general setup. The following is the complete script.
#!/usr/bin/python
import socket
import sys
import os
SMTP_PORT = 25
#
# Helper Functions
#
def create_connection(host, port):
smtp_server = sys.argv[1]
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
return(sock)
def smtp_verify(username, smtp_conn):
smtp_conn.send('VRFY ' + username + '\r\n')
smtp_reply = smtp_conn.recv(1024)
return(smtp_reply)
#
# Arg checking, connection setup
#
try:
assert len(sys.argv) == 3, \
"Usage: smtp_enum.py <smtp_server_ip> <username_list_file>"
users_file = sys.argv[2]
assert os.path.isfile(users_file), "Cannot open file %s" % users_file
smtp_server = sys.argv[1]
smtp_conn = create_connection(smtp_server, SMTP_PORT)
banner = smtp_conn.recv(1024)
print banner
except Exception as e:
print "Error: %s" % e
exit(1)
#
# Perform SMTP enumeration
#
with open(users_file, 'r') as users:
for user in users:
print smtp_verify(user.strip(), smtp_conn)
smtp_conn.close()
I'm wondering if I may later regret the assertion approach if the script grows. Is this an abuse of assertions, or somehow problematic?