[Tutor] code review request

2006-01-04 Thread Will Harris
Hoping to get some of you guru types to look over the start of a tool I
am working on in python. 

A working version of the script is at 
https://mikaru.homeunix.org/py-bin/memberlist.py
The site only allows https because I got sick of all the hacked windoze
boxes trying to execute crap that I didn't have, so port 80(http) is
blocked on my firewall. 

This lets you add users, divisions (groups) and put the users in
divisions(groups). and list the users out by group. I haven't figure
out yet how to authenticate the users from the database (postgresql) so
any pointers there would be helpful. When a user is added, the password
is encrypted in the database using postgresql's encrypt() function so
that it would be possible to use another application to access the
data. Any pointers or advise on where improvments could be made would
be welcome.

#!/usr/bin/python

print 'Content-type: text/html\n'

import psycopg
import cgitb
import cgi
import sys
cgitb.enable()

def quote(string):
if string:
return string.replace("'", "\\'")
else:
return string

form = cgi.FieldStorage()


conn = psycopg.connect('dbname=XXX user=xxx password=x')
curs = conn.cursor()

div_name = quote(form.getvalue('div_name'))
div_director = quote(form.getvalue('div_director'))
div_email = quote(form.getvalue('div_email'))

if not (div_name and div_director and div_email):
print 'ALL FIELDS MUST BE COMPLETED'
sys.exit()

query = """INSERT INTO divisions(div_name, div_director, div_email) VALUES 
('%s', '%s', '%s')""" % (div_name, div_director, div_email)

curs.execute(query)
conn.commit()
conn.close()

print """

  
Division added
  
  
Division created successfully

Back to the main page
  

"""

#!/usr/bin/python

print 'Content-type: text/html\n'

import psycopg
import cgitb
import cgi
import sys
cgitb.enable()

def quote(string):
if string:
return string.replace("'", "\\'")
else:
return string

form = cgi.FieldStorage()


conn = psycopg.connect('dbname= user=x password=x')
curs = conn.cursor()

name = quote(form.getvalue('name'))
address = quote(form.getvalue('address'))
email = quote(form.getvalue('email'))
password = quote(form.getvalue('password'))
username = quote(form.getvalue('username'))
div_id = quote(form.getvalue('division'))

if not (name and username and password):
print 'Please supply name, username, and password'
sys.exit()

query = """INSERT INTO members(name, address, email, password, username, 
div_id) VALUES ('%s', '%s', '%s', encrypt('%s', \'f00zball\', \'aes\'), '%s', 
'%i')""" % (name, address, email, password, username, int(div_id))

curs.execute(query)
conn.commit()
conn.close()

print """

  
User added
  
  
User created successfully

Back to the main page
  

"""

#!/usr/bin/python

from mod_python import apache
import cgitb; cgitb.enable()
import psycopg
conn = psycopg.connect('dbname= user= password=x')
curs = conn.cursor()

print 'Content-type: text/html\n'

print """

  
Member Management
  
  
User List
"""

curs.execute('SELECT * FROM divisions')
rows = curs.dictfetchall()

toplevel = []
children = {}

for row in rows:
division = row['div_id']
print '%(div_name)s' % row

def format(row):
print '%(div_name)s' % row
try: kids = children[row['div_id']]
except KeyError: pass
else:
print ''
for kid in kids:
format(kid)
print ''

print ''

for row in toplevel:
format(row)

print """


Create User | Add 
Division
  

"""

#!/usr/bin/python

from mod_python import apache
import cgitb; cgitb.enable()
import psycopg
conn = psycopg.connect('dbname=x user= password=x')
curs = conn.cursor()

print 'Content-type: text/html\n'

print """

  
Member Management
  
  
User List
"""

curs.execute('SELECT * FROM members')
rows = curs.dictfetchall()

toplevel = []
children = {}

for row in rows:
parent_id = row['div_id']
if parent_id is None:
toplevel.append(row)
else:
children.setdefault(parent_id,[]).append(row)

def format(row):
print '%(name)s' % row
try: kids = children[row['mem_id']]
except KeyError: pass
else:
print ''
for kid in kids:
format(kid)
print ''

print ''

for row in toplevel:
format(row)

print """


Create User | Add 
Division | List Divisions
  

"""

#!/usr/bin/python

print 'Content-type: text/html\n'

import cgitb; cgitb.enable()

import psycopg
conn = psycopg.connect('dbname=xx user= password=x')
curs = conn.cursor()

import cgi, sys
form = cgi.FieldStorage()
#name = form.getvalue('name')


print """

  
Division
  
  
Add Division

"""

print """
Division Name:

Director:

Division E-Mail List:




Back to the main page'
  

"""

#!/usr/bin/python

print 'Content-type: text/html\n'

import cgitb; cgitb.enable()

Re: [Tutor] regex

2005-12-28 Thread Will Harris
Thanks, this helped out. I hadn't thought of trying to use strings for this, I will give that a shot.

I removed the TYPE field from the regex thinking that might have been causing a problem and forgot to add it back to my regex.On 12/27/05, Kent Johnson
 <[EMAIL PROTECTED]> wrote:Danny Yoo wrote:
>>Dec 18 10:04:45 dragon logger: TCPWRAP: SERVICE=sshd@:::192.168.0.1>>,TYPE=ALL_DENY,HOST_ADDRESS=:::195.145.94.75,HOST_INFO=:::
>>195.145.94.75,HOST_NAME=unknown,USER_NAME=unknown,OTHERINFO=>>> Hi Will,>> Observation: the output above looks comma delimited, at least the stuff
> after the 'TCPWRAP:' part.self.twist_fail_re =>>rc('SERVICE=\S*\sHOST_ADDRESS=\S*\sHOST_INFO=\S*\sHOST_NAME=\S*\sUSER_NAME=\S*\s')>>> The line given as example doesn't appear to have whitespace in the places
> that the regular _expression_ expects.  It does contain commas as delimiters> between the key/value pairs encoded in the line.Expanding on Danny's comment...\S*\s matches any amount of non-whitespace followed by one whitespace.
This doesn't match your sample. It looks like you want to matchnon-comma followed by comma. For example this will match the first field:SERVICE=[^,]*,Presumably you will want to pull out the value of the field so enclose
it in parenthesis to make a group:SERVICE=([^,]*),Another thing I notice about your regex is it doesn't include all thefields in the sample, for example TYPE. If the fields are always thesame you can just include them in your regex. If they vary you can try
to make the regex skip them, use a different regex for each field, ortry Danny's approach of using str.split() to break apart the data.The Regex Demo program that comes with Python is handy for creating and
testing regexes. Look in C:\Python24\Tools\Scripts\redemo.py or theequivalent.Kent___Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] regex

2005-12-26 Thread Will Harris
Does anyone see anything that jumps out at them on why these regex strings aren't catching this line:

Dec 18 10:04:45 dragon logger: TCPWRAP:
SERVICE=sshd@:::192.168.0.1,TYPE=ALL_DENY,HOST_ADDRESS=:::195.145.94.75,HOST_INFO=:::195.145.94.75,HOST_NAME=unknown,USER_NAME=unknown,OTHERINFO=


This is the output of a tcpwrapper script I have, I am trying to write
a script to parse this and tell me how many times host_address X has
been denied access (among many other things). I have it working for the
firewall rules just fine, but I am missing something somewhere to catch
the string above. Below are the regex expressions I have tried:

--
initial regex to find the line and pass it back to the routine to sort
all this out. This line works, I believe (least I can get it to print
all the entries back to me I am looking for.
-
rc('logger\S*\sTCPWRAP') : self.twist_failure

Here is where I seem to run into trouble, none of the regex strings I have used seem to catch and sort out the strings.

self.twist_fail_re = rc('SERVICE=\S*\sHOST_ADDRESS=\S*\sHOST_INFO=\S*\sHOST_NAME=\S*\sUSER_NAME=\S*\s')
--
rc is set as rc = re.compile at the early part of my script. I have
tried every combination I can think of for the _expression_ above, below
are the couple I still have written down.
self.twist_fail_re = rc('SERVICE=(\.)\.TYPE=(\.)\.HOST_ADDRESS=(\.)\.HOST_INFO=(\.)\.USER_NAME=(\.)')
self.twist_fail_re = rc('SERVICE=(\S*)\S*TYPE=(\S*)\S*HOST_ADDRESS=(\S*)\S*HOST_INFO=(\S*)\S*USER_NAME=(\S*)')
rc('SERVICE=\S*\sHOST_ADDRESS=\S*\sHOST_INFO=\S*\sHOST_NAME=\S*\sUSER_NAME=\S*\s')

But for some reason they are not picking up the strings. Any suggestions?

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Editors

2005-12-12 Thread Will Harris
Any of you familar with SPE
? I found this just recently on freshmeat and was curious if anyone had
used it? If so how well it works and what not. This caught my attention
because its cross platform (written in python).
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] log parsing

