sql註入與防止SQL註入之參數化處理
阿新 • • 發佈:2018-11-25
NPU dict class 登錄 int 處理 where cal 執行
sql註入的兩種情況:
操作代碼:
import pymysql user = input(‘用戶名: ‘).strip() pwd = input(‘密碼: ‘).strip() # 鏈接 conn = pymysql.connect(host=‘localhost‘, user=‘root‘, password=‘123‘, database=‘db1‘, charset=‘utf8‘) # 遊標 cursor = conn.cursor() # 執行完畢返回的結果集默認以元組顯示 # cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)# 執行sql語句 sql = ‘select * from t1 where name="%s" and pwd="%s"‘ % (user, pwd) # 註意%s需要加引號 print(sql) res = cursor.execute(sql) # 執行sql語句,返回sql查詢成功的記錄數目 print(res) cursor.close() conn.close() if res: print(‘登錄成功‘) else: print(‘登錄失敗‘)
正常情況
用戶名: zj 密碼: 123 select * from t1 where name="zj" and pwd="123" 1 登錄成功
sql註入
1、sql註入之:用戶存在,繞過密碼
用戶名: zj" -- saaa 密碼: a select * from t1 where name="zj" -- saaa" and pwd="a" 1 登錄成功
2、sql註入之:用戶不存在,繞過用戶與密碼
用戶名: 12e" or 1=1 -- asddas 密碼: select * from t1 where name="12e" or 1=1 -- asddas" and pwd="" 1 登錄成功
防止SQL註入之參數化處理
優化後的代碼
import pymysql user= input(‘用戶名: ‘).strip() pwd = input(‘密碼: ‘).strip() # 打開數據庫連接 conn = pymysql.connect(host=‘localhost‘, user=‘root‘, password=‘123‘, database=‘db1‘, charset=‘utf8‘) # 創建一個遊標對象 cursor = conn.cursor() # 參數化處理 sql = "select * from t1 where name=%s and pwd=%s" # 註意%s需要去掉引號,因為pymysql會自動為我們加上 print(sql) res = cursor.execute(sql, [user, pwd]) # 執行sql語句,返回sql查詢成功的記錄數目 print("res:", res) # 關閉遊標 cursor.close() # 關閉數據庫 conn.close() if res: print(‘登錄成功‘) else: print(‘登錄失敗‘)
正確輸入
用戶名: zj 密碼: 123 select * from t1 where name=%s and pwd=%s res: 1 登錄成功
sql註入,失敗示例
用戶名: zj" -- sad 密碼: a select * from t1 where name=%s and pwd=%s res: 0 登錄失敗
sql註入與防止SQL註入之參數化處理