python file I/O_file_exception_module_third-party package_color component_blasting secret_ping host survival (03)

python file I/O_file_exception_module_third-party package_color component_blasting secret_ping host survival (03)

Article directory

1 file reading

​ Reference video: Dark Horse nanny-level video

1.1 read() method:
文件对象.read(num)

num表示要从文件中读取的数据的长度(单位是字节),如果没有传入num,那么就表示读取文件中所有的数据。
1.2 readlines() method:

eadlines can read the contents of the entire file line by line at once, and returns a list in which the data of each line is an element.

f=open('python.txt')
content=f.readlines()
print(content) # ['hello world\n', 'abcdefg\n', 'aaa\n', 'bbb\n', 'ccc']

#关闭文件
f.close()
1.3 read() use case:
1.3.1 The content of the text.txt file is
在岁月的轮回里,
藏着世间的种种美,
高山巍峨耸入云霄,
江河奔腾破浩渺。
1.3.2 py executable file
# 打开文件
f = open("D:/test.txt","r", encoding="UTF-8")
print(type(f))

print(f"读取10个字节:{f.read(10)}")
print(f"read方法读取全部内容的结果:{f.read()}")
1.3.3 Printing results: Note: Execute the read() method twice. The second time will continue to read at the subscript after read.
<class '_io.TextIOWrapper'>
读取10个字节:在岁月的轮回里,
藏
read方法读取全部内容的结果:着世间的种种美,
高山巍峨耸入云霄,
江河奔腾破浩渺。
1.4 for loop reads file lines
# 打开文件
f = open("D:/test.txt","r", encoding="UTF-8")
print(type(f))
for line in f:
    print(f"读取10个字节:{line}")
f.close()

Print the result:

<class '_io.TextIOWrapper'>
读取10个字节:在岁月的轮回里,

读取10个字节:藏着世间的种种美,

读取10个字节:高山巍峨耸入云霄,

读取10个字节:江河奔腾破浩渺。
1.5 Practice reading and counting the number of times a certain character appears
=====test.txt内容========
itheima itcast python
itheima python itcast
beijing shanghai itheima
=======思路======= 
第一种. read() , count("itheima")
第二种.一行行的读取文件 按照空格切分,统计itheima的次数
===============
方式一:
f = open("D:/test.txt","r", encoding="UTF-8")
content = f.read()  # 读取全部内容
count = content.count("itheima")
print(f"的在文件中出现了:{count}次")
f.close()

打印结果: 3次

方式二:
f = open("D:/test.txt","r", encoding="UTF-8")
count = 0
for line in f:
	line = line.strip()
	words = line.split(" ") # 以空格分隔
	print(words)  # 打印每一行有个换行符 ['itheima', 'itcast', 'python\n']...,使用strip()
	for word in words:
		if word == "itheima":
			count += 1
print(count)
f.close()

打印结果出现:3次
1.4 Summary of read reading methods
operate Function
File object = open(file, mode, encoding) Open a file to get a file object
File object.read(num) Read the specified length of bytes
without specifying num. Read the entire file.
File object.readline() read a line
File object.readlines() Read all lines and get a list
for line in file object for line in file object for loops file lines, obtaining one line of data at a time
File object.close() Close file object
with open() as f Open the file through the with open syntax and can automatically close it

2. Writing of files

Notice:

When write is called directly

When flush is called, the content will actually be written to the file; this is to avoid frequent operations on the hard disk, which will lead to a decrease in efficiency (save a bunch of files and write to the disk at once).

#1.打开文件
f=open('python.txt','w')

#2.文件写入
f write(hello world)

#3.内容刷新
f.flush()
2.1 write() file writing:

1. Write files using the open function mode.

2. The writing methods are:
wirte(), write content
flush(), refresh the content to the hard disk

Note:
In w mode, if the file does not exist, a new file will be created.
In w mode, if the file exists, the original content will be cleared
. close() method has the function of flush() method.

