Python防止sql注入

时间:2022-04-23
本文章向大家介绍Python防止sql注入,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

看了网上文章,说的都挺好的,给cursor.execute传递格式串和参数,就能防止注入,但是我写了代码,却死活跑不通,怀疑自己用了一个假的python

最后,发现原因可能是不同的数据库,对于字符串的占位定义不同,这段话:

Note that the placeholder syntax depends on the database you are using

'qmark' Question mark style, e.g. '...WHERE name=?' 
'numeric' Numeric, positional style, e.g. '...WHERE name=:1' 
'named' Named style, e.g. '...WHERE name=:name' 
'format' ANSI C printf format codes, e.g. '...WHERE name=%s' 
'pyformat' Python extended format codes, e.g. '...WHERE name=%(name)s'

我理解,就是有多种占位方式,而我一棵树上吊死,光试验%s了,所以每次都报这个错:

rs=c.execute("select * from log where f_UserName=%s","jetz")

OperationalError: near "%": syntax error

换一个试试,

rs=c.execute("select * from log where f_UserName=:usr",{"usr":"jetz"})

可以

再试:

rs=c.execute("select * from log where f_UserName=:1 ",["jetz"])

也可以

看了sqlite对%比较过敏

对于sql注入的测试效果。

1)用构造串的方式,传递用户名

getData("select * from log where f_UserName='%s'"%("jetz"))

如果传递的是测试表名存在的串,可以执行

getData("select * from log where f_UserName='%s'"%("jetz' And (Select count(*) from user)<>0 and '1'='1"))

但是,如果改用参数方式,则不能执行

getData("select * from log where f_UserName=:1","jetz' And (Select count(*) from user)<>0 and '1'='1")

这种近乎“原生”的防止注入手段,比对传入参数进行检测来说,实在好太多了。