這個月太忙,最近不太太平,我的願望是世界和平!
==================================
今天也在找python的預編譯,早上寫的sql是拼接來構成的。於是找了2篇文章,還不錯,分享一下大家學習。
ps:直接引用別人的話了,因為他們說的已經很好了。
錯誤用法:
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