2.1.1 bill.txt content
周轮,2022-01-01,100000,消费,正式
周轮,2022-01-02,300000,收入,正式
周轮,2022-01-03,100000,消费,测试
2.1.2 py execution file, backup file writing
fr =open("D:/test.txt", "r", encoding="UTF-8")  # 打开文件得到文件对象,准备读取
fw =open("D:/bill.txt.bak", "w", encoding="UTF-8")  #打开文件得到文件对象,准备写入

# for 循环读取文件
for line in fr:
	line = line.strip()
	if line.split(",")[4] == "测试": # 判断内容,将满足的内容写出
		continue
	fw.write(line)  # 将内容写出去
	fw.write("\n")  #由于前面对内容进行了strip()的操作,所以要手动的写出换行符
fr.close()
fw.close()   # close内置flush()功能,flush將内存的文件写入磁盘

3. File appended content

​A mode is opened to add content

#1.打开文件,通过a模式打开即可
f=open('python.txt', 'a')

#2.文件写入
f.write('hello world')

#3.内容刷新
f.flush()

Note:
a mode, if the file does not exist, the file will be created.
a mode, if the file exists, the file will be appended to the end.

3.1 When there is no file, a automatically creates a file to append content. Example:
#打开文,不存在文件
f = open("D:/test1.txt","a",encoding="UTF-8")  #write写入
f.write("heima程序员")
f.flush()  #flush新
f.close()  #close关闭

# 打开路径,自动test1.txt文件及追加了内容
3.2 Continue a to write additional content:
f = open("D:/test1.txt", "a", encoding="UTF-8")  #打开一个存在的文件

f.write("\npython最佳保姆式") # write写入 \n换行

f.close()  #close关闭
3.3 Summary
1追加写入文件使用open函数的”a”模式进行写入

2.追加写入的方法有(和w模式一致):
	wirte(),写入内容
	flush(),刷新内容到硬盘中
	
3.注意事项:
	a模式,文件不存在,会创建新文件
	a模式,文件存在,会在原有内容后面继续写入
	可以使用”\n”来写出换行符

4 Exception handling

​ Reference video: Dark Horse nanny-level video

unusual characteristics

Exceptions are transitive

​ When an exception occurs in function func01 and the exception is not caught and handled,

​The exception will be passed to function func02. When func02 does not catch and handle the exception,

The main function will catch this exception, which is the transitivity of the exception.

Note:
When all functions do not catch exceptions, the program will report an error

Insert image description here

def func1():
    print("func1 开始执行")
    num=1/0
    #肯定有异常,除以0的异常
    print("func1 结束执行")

# 定义一个无异常的方法,调用上面的方法
def func2():
    print("func2 开始执行")
    func1()
    print("func2 结束执行")

#定义一个方法,调用上面的方法
def main():
    try:
        func2()
    except Exception as e:
        print(f"出现异常了,异常的信息是:{
      
      e}")

main()

Print results

func2 开始执行
func1 开始执行
出现异常了,异常的信息是:division by zero

5 module import and export

Reference video: Dark Horse high-quality nanny-level video

Modules need to be imported before use. The syntax for import is as follows:

[from 模块名] import [模块 | 类 | 变量 | 函数 | *] [as 别名]   # from是针对模块中某个方法去使用

How to import modules:

常用的组合形式如:
    import 模块名
    from   模块名  import  类、变量、方法等
    from   模块名  import  *
    import 模块名  as  别名
    from   模块名  import  功能名  as  别名
5.1 Basic syntax of import:
import 模块名
import 模块名1,模块名2

模块名.功能名()
5.2 Import case: Importing the time module requires calling time.sleep()
#导入时间模块
import time

print("开始")
#让程序睡眠1秒(阻塞)
time.sleep(1)
print("结束")
5.3 from basic syntax:

​ Use for a method in the module

from 模块名 import 功能名
功能名()

注意:
from time import *  # 是将某块中所有方法都导入
5.4 from case: import the sleep method in the time module, you can directly write the sleep call
#导入time时间模块中的sleep方法
from time import sleep

print("开始")
#让程序睡眠1秒(阻塞)
sleep(1)
print("结束")
5.5 from case: import * in the time module

Case: Import all methods in the time module, and you can directly write sleep calls

#导入时间模块中所有的方法
from time import *

print("开始")
#让程序睡眠1秒(阻塞)
sleep(1)
print("结束")

6 Custom modules

Reference video: Dark Horse nanny-level high-quality video

Insert image description here

6.1 External import does not allow functions to run by themselves
my_modulel.py file
def test(a, b):
	print(a + b)

if __name__ == '__main__': # 加入这个函数,也可以单独测试运行定义的函数
	test(1,2)
6.2 [__all__]Variables

If you don’t write __all__all, you can use it. If you write all, you can only use the functions in the list. All is only limited to *.

Insert image description here

6.3 Summary
 1.如何自定义模块并导入?
    在Python代码文件中正常写代码即可,通过import、from关键字和导
    入Python内置模块一样导入即可使用。

2._main_变量的功能是?
    if __main__==“_main_”表示,只有当程序是直接执行的才会进入
    if内部,如果是被导入的,则if无法进入
    
3.注意事项
	不同模块,同名的功能,如果都被导入,那么后导入的会覆盖先导入的

7 Custom python package

Reference video: Dark Horse nanny-level video

基于Python模块,我们可以在编写代码的时候,导入许
多外部代码来丰富功能。
但是,如果Python的模块太多了,就可能造成一定的混
乱,那么如何管理呢?
通过Python包的功能来管理。
7.1 The steps are as follows

Insert image description here

7.2 Basic steps in pycharm (creating packages)

​Select the project root directory -> Right-click [new] -> [Python Packag] -> Enter the package name (such as my_package) -> OK -> Create a new function module

Note: After creating a new package, such as (my_package), a file will be automatically created inside the package __init__.py. This file controls the import behavior of the package, such as [__all__ =['my_module1']]

​ You can create new files *.py in the package --> Respective function *.py files

7.3 Import custom packages
import my_package.my_modulel
import my_package.my_module2

my_package.my_modulel.info_print1()   #使用包里面函数


或者优化导入:
import my_package.my_module2 import info_print1

info_print1()   #使用包里面函数
7.4 Summary
1.什么是Python的包?
  包就是一个文件夹,里面可以存放许多Python的模块(代码文件),通
  过包,在逻辑上将一批模块归为一类,方便使用。
    
2._init_.py文件的作用?
  创建包会默认自动创建的文件,通过这个文件来表示一个文件夹是
  Python的包,而非普通的文件夹。
	
3.all变量的作用?
	同模块中学习到的是一个作用,控制import*能够导入的内容

8 third-party packages

Reference video: Dark Horse nanny-level video

8.1 What is a third-party package?

We know that a package can contain a bunch of Python modules, and each module contains many functions.
Therefore, we can think of a package as a collection of functions of the same type.

In the ecosystem of Python programs, there are many third-party packages (non-official Python), which can greatly help us improve development efficiency, such as: commonly used in scientific computing:
numpy package
commonly used in data analysis: pandas
package Commonly used in data calculation: pyspark, apache-flink package
Commonly used in graphic visualization: matplotlib, pyecharts
Commonly used in artificial intelligence: tensorflow

8.2 Install third-party packages

Install third-party packages-pip

The installation of third-party packages is very simple, we only need to use Python's built-in pip program.

Open the command prompt program that we have not seen for a long time, enter:
pipinstall package name
to quickly install third-party packages through the network

命令提示符cmd进行安装:

C:\Users\javac>pip install numpy
8.3 Network optimization of pip

Since pip is connected to foreign websites to download packages, sometimes the speed will be very slow.
We can use the following command to connect to the domestic website to install the package:
pip install -i https://pyp.ituna.tsinghua.edu.cn/simple package name

命令提示符cmd
C:\Users\javac> pip install	 -i https://pypi.tuna.tsinghua.edu.cn/simple numpy

https://pypi.tuna.tsinghua.edu.cn/simple is a website provided by Tsinghua University, which allows pip programs to download third-party packages.

Test to verify installation is successful

Insert image description here

8.4 pycharm installs third-party packages
8.4.1 Click python in the lower right corner --> select inter setting

Insert image description here

8.4.2 Click +

Insert image description here

8.4.3 After selection, select install-》Close the window-》Confirm to download in the background.

Insert image description here

8.4.4 Download status in the background

Insert image description here

9 color components

9.1 Installation
pip install colorama # 安装组件
9.2 Import into Python and print colored text:
from colorama import init, Fore, Back, Style

# 初始化 colorama
init()

# 使用不同的颜色打印文本
print(Fore.RED + '红色的文本')
print(Back.GREEN + '绿色背景的文本')
print(Fore.YELLOW + Back.BLUE + '黄色文字和蓝色背景的文本')

# 重置颜色(切换回默认颜色)
print(Style.RESET_ALL + '这是默认颜色的文本')

10 Read the password blasting script

import crypt
import colorama

# 定义密码
shaw_line = "root:$y$j9T$b8VajevNPKrgCkOfpJaZf.$87w.72igkRq6sPzbDOnaqTh4o3l4TkDWEagTPHq4K2C:19597:0:99999:7:::"

# 以:进行分割,组合密文组合,取下标1的值
crypt_text = shaw_line.split(":")[1]

print(crypt_text)
#密码中获取盐值
salt = crypt_text[0:crypt_text.rindex("$")]

file_path = "/home/kali/mytestcode/test.text"
with open( file=file_path, mode= "r") as f:
    for line in f:
        passwd = line.strip() 
        print(f"\r{colorama.Fore.RED}[-] Trying password: {passwd}", end= "")

        # passwd = "weiwei"
        # 明文和盐值组合密文
        new_crypt_text = crypt.crypt(passwd, salt)
        # 对比是否相等_crypt
        if new_crypt_text == crypt_text:
            print(f"{colorama.Fore.RED}[+] PASSWORD FOUND:{passwd}" )
    print(f"[-] pwssword not fo")

11 Send host ping packet (host alive)

11.01Install the scapy package
pip show scapy
11.02 Check the version of the installation package
import scapy
print(scapy.__version__)
11.03 ping code
from scapy.layers.inet import *

netmast = "10.9.75."
src="10.9.75.160"

for i in range(1,5):
    dst = f"{netmast}{i}"
    # print(dst)
    pkt = IP(src= src, dst= dst)/ICMP() # src目标地址, dst循环的地址
    res = sr1(pkt, timeout=1)
    if res and res.type == 0:
        print(f"{dst} is ALIVE!")

Print the result:

Received 46 packets, got 0 answers, remaining 1 packets
10.9.75.4
Begin emission:
WARNING: Mac address to reach destination not found. Using broadcast.
Finished sending 1 packets.
....................................................................................................................................................

12 Host survival code optimization

12.1 Shield WARNING information and do not display the point verbose= False
屏蔽WARNING的信息
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)  # 只有报错时才显示



不显示点
res = sr1(pkt, timeout=1, verbose= False)

After final optimization:

from scapy.layers.inet import *
from colorama import init, Fore, Back, Style

import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)

netmast = "10.9.75."  # 遍历扫描地址前缀
src="10.9.75.160"   # 自己的主机


for i in range(1,5):
    dst = f"{netmast}{i}"
    # print(dst)
    pkt = IP(src= src, dst= dst)/ICMP() # src目标地址, dst循环的地址
    res = sr1(pkt, timeout=1, verbose= False)
    if res and res.type == 0:
        print(Fore.RED + f"{dst} is ALIVE!")  # Fore.RED增加颜色
 

Print the result:

10.9.75.1 is ALIVE!

1 file reading

​ Reference video: Dark Horse nanny-level video

1.1 read() method:
文件对象.read(num)

num表示要从文件中读取的数据的长度(单位是字节),如果没有传入num,那么就表示读取文件中所有的数据。
1.2 readlines() method:

eadlines can read the contents of the entire file line by line at once, and returns a list in which the data of each line is an element.

f=open('python.txt')
content=f.readlines()
print(content) # ['hello world\n', 'abcdefg\n', 'aaa\n', 'bbb\n', 'ccc']

#关闭文件
f.close()
1.3 read() use case:
1.3.1 The content of the text.txt file is
在岁月的轮回里,
藏着世间的种种美,
高山巍峨耸入云霄,
江河奔腾破浩渺。
1.3.2 py executable file
# 打开文件
f = open("D:/test.txt","r", encoding="UTF-8")
print(type(f))

print(f"读取10个字节:{
      
      f.read(10)}")
print(f"read方法读取全部内容的结果:{
      
      f.read()}")
1.3.3 Printing results: Note: Execute the read() method twice. The second time will continue to read at the subscript after read.
<class '_io.TextIOWrapper'>
读取10个字节:在岁月的轮回里,
藏
read方法读取全部内容的结果:着世间的种种美,
高山巍峨耸入云霄,
江河奔腾破浩渺。
1.4 for loop reads file lines
# 打开文件
f = open("D:/test.txt","r", encoding="UTF-8")
print(type(f))
for line in f:
    print(f"读取10个字节:{
      
      line}")
f.close()

Print the result:

<class '_io.TextIOWrapper'>
读取10个字节:在岁月的轮回里,

读取10个字节:藏着世间的种种美,

读取10个字节:高山巍峨耸入云霄,

读取10个字节:江河奔腾破浩渺。
1.5 Practice reading and counting the number of times a certain character appears
=====test.txt内容========
itheima itcast python
itheima python itcast
beijing shanghai itheima
=======思路======= 
第一种. read() , count("itheima")
第二种.一行行的读取文件 按照空格切分,统计itheima的次数
===============
方式一:
f = open("D:/test.txt","r", encoding="UTF-8")
content = f.read()  # 读取全部内容
count = content.count("itheima")
print(f"的在文件中出现了:{
      
      count}次")
f.close()

打印结果: 3次

方式二:
f = open("D:/test.txt","r", encoding="UTF-8")
count = 0
for line in f:
	line = line.strip()
	words = line.split(" ") # 以空格分隔
	print(words)  # 打印每一行有个换行符 ['itheima', 'itcast', 'python\n']...,使用strip()
	for word in words:
		if word == "itheima":
			count += 1
print(count)
f.close()

打印结果出现:3
1.4 Summary of read reading methods
operate Function
File object = open(file, mode, encoding) Open a file to get a file object
File object.read(num) Read the specified length of bytes
without specifying num. Read the entire file.
File object.readline() read a line
File object.readlines() Read all lines and get a list
for line in file object for line in file object for loops file lines, obtaining one line of data at a time
File object.close() Close file object
with open() as f Open the file through the with open syntax and can automatically close it

2. Writing of files

Notice:

When write is called directly

When flush is called, the content will actually be written to the file; this is to avoid frequent operations on the hard disk, which will lead to a decrease in efficiency (save a bunch of files and write to the disk at once).

#1.打开文件
f=open('python.txt','w')

#2.文件写入
f write(hello world)

#3.内容刷新
f.flush()
2.1 write() file writing:

1. Write files using the open function mode.

2. The writing methods are:
wirte(), write content
flush(), refresh the content to the hard disk

Note:
In w mode, if the file does not exist, a new file will be created.
In w mode, if the file exists, the original content will be cleared
. close() method has the function of flush() method.

