sql注入攻擊


# ###sql 注入攻擊
# 創建一張表

create table usr_pwd(
id int unsigned primary key auto_increment,
username varchar(255) not null,
password varchar(255) not null
)

# (1)sql注入問題

import pymysql
user=input("user:>>>").strip()
pwd=input("pwd:>>>").strip()
conn=pymysql.connect(host="localhost",user="root",password="123456",database="testdb1")
cursor=conn.cursor()
sql="select * from usr_pwd where username='%s' and password='%s'"%(user,pwd)
"""注意,username='%s'和password='%s'要加引號,因為數據庫中username和password都是字符串型"""
""" 注入攻擊(1): r734d' or 2=2 -- dfe23 實際執行的sql語句: select * from usr_pwd where username='r734d' or 2=2 -- dfe23' and password=''
# 這里
-- 后面的語句表示注釋
注入攻擊(2)(更簡單): 
' or 1 #
實際執行的sql語句: select * from usr_pwd where username='' or 1 #' and password=''
"""
print(sql)
res
=cursor.execute(sql)
print(res) #返回查詢到的條數
if res:
  print("登錄成功")
else:
  print("登錄失敗")
cursor.close()
conn.close()

# (2) 解決辦法

使用預處理機制,可以避免絕大多數的sql注入問題;
execute 默認參數是一個sql語句 ,如果把sql語句和參數值分開執行,就開啟預處理
execute(sql,(參數1,參數2,參數3 ..... ) )

import pymysql
user=input("user>>>").strip()
pwd=input("pwd>>>").strip()
conn=pymysql.connect(host="127.0.0.1",user="root",password="123456",database="testdb1")
cursor=conn.cursor()
sql="select * from usr_pwd where username=%s and password=%s"
res=cursor.execute(sql,(user,pwd))

if res:
    print("登錄成功")
else:
    print("登錄失敗")
cursor.close()
conn.close()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM