Python预编译语句防止SQL注入(转)

 

错误用法:

1 sql = "select id,type,name from xl_bugs where id = %s and type = %s" % (id, type)
2 cur.execute(sql)

这种用法就是常见的拼接字符串导致sql注入漏洞的产生。看到这个突然想到上个礼拜drupal水滴的那个漏洞,其并不是预编译语句被绕过了。而是在构造带入的预编译语句的时候拼接了用户输入字符串,还未带入查询的预编译语句已经被注入了,之后带入正确的参数,最后被注入了

正确用法:
execute() 函数本身有接受sql语句参数位的,可以通过python自身的函数处理sql注入问题。

1 args = (id, type)
2 cur.execute('select id, type ,name from xl_bugs where id = %s and type = %s', args )

使用如此参数带入方式,python会自动过滤args中的特殊字符,制止SQL注入的产生。

当然,这只是一篇文章,查了下另外一个,来对这个进行补充:

execute()函数本身就有接受SQL语句变量的参数位,只要正确的使用(直白一点就是:使用”逗号”,而不是”百分号”)就可以对传入的值进行correctly转义,从而避免SQL注入的发生。

example:

 1 import sqlite3
 2  
 3 con = sqlite3.connect(":memory:")
 4 cur = con.cursor()
 5 cur.execute("create table people (name_last, age)")
 6  
 7 who = "Yeltsin"
 8 age = 72
 9  
10 # This is the qmark style:
11 cur.execute("insert into people values (?, ?)", (who, age))
12  
13 # And this is the named style:
14 cur.execute("select * from people where name_last=:who and age=:age", {"who": who, "age": age})
15  
16 print cur.fetchone()

 

本文参考信息:

http://xlixli.net/?p=377

https://crazyof.me/blog/archives/2224.html

【版权所有@Sevck 博客地址http://www.cnblogs.com/sevck】 可以转载,注明出处.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值