2.1.1 bill.txt content
周轮,2022-01-01,100000,消费,正式
周轮,2022-01-02,300000,收入,正式
周轮,2022-01-03,100000,消费,测试
2.1.2 py execution file, backup file writing
fr =open("D:/test.txt", "r", encoding="UTF-8")  # 打开文件得到文件对象,准备读取
fw =open("D:/bill.txt.bak", "w", encoding="UTF-8")  #打开文件得到文件对象,准备写入

# for 循环读取文件
for line in fr:
	line = line.strip()
	if line.split(",")[4] == "测试": # 判断内容,将满足的内容写出
		continue
	fw.write(line)  # 将内容写出去
	fw.write("\n")  #由于前面对内容进行了strip()的操作,所以要手动的写出换行符
fr.close()
fw.close()   # close内置flush()功能,flush將内存的文件写入磁盘

3. File appended content

​A mode is opened to add content

#1.打开文件,通过a模式打开即可
f=open('python.txt', 'a')

#2.文件写入
f.write('hello world')

#3.内容刷新
f.flush()

Note:
a mode, if the file does not exist, the file will be created.
a mode, if the file exists, the file will be appended to the end.

3.1 When there is no file, a automatically creates a file to append content. Example:
#打开文,不存在文件
f = open("D:/test1.txt","a",encoding="UTF-8")  #write写入
f.write("heima程序员")
f.flush()  #flush新
f.close()  #close关闭

# 打开路径,自动test1.txt文件及追加了内容
3.2 Continue a to write additional content:
f = open("D:/test1.txt", "a", encoding="UTF-8")  #打开一个存在的文件

f.write("\npython最佳保姆式") # write写入 \n换行

f.close()  #close关闭
3.3 Summary
1追加写入文件使用open函数的”a”模式进行写入

2.追加写入的方法有(和w模式一致):
	wirte(),写入内容
	flush(),刷新内容到硬盘中
	
3.注意事项:
	a模式,文件不存在,会创建新文件
	a模式,文件存在,会在原有内容后面继续写入
	可以使用”\n”来写出换行符

4 Exception handling

​ Reference video: Dark Horse nanny-level video

unusual characteristics

Exceptions are transitive

​ When an exception occurs in function func01 and the exception is not caught and handled,

​The exception will be passed to function func02. When func02 does not catch and handle the exception,

The main function will catch this exception, which is the transitivity of the exception.

Note:
When all functions do not catch exceptions, the program will
The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly.
report an errorThe external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly.

def func1():
    print("func1 开始执行")
    num=1/0
    #肯定有异常,除以0的异常
    print("func1 结束执行")

# 定义一个无异常的方法,调用上面的方法
def func2():
    print("func2 开始执行")
    func1()
    print("func2 结束执行")

#定义一个方法,调用上面的方法
def main():
    try:
        func2()
    except Exception as e:
        print(f"出现异常了,异常的信息是:{
      
      e}")

main()

Print results

func2 开始执行
func1 开始执行
出现异常了,异常的信息是:division by zero

5 module import and export

Reference video: Dark Horse high-quality nanny-level video

Modules need to be imported before use. The syntax for import is as follows:

[from 模块名] import [模块 | 类 | 变量 | 函数 | *] [as 别名]   # from是针对模块中某个方法去使用

How to import modules:

常用的组合形式如:
    import 模块名
    from   模块名  import  类、变量、方法等
    from   模块名  import  *
    import 模块名  as  别名
    from   模块名  import  功能名  as  别名
5.1 Basic syntax of import:
import 模块名
import 模块名1,模块名2

模块名.功能名()
5.2 Import case: Importing the time module requires calling time.sleep()
#导入时间模块
import time

print("开始")
#让程序睡眠1秒(阻塞)
time.sleep(1)
print("结束")
5.3 from basic syntax:

​ Use for a method in the module

from 模块名 import 功能名
功能名()

注意:
from time import *  # 是将某块中所有方法都导入
5.4 from case: import the sleep method in the time module, you can directly write the sleep call
#导入time时间模块中的sleep方法
from time import sleep

