pymysql存在的SQL注入隐患

前面博文写到用pymysql连接MySQL数据库:

 

#!/usr/bin/env python  
# -*- coding:utf-8 -*-  
import pymysql  
    
# 创建连接  
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')  
# 创建游标(游标是用来帮你获取数据的)  
cursor = conn.cursor()  
    
# 执行SQL,并返回收影响行数  
effect_row = cursor.execute("update hosts set host = '1.1.1.2'")  
    
# 执行SQL,并返回受影响行数  
#effect_row = cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,))  
#effect_row = cursor.execute("select username from user_info where username = '%s' password = '%s'" % (name,pwd))  
    
# 执行SQL,并返回受影响行数(插入多个数据)  
#effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])  
    
    
# 提交,不然无法保存新建或者修改的数据  
conn.commit()  
    
# 关闭游标  
cursor.close()  
# 关闭连接  
conn.close()

 

pymysql使用的是cuosor.execute来执行SQL语句,我们可能会使用字符串拼接的方式来执行SQL语句,例如:

 

temp = "select name from user_info where username = '%s' password = '%s' " % (username,password)

effect_row = cursor.execute(temp)

#但是如此使用就会引起SQL注入,例如在用户提交表单时,在用户名这一栏填入anything '  or 1=1 -- d ,那么就可以登录到系统,因为单引号被识别为账号这个字符串的
#结束,那么又写入了一个或的条件判定,1恒等于1,必定成立。--在SQL中是注释,注释掉了账号之后的所有信息,所以能够‘骗’过系统,登录成功。更严重的是甚至可以通
#过SQL注入对数据库进行各种操作,后果不堪设想。
解决方法:使用pymysql自身的字符串拼接功能,不要自行拼接
需要注意的是,使用excute进行字符串的拼接,%s不要带引号
cursor.execute("INSERT INTO interface(name,ip,mask,gateway,status) VALUE (%s,%s,%s,%s,%s)",
                       (i['name'], i['IP'], i['NETMASK'], i['GATEWAY'], i['STATUS']))

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章