python番外篇--sql注入

1、sql注入概念介紹python

所謂SQL注入,就是經過把SQL命令插入到Web表單提交或輸入域名或頁面請求的查詢字符串,最終達到欺騙服務器執行惡意的SQL命令。具體來講,它是利用現有應用程序,將(惡意的)SQL命令注入到後臺數據庫引擎執行的能力,它能夠經過在Web表單中輸入(惡意)SQL語句獲得一個存在安全漏洞的網站上的數據庫,而不是按照設計者意圖去執行SQL語句。mysql

2、Python中防止sql注入的方法sql

import pymysql

def op_mysql(host,user,password,db,sql,port=3306,charset='utf8'):
	conn = pymysql.connect(host=host,user=user,
						   password=password,
						   port=port,
						   charset=charset,db=db)
	cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
	cur.execute(sql)
	sql_start = sql[:6].upper() #取sql前6個字符串,判斷它是什麼類型的sql語句
	if sql_start=='SELECT' :
		res = cur.fetchall()
	else:
		conn.commit()
		res = 'ok'
	cur.close()
	conn.close()
	return res

# conn = pymysql.connect(host='211.149.218.16',user='jxz',
# 					   password='123456',
# 					   port=3306,
# 					   charset='utf8',db='jxz')
# cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
# name='zdq'
# # sql = 'select * from bt_stu where username="%s"; '%name
# sex='nv'
# cur.execute('select * from bt_stu where real_name="%s;"' % name) #能夠sql注入的
# cur.execute('select * from bt_stu where real_name=%s and sex = %s',(name,sex)) #能夠防止sql注入
# print(cur.fetchall())


def test(a,b):
	# print(a,b)
	pass
li = [1,2]
d = {'a':'ybq','b':'mpp'}
test(*li)
test(**d)
conn = pymysql.connect(host='211.149.218.16',user='jxz',
					   password='123456',
					   port=3306,
					   charset='utf8',db='jxz')
cur = conn.cursor(cursor=pymysql.cursors.DictCursor)

def op_mysql_new(sql,*data): #data傳入後會變成一個List
	#利用 *data這個可變參數,就能防止sql注入了
	print(sql)
	print(data)
	cur.execute(sql,data)
	# cur.execute('select',(name,id,name))
	# cur.execute('select * from user where name=%s',('haha'))
	print(cur.fetchall())
# sql = 'select * from user where username  = %s and sex=%s;'
# name='haha'
# sex='xxx'
# op_mysql_new(sql,name,sex)

conn = pymysql.connect(host='211.149.218.16',user='jxz',
					   password='123456',
					   port=3306,
					   charset='utf8',db='jxz')

cur = conn.cursor(cursor=pymysql.cursors.DictCursor)

sql = 'insert into seq (blue,red,date) values (%s,%s,%s)'
all_res = [
	['16','01,02,03,05,09,06','2018-01-28'],
	['15','01,02,03,05,09,06','2018-01-28'],
	['14','01,02,03,05,09,06','2018-01-28'],
	['13','01,02,03,05,09,06','2018-01-28'],
	['13','01,02,03,05,09,06','2018-01-28'],
	['13','01,02,03,05,09,06','2018-01-28'],
	['13','01,02,03,05,09,06','2018-01-28'],
	['13','01,02,03,05,09,06','2018-01-28'],
	['13','01,02,03,05,09,06','2018-01-28'],
	['13','01,02,03,05,09,06','2018-01-28'],
	['13','01,02,03,05,09,06','2018-01-28'],
	['13','01,02,03,05,09,06','2018-01-28'],
]
cur.executemany(sql,all_res) #批量執行
conn.commit()
相關文章
相關標籤/搜索