Python sql注入 过滤字符串的非法字符实例
时间:2021-05-14 10:37:39|栏目:Python代码|点击: 次
我就废话不多说了,还是直接看代码吧!
#coding:utf8
#在开发过程中,要对前端传过来的数据进行验证,防止sql注入攻击,其中的一个方案就是过滤用户传过来的非法的字符
def sql_filter(sql, max_length=20):
dirty_stuff = ["\"", "\\", "/", "*", "'", "=", "-", "#", ";", "<", ">", "+", "%", "$", "(", ")", "%", "@","!"]
for stuff in dirty_stuff:
sql = sql.replace(stuff, "")
return sql[:max_length]
username = "1234567890!@#!@#!@#$%======$%"
username = sql_filter(username) # SQL注入
print username
# 输出结果是:1234567890
补充知识:python解决sql注入以及特殊字符
python往数据库插入数据,
基础做法是:
cur=db.cursor() sql = "INSERT INTO test2(cid, author, content) VALUES (1, '1', 'aa')" cur.execute(sql,())
也可以这样:
cur=db.cursor()
sql = "INSERT INTO test2(cid, author, content) VALUES (%s, '%s', '%s')"
sql=sql%('2','2','bb')
cur.execute(sql,())
但是当含有特殊一点的字符时就有问题了,比如单引号,%等,甚至会被sql注入。
和其他语言一样,python也他的方法来解决sql注入。
cur=db.cursor()
sql = "INSERT INTO test2(cid, author, content) VALUES (%s, %s, %s)"
cur.execute(sql,('3','3','c%c'))
注意,后面2个%s的前后单引号去掉了。
结果如下:

栏 目:Python代码
下一篇:Python + selenium + crontab实现每日定时自动打卡功能
本文标题:Python sql注入 过滤字符串的非法字符实例
本文地址:http://www.codeinn.net/misctech/121194.html