print("开始")
#让程序睡眠1秒(阻塞)
sleep(1)
print("结束")
5.5 from case: import * in the time module

Case: Import all methods in the time module, and you can directly write sleep calls

#导入时间模块中所有的方法
from time import *

print("开始")
#让程序睡眠1秒(阻塞)
sleep(1)
print("结束")

6 Custom modules

Reference video: Dark Horse nanny-level high-quality video

The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly.

6.1 External import does not allow functions to run by themselves
my_modulel.py file
def test(a, b):
	print(a + b)

if __name__ == '__main__': # 加入这个函数,也可以单独测试运行定义的函数
	test(1,2)
6.2 [__all__]Variables

If you don’t write __all__all, you can use it. If you write all, you can only use the functions in the list. All is only limited to *.

The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly.

6.3 Summary
 1.如何自定义模块并导入?
    在Python代码文件中正常写代码即可,通过import、from关键字和导
    入Python内置模块一样导入即可使用。

2._main_变量的功能是?
    if __main__==“_main_”表示,只有当程序是直接执行的才会进入
    if内部,如果是被导入的,则if无法进入
    
3.注意事项
	不同模块,同名的功能,如果都被导入,那么后导入的会覆盖先导入的

7 Custom python package

Reference video: Dark Horse nanny-level video

基于Python模块,我们可以在编写代码的时候,导入许
多外部代码来丰富功能。
但是,如果Python的模块太多了,就可能造成一定的混
乱,那么如何管理呢?
通过Python包的功能来管理。
7.1 The steps are as follows

The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly.

7.2 Basic steps in pycharm (creating packages)

​Select the project root directory -> Right-click [new] -> [Python Packag] -> Enter the package name (such as my_package) -> OK -> Create a new function module

Note: After creating a new package, such as (my_package), a file will be automatically created inside the package __init__.py. This file controls the import behavior of the package, such as [__all__ =['my_module1']]

​ You can create new files *.py in the package --> Respective function *.py files

7.3 Import custom packages
import my_package.my_modulel
import my_package.my_module2

my_package.my_modulel.info_print1()   #使用包里面函数


或者优化导入:
import my_package.my_module2 import info_print1

info_print1()   #使用包里面函数
7.4 Summary
1.什么是Python的包?
  包就是一个文件夹,里面可以存放许多Python的模块(代码文件),通
  过包,在逻辑上将一批模块归为一类,方便使用。
    
2._init_.py文件的作用?
  创建包会默认自动创建的文件,通过这个文件来表示一个文件夹是
  Python的包,而非普通的文件夹。
	
3.all变量的作用?
	同模块中学习到的是一个作用,控制import*能够导入的内容

8 third-party packages

Reference video: Dark Horse nanny-level video

8.1 What is a third-party package?

We know that a package can contain a bunch of Python modules, and each module contains many functions.
Therefore, we can think of a package as a collection of functions of the same type.

In the ecosystem of Python programs, there are many third-party packages (non-official Python), which can greatly help us improve development efficiency, such as: commonly used in scientific computing:
numpy package
commonly used in data analysis: pandas
package Commonly used in data calculation: pyspark, apache-flink package
Commonly used in graphic visualization: matplotlib, pyecharts
Commonly used in artificial intelligence: tensorflow

8.2 Install third-party packages

Install third-party packages-pip

The installation of third-party packages is very simple, we only need to use Python's built-in pip program.

Open the command prompt program that we have not seen for a long time, enter:
pipinstall package name
to quickly install third-party packages through the network

命令提示符cmd进行安装:

C:\Users\javac>pip install numpy
8.3 Network optimization of pip

Since pip is connected to foreign websites to download packages, sometimes the speed will be very slow.
We can use the following command to connect to the domestic website to install the package:
pip install -i https://pyp.ituna.tsinghua.edu.cn/simple package name

命令提示符cmd
C:\Users\javac> pip install	 -i https://pypi.tuna.tsinghua.edu.cn/simple numpy

https://pypi.tuna.tsinghua.edu.cn/simple is a website provided by Tsinghua University, which allows pip programs to download third-party packages.

Test to verify installation is successful

The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly.

8.4 pycharm installs third-party packages
8.4.1 Click python in the lower right corner --> select inter setting

The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly.

8.4.2 Click +

The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly.

8.4.3 After selection, select install-》Close the window-》Confirm to download in the background.

The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly.

8.4.4 Download status in the background

The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly.

9 color components

9.1 Installation
pip install colorama # 安装组件
9.2 Import into Python and print colored text:
from colorama import init, Fore, Back, Style

# 初始化 colorama
init()

# 使用不同的颜色打印文本
print(Fore.RED + '红色的文本')
print(Back.GREEN + '绿色背景的文本')
print(Fore.YELLOW + Back.BLUE + '黄色文字和蓝色背景的文本')

# 重置颜色(切换回默认颜色)
print(Style.RESET_ALL + '这是默认颜色的文本')

10 Read the password blasting script

import crypt
import colorama

# 定义密码
shaw_line = "root:$y$j9T$b8VajevNPKrgCkOfpJaZf.$87w.72igkRq6sPzbDOnaqTh4o3l4TkDWEagTPHq4K2C:19597:0:99999:7:::"

# 以:进行分割,组合密文组合,取下标1的值
crypt_text = shaw_line.split(":")[1]

print(crypt_text)
#密码中获取盐值
salt = crypt_text[0:crypt_text.rindex("$")]

file_path = "/home/kali/mytestcode/test.text"
with open( file=file_path, mode= "r") as f:
    for line in f:
        passwd = line.strip() 
        print(f"\r{
      
      colorama.Fore.RED}[-] Trying password: {
      
      passwd}", end= "")

        # passwd = "weiwei"
        # 明文和盐值组合密文
        new_crypt_text = crypt.crypt(passwd, salt)
        # 对比是否相等_crypt
        if new_crypt_text == crypt_text:
            print(f"{
      
      colorama.Fore.RED}[+] PASSWORD FOUND:{
      
      passwd}" )
    print(f"[-] pwssword not fo")

11 Send host ping packet (host alive)

11.01Install the scapy package
pip show scapy
11.02 Check the version of the installation package
import scapy
print(scapy.__version__)
11.03 ping code
from scapy.layers.inet import *

netmast = "10.9.75."
src="10.9.75.160"

for i in range(1,5):
    dst = f"{
      
      netmast}{
      
      i}"
    # print(dst)
    pkt = IP(src= src, dst= dst)/ICMP() # src目标地址, dst循环的地址
    res = sr1(pkt, timeout=1)
    if res and res.type == 0:
        print(f"{
      
      dst} is ALIVE!")

Print the result:

Received 46 packets, got 0 answers, remaining 1 packets
10.9.75.4
Begin emission:
WARNING: Mac address to reach destination not found. Using broadcast.
Finished sending 1 packets.
....................................................................................................................................................

12 Host survival code optimization

12.1 Shield WARNING information and do not display the point verbose= False
屏蔽WARNING的信息
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)  # 只有报错时才显示



不显示点
res = sr1(pkt, timeout=1, verbose= False)

After final optimization:

from scapy.layers.inet import *
from colorama import init, Fore, Back, Style

import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)

netmast = "10.9.75."  # 遍历扫描地址前缀
src="10.9.75.160"   # 自己的主机


for i in range(1,5):
    dst = f"{
      
      netmast}{
      
      i}"
    # print(dst)
    pkt = IP(src= src, dst= dst)/ICMP() # src目标地址, dst循环的地址
    res = sr1(pkt, timeout=1, verbose= False)
    if res and res.type == 0:
        print(Fore.RED + f"{
      
      dst} is ALIVE!")  # Fore.RED增加颜色
 

Print the result:

10.9.75.1 is ALIVE!

Guess you like

Origin blog.csdn.net/weixin_42786460/article/details/133098314