Contents
- file_input.py
- fixed_input.py
- security_bug.py
file_input.py 1/3
[top][prev][next]
# Example of providing a validated list of input
# Sara Sprenkle
def main():
# the list of valid files user can choose from
VALID_LIST= ["killers.txt", "fergie.txt", "west.txt", "bte.txt", "atkins.txt"]
VALID_LIST.sort()
print
print "Which of the following files do you want to process?"
x = 1
for filename in VALID_LIST:
print "\t%d: %s"%(x, filename)
x+=1
choicestr = raw_input("Select the file by number: ")
print
try:
choice = int(choicestr)
if choice < 1 or choice > len(VALID_LIST):
print "ERROR:", choice, "is not a valid selection."
else:
print "Processing file %d: %s" % (choice, VALID_LIST[choice-1])
except:
print "ERROR: selection must be an integer."
main()
fixed_input.py 2/3
[top][prev][next]
# Example of addressing the input() security bug in Python
# Sara Sprenkle
totalGrades = 0
numGrades = input("How many grades are there? ")
if numGrades <= 0:
print "Error: Number of grades must be positive"
sys.exit(1)
for x in xrange(numGrades):
gradestring = raw_input("Enter grade " + str(x) + ": ")
try:
grade = int(gradestring)
totalGrades += grade
except:
# Note that one less grade will be included in total; does not
# reprompt for grade
print "Error: the grade must be an integer."
avgGrade = totalGrades/float(numGrades)
print "The student's average is %.2f." % avgGrade
security_bug.py 3/3
[top][prev][next]
# Example of security bug in python with input() function in Python
# Sara Sprenkle
totalGrades = 0
numGrades = input("How many grades are there? ")
if numGrades <= 0:
print "Error: Number of grades must be positive"
sys.exit(1)
for x in xrange(numGrades):
# Try entering something like "totalGrades * 2" for the second grade
totalGrades += input("Enter grade " + str(x) + ": ")
avgGrade = totalGrades/float(numGrades)
print "The student's average is %.2f." % avgGrade
Generated by GNU enscript 1.6.4.