Mysql數據庫之sql漏洞注入


sql漏洞注入是利用sql語句拼接字符串造成入侵者不輸入密碼甚至不輸入用戶名就能登錄。

# 導入pymsql模塊
import pymysql

user=input("用戶名:")
pwd=input("密碼:")

# 步驟一:python創建與mysql的連接
conn=pymysql.connect(host="127.0.0.1",user="root",password="123456",database="test")
# 步驟二:創建一個游標對象
get_cursor=conn.cursor()
sql="select * from userinfo2 where name='%s' and pwd='%s'" %(user,pwd)
# 步驟三:使用游標對象中的execute方法執行sql語句
get_cursor.execute(sql)
# 步驟四:將查詢出的結果取出來
result=get_cursor.fetchone()

if result:
    print("登錄成功!")
else:
    print("登錄失敗!")

通過上述代碼中:假設用戶名是:user,密碼:123456

在通過輸入用戶名和密碼正確的情況下,登錄成功;只要有一個不正確,那么就登錄失敗。那么如何才能在不知道用戶名和密碼的情況下登錄成功呢?如下:

首先我們輸入正確的用戶名和密碼,得到的sql語句:select * from userinfo2 where name='user' and pwd='123456';

但是如果我們這樣輸入,也可以登錄:abcdefg' or 1=1 --'

這種輸入的話,得到的sql語句是:select * from userinfo2 where name='abcdefg' or 1=1 --' and pwd='123456';  這句話是絕對成立的,原因是后面的--將密碼給注釋掉了,前面的兩個條件中,無論name什么值,在1=1是絕對正確的,查詢數據庫中所有的數據。

 

防止sql漏洞注入的方法

不要使用上面的字符串拼接的方法進行使用sql語句,而是要使用如下方法(將上面的方法修改):

方法一:使用元組或列表的方法代替字符串拼接

sql="select * from userinfo2 where name=%s and pwd=%s"
get_cursor.execute(sql,[user,pwd])

方法二:使用execute提供的方法中的參數代替字符串拼接

sql="select * from userinfo2 where name=%s and pwd=%s"
get_cursor.execute(sql,user,pwd)

方法三:使用字典的方法代替字符串拼接

sql="select * from userinfo2 where name=%(a)s and pwd=%(b)s"
get_cursor.execute(sql,{'a':user,'b':pwd})

 


免責聲明!

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



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