Python 语言笔记(网络空间安全) 这是一份全面、详尽、通俗易懂的 Python 语言学习笔记,结合网络空间安全学习要求,适合初学者和进阶学习者。笔记涵盖 Python 基础语法、数据类型、控制流、函数、模块、文件操作、异常处理、面向对象编程,以及网络安全相关的高级主题。每部分配有示例代码和解释,帮助快速上手并深入理解。
1. Python 简介 Python 是一种高级、解释型、通用编程语言,由 Guido van Rossum 于 1991 年创建,因其语法简洁、功能强大而广受欢迎。它在 Web 开发、数据分析、人工智能和网络安全等领域有广泛应用。
特点:
易学易用 :语法接近自然语言,适合初学者。
开源免费 :拥有庞大社区和丰富的第三方库。
跨平台 :支持 Windows、macOS、Linux 等系统。
多范式 :支持面向过程、面向对象和函数式编程。
2. 环境搭建 学习 Python 前需安装 Python 环境,推荐使用 Python 3.x 版本。
安装 Python:
访问 Python 官网 下载安装包。
安装时勾选“Add Python to PATH”。
在命令行输入 python --version 检查安装是否成功。
推荐工具:
PyCharm :专业 IDE,适合开发大型项目。
VS Code :轻量编辑器,配合 Python 插件使用。
Jupyter Notebook :交互式环境,适合数据分析和安全脚本测试。
3. 基础语法 3.1 变量和数据类型 Python 变量无需声明类型,赋值时自动确定。
1 2 3 4 x = 10 y = 3.14 name = "Alice" is_ok = True
基本数据类型:
整数(int) :如 5, -10
浮点数(float) :如 3.14, -0.5
字符串(str) :如 “Hello”, ‘Python’
布尔值(bool) :True 或 False
类型转换: 1 2 3 4 age = 25 age_str = str (age) pi = 3.14 pi_int = int (pi)
3.2 运算符 算术运算符:
+(加)、-(减)、*(乘)、/(除)、//(整除)、%(取模)、**(幂)
比较运算符:
逻辑运算符:
示例: 1 2 3 4 5 6 7 8 9 a = 10 b = 3 print (a + b) print (a / b) print (a // b) print (a % b) print (a ** b) print (a > b) print (a > 5 and b < 5 )
4. 控制流 4.1 条件语句 if-elif-else: 1 2 3 4 5 6 7 age = 18 if age < 18 : print ("未成年" ) elif age == 18 : print ("刚成年" ) else : print ("成年" )
三元运算符: 1 status = "成年" if age >= 18 else "未成年"
4.2 循环语句 for 循环:
1 2 3 fruits = ["apple" , "banana" , "cherry" ] for fruit in fruits: print (fruit)
1 2 for i in range (5 ): print (i)
while 循环: 1 2 3 4 count = 0 while count < 5 : print (count) count += 1
循环控制:
break:跳出循环
continue:跳过本次循环
1 2 3 4 for i in range (10 ): if i == 5 : break print (i)
5. 数据结构 5.1 列表(List) 特点:有序、可变、允许重复 1 my_list = [1 , 2 , 3 , "a" , "b" ]
常用方法:
append():加到末尾
insert():插入到指定位置
remove():删除指定元素
pop():删除并返回元素
sort():排序
示例: 1 2 my_list.append(4 ) my_list.remove("a" )
5.2 元组(Tuple) 特点:有序、不可变 1 2 my_tuple = (1 , 2 , 3 , "a" ) print (my_tuple[0 ])
5.3 字典(Dictionary) 特点:键值对、无序、可变 1 my_dict = {"name" : "Alice" , "age" : 25 }
常用方法:
keys():所有键
values():所有值
items():所有键值对
get():获取值
示例: 1 2 print (my_dict["name" ]) my_dict["age" ] = 26
5.4 集合(Set) 特点:无序、不重复
常用方法:
add():添加
remove():删除
union():并集
intersection():交集
示例:
6. 函数 定义与调用: 1 2 3 4 def greet (name ): return f"Hello, {name} !" print (greet("Alice" ))
参数类型:
1 2 3 def add (a, b=0 ): return a + b print (add(5 ))
1 2 3 def total (*args ): return sum (args) print (total(1 , 2 , 3 ))
匿名函数: 1 2 square = lambda x: x ** 2 print (square(5 ))
7. 模块和包 导入模块: 1 2 import mathprint (math.pi)
自定义模块: 假设有个文件 mymodule.py:
1 2 3 def say_hi (): print ("Hi!" )
使用:
1 2 from mymodule import say_hisay_hi()
8. 文件操作 读写文件: 1 2 3 4 5 6 7 with open ("test.txt" , "w" ) as file: file.write("Hello!" ) with open ("test.txt" , "r" ) as file: print (file.read())
9. 异常处理 try-except: 1 2 3 4 try : x = 1 / 0 except ZeroDivisionError: print ("不能除以 0" )
raise 抛异常: 1 2 if age < 18 : raise ValueError("年龄太小" )
10. 面向对象编程 类与对象: 1 2 3 4 5 6 7 8 9 class Dog : def __init__ (self, name ): self .name = name def bark (self ): return "Woof!" dog = Dog("Buddy" ) print (dog.bark())
继承: 1 2 3 4 5 6 class Puppy (Dog ): def bark (self ): return "Yip!" puppy = Puppy("Max" ) print (puppy.bark())
11. 高级主题 装饰器: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 def deco (func ): def wrapper (): print ("开始" ) func() print ("结束" ) return wrapper @deco def say (): print ("Hello" ) say()
生成器: 1 2 3 4 5 6 7 8 def count (n ): i = 0 while i < n: yield i i += 1 for x in count(3 ): print (x)
12. 标准库与第三方库 标准库: 1 2 import osprint (os.getcwd())
第三方库: 安装:pip install requests
使用:
1 2 3 import requestsresponse = requests.get("https://api.github.com" ) print (response.text)
13. Python 在网络空间安全中的应用 Python 因其简洁性和丰富库在网络安全领域广受欢迎,适用于自动化任务、网络扫描、数据加密等。
13.1 网络安全中的 Python 概述 Python 在网络安全中的优势包括:
易用性 :语法简单,适合快速开发安全脚本。
丰富库 :如 Scapy、Requests、Cryptography,支持多种安全任务。
跨平台 :可在多种操作系统上运行。
社区支持 :大量开源项目和论坛提供支持。
应用领域:
网络扫描 :检测开放端口和网络漏洞。
Web 安全 :测试 SQL 注入、跨站脚本攻击(XSS)等。
数据加密 :保护敏感信息。
自动化 :简化日志分析、监控等任务。
13.2 基础编程在安全中的应用 13.2.1 变量和数据类型 在安全脚本中,常用数据类型处理网络数据。
1 2 3 4 port = 8080 ip_address = "192.168.1.1" open_ports = [22 , 80 , 443 ] user_data = {"username" : "admin" , "password" : "securepass" }
13.2.2 控制结构 用于决策和迭代,如检查端口状态。
1 2 3 4 if port in open_ports: print (f"端口 {port} 开放" ) else : print (f"端口 {port} 关闭" )
13.3 网络编程与安全 13.3.1 使用 Scapy 进行网络包操控 Scapy 用于创建、发送和分析网络包。
1 2 3 4 5 6 7 8 9 from scapy.all import *packet = IP(dst="8.8.8.8" ) / ICMP() response = sr1(packet) if response: print ("响应:" , response.summary()) else : print ("无响应" )
13.3.2 端口扫描 编写简单的端口扫描器。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 import socketdef scan_port (host, port ): try : sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(1 ) result = sock.connect_ex((host, port)) if result == 0 : print (f"端口 {port} 开放" ) else : print (f"端口 {port} 关闭" ) sock.close() except Exception as e: print (f"错误:{e} " ) scan_port("192.168.1.1" , 80 )
13.4 Web 安全与 Python 13.4.1 使用 Requests 进行安全 Web 请求 1 2 3 4 5 6 7 8 9 10 11 import requestsurl = "https://example.com" try : response = requests.get(url) if response.status_code == 200 : print ("网站正常" ) else : print ("网站异常" ) except requests.exceptions.RequestException as e: print (f"请求错误:{e} " )
13.4.2 检测 SQL 注入漏洞 1 2 3 4 5 6 7 8 9 10 11 import requestsurl = "https://example.com/login" data = {"username" : "admin' OR '1'='1" , "password" : "" } response = requests.post(url, data=data) if "Invalid username or password" not in response.text: print ("可能存在 SQL 注入漏洞" ) else : print ("未检测到 SQL 注入" )
13.5 数据加密与解密 13.5.1 对称加密 1 2 3 4 5 6 7 8 from cryptography.fernet import Fernetkey = Fernet.generate_key() cipher = Fernet(key) message = b"Hello, World!" encrypted = cipher.encrypt(message) decrypted = cipher.decrypt(encrypted) print (decrypted.decode())
13.5.2 哈希函数 1 2 3 4 5 6 import hashlibdata = b"password123" hash_object = hashlib.sha256(data) hex_dig = hash_object.hexdigest() print (hex_dig)
13.6 自动化安全任务 13.6.1 日志分析 1 2 3 4 5 6 7 8 import relog_line = "2025-04-19 11:35:00 INFO User logged in: admin" match = re.search(r"User logged in: (\w+)" , log_line)if match : user = match .group(1 ) print (f"用户 {user} 登录" )
13.6.2 漏洞扫描 1 2 3 4 5 6 7 8 9 10 11 12 import requestsdef check_vulnerability (url ): response = requests.get(url) if "vulnerable" in response.text: print (f"{url} 存在漏洞" ) else : print (f"{url} 无漏洞" ) urls = ["https://example.com" , "https://test.com" ] for url in urls: check_vulnerability(url)
13.7 安全编码实践 13.7.1 输入验证 1 2 3 4 5 6 7 def safe_input (user_input ): safe = user_input.replace("'" , "" ) return safe user_input = input ("输入用户名:" ) safe_name = safe_input(user_input) print (f"欢迎,{safe_name} " )
13.7.2 使用安全协议 1 2 3 import requestsresponse = requests.get("https://example.com" )
13.7.3 异常处理 1 2 3 4 5 try : response = requests.get("https://example.com" ) response.raise_for_status() except requests.exceptions.RequestException as e: print (f"错误:{e} " )
13.8 与安全工具集成 13.8.1 自动化 Nmap 扫描 1 2 3 4 import subprocessresult = subprocess.run(["nmap" , "-p" , "80" , "192.168.1.1" ], capture_output=True , text=True ) print (result.stdout)
14. 学习建议
多实践 :编写代码,调试错误。
做项目 :如端口扫描器、日志分析工具。
阅读文档 :参考 Python 官方文档 和安全相关资源。
参与社区 :加入 Stack Overflow、Reddit(r/learnpython、r/cybersecurity)等。