2005-11-30 Thread Will Harris
Cool, thanks Kent.On 11/29/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
Will Harris wrote:> I am trying to work out doing a bit of log parsing in python. Below is> the code I have gotten so far, It works in an earlier version of this> one but this one doesn't print out the lines in my log files. Does
> anyone see anything that I am missing here or can just point me in the> direction to look?>> for logs in sys.argv[1:]:>   open(logs)>   for line in logs:This should be something like
  f = open(logs)  for line in f:You are opening the file and throwing it away, then iterating over the command line argument.Kent--http://www.kentsjohnson.com
___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] log parsing

2005-11-29 Thread Will Harris
I am trying to work out doing a bit of log parsing in python. Below is
the code I have gotten so far, It works in an earlier version of this
one but this one doesn't print out the lines in my log files. Does
anyone see anything that I am missing here or can just point me in the
direction to look?
This iteration I am just trying to get it to let me specify the logs I
want to parse from the command line (later I want to sort all this out
and put it into a postgres database)

#!/usr/bin/python
###

import sys
import re

###

USAGE = (sys.argv[0]) + ''' logfile logfile logfile '''
###

def hasAccept(s):
   return s.find('accept-n-log') != -1

def hasDrop(s):
   return s.find('drop-n-log') != -1

def main():
    if len(sys.argv) <= 1:
    print USAGE
    return 1

    for logs in sys.argv[1:]:
  open(logs)
  for line in logs:
 if hasAccept(line):
 print(line)

if __name__ == '__main__':
    main()


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] slices

2005-11-17 Thread Will Harris
Blah brain freeze I saw my mistake as I hit send.
It should just be word[-2:]

So 

#!/usr/bin/python

import sys



for word in sys.argv[1:]:

 print word[-2:]

Works now. Thanks!
On 11/17/05, Will Harris <[EMAIL PROTECTED]> wrote:
Is there an easy way to slice the last set of characters off a string
when I don't know the length of the string? For example say I have a
list of words like
   this
   though
   weather
I want to get the last 2 characters from each. But so far nothing I
have tried has seemed to work. Currently I am doing something like:

#!/usr/bin/python
import sys

for word in sys.argv[1:]:
 print word[-3:-1]

I have tried to change the numbers around but I always seem to end up
at the wrong place of the string. If I new the length each time I could
just do a positive.
Doesn't this work in the form of:

t    h   i    s
0   1   2   3
-4 -3  -2  -1

Did I miss something somewhere in some tutorial that someone would be kind enough to point me to?


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] slices

2005-11-17 Thread Will Harris
Is there an easy way to slice the last set of characters off a string
when I don't know the length of the string? For example say I have a
list of words like
   this
   though
   weather
I want to get the last 2 characters from each. But so far nothing I
have tried has seemed to work. Currently I am doing something like:

#!/usr/bin/python
import sys

for word in sys.argv[1:]:
 print word[-3:-1]

I have tried to change the numbers around but I always seem to end up
at the wrong place of the string. If I new the length each time I could
just do a positive.
Doesn't this work in the form of:

t    h   i    s
0   1   2   3
-4 -3  -2  -1

Did I miss something somewhere in some tutorial that someone would be kind enough to point me to?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Print Output Location in Windows XP

2005-09-02 Thread Will Harris
Something I do is like

raw_input("\n\nPress enter to exit.")

at the end, this works if all you want to do is see the text on the screen.

Tom Strickland wrote:

>Up until now I have been running my Python programs in Linux. I just 
>wrote one in Windows XP and I can't find the print output. The Python 
>program has a print statement, and when I run the program a black window 
>opens and I can see printing going on. However, when it's finished 
>printing, the output window closes.
>
>How do I get the output window to stay open, or where is the output stored?
>
>Thanks!
>
>Tom Strickland
>
>___
>Tutor maillist  -  Tutor@python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>  
>

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] while loops

2005-08-08 Thread Will Harris
Thanks for the help guys.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] while loops

2005-08-08 Thread Will Harris
I am working my way through "python programming for the absolute beginner" and 
one of the challenges is to create a program that will flip a coin 100 times 
and tell you how many of each it did. Now I have it flipping the coin, but when 
I try to do this 100 times I end up with it running through 100 times, but 
always the same result comes back. It will either be 100 heads, or 100 tails. I 
have tried if statements and while loops and both seem to give me all or 
nothing. I am just looking for a hint at the direction to look of adjust to get 
the code below working not really the solution. Thanks in advanced for any tips.

#!/usr/bin/python
import random

coin = random.randrange(2)

count = 0
head_count = 0
tail_count = 0

while (count != 100):
if coin == 0:
print "You got Heads!"
head_count = head_count + 1
count = count + 1
else:
print "You got Tails!"
tail_count = tail_count + 1
count = count + 1

print "Out of", count, "you flipped", head_count, "heads and ", tail_count, 
"tails"

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor