Python sql注入 过滤字符串的非法字符实例

2020-09-25 0 499

我就废话不多说了,还是直接看代码吧!

#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 sql注入 过滤字符串的非法字符实例

以上这篇Python sql注入 过滤字符串非法字符实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持自学编程网。

遇见资源网 Python Python sql注入 过滤字符串的非法字符实例 http://www.ox520.com/25188.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务