fjiqiang

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})

 

分类:

技术点:

相关文章: