pymysql存在的SQL注入隱患

前面博文寫到用pymysql連接MySQL數據庫:

 

#!/usr/bin/env python  
# -*- coding:utf-8 -*-  
import pymysql  
    
# 創建連接  
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')  
# 創建遊標(遊標是用來幫你獲取數據的)  
cursor = conn.cursor()  
    
# 執行SQL,並返回收影響行數  
effect_row = cursor.execute("update hosts set host = '1.1.1.2'")  
    
# 執行SQL,並返回受影響行數  
#effect_row = cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,))  
#effect_row = cursor.execute("select username from user_info where username = '%s' password = '%s'" % (name,pwd))  
    
# 執行SQL,並返回受影響行數(插入多個數據)  
#effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])  
    
    
# 提交,不然無法保存新建或者修改的數據  
conn.commit()  
    
# 關閉遊標  
cursor.close()  
# 關閉連接  
conn.close()

 

pymysql使用的是cuosor.execute來執行SQL語句,我們可能會使用字符串拼接的方式來執行SQL語句,例如:

 

temp = "select name from user_info where username = '%s' password = '%s' " % (username,password)

effect_row = cursor.execute(temp)

#但是如此使用就會引起SQL注入,例如在用戶提交表單時,在用戶名這一欄填入anything '  or 1=1 -- d ,那麼就可以登錄到系統,因爲單引號被識別爲賬號這個字符串的
#結束,那麼又寫入了一個或的條件判定,1恆等於1,必定成立。--在SQL中是註釋,註釋掉了賬號之後的所有信息,所以能夠‘騙’過系統,登錄成功。更嚴重的是甚至可以通
#過SQL注入對數據庫進行各種操作,後果不堪設想。
解決方法:使用pymysql自身的字符串拼接功能,不要自行拼接
需要注意的是,使用excute進行字符串的拼接,%s不要帶引號
cursor.execute("INSERT INTO interface(name,ip,mask,gateway,status) VALUE (%s,%s,%s,%s,%s)",
                       (i['name'], i['IP'], i['NETMASK'], i['GATEWAY'], i['STATUS']))

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章