python3 自动生成 nginx 的端口映射, 端口定义的:列表,范围,源端口和目标端口; 服务的端口: samba, mysql, mqtt, mail, webPublic, webInside

本文涉及的产品
实时数仓Hologres,5000CU*H 100GB 3个月
智能开放搜索 OpenSearch行业算法版,1GB 20LCU 1个月
实时计算 Flink 版,5000CU*H 3个月
简介: python3 自动生成 nginx 的端口映射
#!/bin/python3
import os
# from portServer import *                      # 可以将下面 samba 等定义的端口函数,存放在 portServer.py 里,然后这里导入所有函数

# 定义全局变量的初始值
type = ""
rank_type = ""
ip = ""
ip_segment = ""
port_list = []
source_port = []
dest_port = []
portmin = 0
portmax = 0
vpn_flag = 0
vpn_ip = "10.1.1.3"

# 定义服务函数
def samba():
    global type, rank_type, ip, port_list       # 如果需要修改全局变量,都需要加  global 全局声明
    type = "samba"
    rank_type = "list"
    ip = "192.168.122.1"
    port_list = [139, 445]

def mysql():
    global type, rank_type, ip, port_list
    type = "mysql"
    rank_type = "list"
    ip = "192.168.122.80"
    port_list = [3306]

def mqtt():
    global type, rank_type, ip, port_list
    type = "mqtt"
    rank_type = "list"
    ip = "192.168.122.80"
    port_list = [1883, 8883, 8083, 8084, 18083, 4370, 5370]

def mail():
    global type, rank_type, ip, port_list
    type = "mail"
    rank_type = "list"
    ip = "192.168.122.81"
    port_list = [143, 993, 110, 995, 465, 587]

def webPublic():
    global type, rank_type, ip, portmin, portmax
    type = "web"
    rank_type = "range"
    ip = "192.168.122.80"
    portmin = 62010
    portmax = 62018 

def webInside():
    global type, rank_type, ip, port_list
    type = "insideweb"
    rank_type = "list"
    ip = "192.168.122.80"
    port_list = [3000, 3000, 3000, 3000]
def ssh():
    global type, rank_type, ip_segment, ip, source_port, dest_port
    type = "ssh"
    rank_type = "SouceDest"
    ip_segment = "192.168.122"
    ip = [22, 22, 22, 22, 22, 22]    
    source_port = [22, 22, 22, 22, 22, 22]
    dest_port = [22, 22, 22, 22, 22, 22]
def mstsc():
    global type, rank_type, ip_segment, ip, source_port, dest_port
    type = "mstsc"
    rank_type = "SouceDest"
    ip_segment = "192.168.122"
    ip = [200, 200]
    source_port = [3389, 3389]
    dest_port = [3389, 3389]

# 创建目标文件夹并附加权限,如果 tcp.conf 不存在则创建它
def create_directory(tcp_file_dir, mode=0o777):                     # 定义函数,有两个参数: 1. 文件路径,2. 定义的权限: 0o 代表8进制
    os.makedirs(tcp_file_dir, exist_ok=True)                        # 1. mkdir:  make制作,dirs目录。  2. 目录存在不抛出异常
    tcp_conf_path = os.path.join(tcp_file_dir, 'tcp.conf')          # 拼接目录 tcp.conf 的完整路径
    if not os.path.exists(tcp_conf_path):                           # 判断目录 不 存在
        with open(tcp_conf_path, 'w') as file:                      # 1.上下文管理器,作用:在 with 板块里面的代码执行完,自动关闭文件操作流,和其他需要手动操作关闭的动作
                                                                    # 2.打开文件,模式w写,覆盖 和 不存在就新建文件; 3. as file: 这个一个动作定义为一个 别名 file 写文件的对象函数; 并继承 open() 函数的内置方法如读写操作
            file.write("stream {\n")                                # 1.file 函数动作传入参数,自动写入字符

# 主函数
def main():
    global tcp_file_dir, vpn_ip, vpn_flag
    tcp_file_dir = '/datadisk/eisc/wwwconf/tcp/'

    # 用户输入和逻辑判断
    vpn_input = input("当前电脑是放置在家庭吗?(y/n): ").strip().lower() #变量vpn_input=input内置函数输入的字符串,strip()删除空白字符;  lower() 将大写转为小写字母
    vpn_flag = 0 if vpn_input == 'y' else 1                         # 先给你数值,你要满足的我条件: 输入为y 就不做任何操作。不满足我条件,将重新给你数值 为1;  当前是三元操作

    port_list = ['samba', 'mysql', 'mqtt', 'mail', 'webPublic', 'webInside', 'ssh', 'mstsc']

    print("选择的服务组有:")
    for i, port_number in enumerate(port_list):                     # enumerate 遍历数组会返回两个参数,1.元素角标, 2.元素
        print(f"{i}: {port_number}")

    print("选择您要映射的端口组。使用空格分隔。例如: 0 1 2 3 (输入 '666' 选择所有服务)")
    vpn_str_input = input("输入: ").strip()                         # 接收输入参数,删除空白字符
    vpn_str_list = vpn_str_input.split()                           # split()  函数: 将字符串转为列表数组; 可以指定逗号分隔符案例: split(",") 

    if '666' in vpn_str_list:                                      # 判断 all 元素是数组的成员 ; vpn_str_list 是选择的数字数组
        vpn_select_port_list = port_list
    else:
        vpn_select_port_list = [port_list[int(port_number)] for port_number in vpn_str_list]
                                                                    # 1. port_list[int(port_number)] 数组+角标获取元素; 而角标 port_number 是通过选择端口组的数组 在for 遍历得来

    print(f"选择的端口组为: {vpn_select_port_list}")                   # f 格式化字符串,允许字符串包含表达式

    # 创建目录并初始化 tcp.conf 文件
    create_directory(tcp_file_dir)

    # 根据选择的服务调用相应的函数
    for service_name in vpn_select_port_list:
        globals()[service_name]()                                   # globals() 动态获取访问和操作函数 service_name  里面定义的全局变量
                                                                    # python 所有函数板块使用缩进区分结束。
                                                                    # 如 match rank_type: 位于 for 对齐将不会循环多次,不受for控制
        # 根据不同的 rank_type 调用不同的创建函数
        match rank_type:
            case 'list':
                print(f"端口类型 {service_name} 是列表类型,分类进入 createListPort 生成")
                createListPort()
            case 'range':
                print(f"端口类型 {service_name} 是范围,分类进入 createRangePort 生成")
                createRangePort()
            case 'SouceDest':
                print(f"端口类型 {service_name} 是源端口和目标绑定端口,分类进入 createSouceDestPort 生成")
                createSouceDestPort()
            case _:
                print(f"未知的rank_type: {rank_type}")

    # 添加额外的配置到 tcp.conf 文件
    with open(os.path.join(tcp_file_dir, 'tcp.conf'), 'a') as file: # os.path.join 拼接文件完整路径,open打开文件 然后将这个动作方法 定义为file 对象函数,同时继承open() 函数的方法,如读写; 相当于 open() 函数被 file 函数继承所有方法
        file.write("}  # End of stream configuration\n")            # 使用对象函数的方法 写文件

# 创建列表类型端口
def createListPort():
    with open(os.path.join(tcp_file_dir, 'tcp.conf'), 'a') as file:
        file.write(f"#-------  {type}  ---------#\n")
        for port in port_list:
            if vpn_flag == 1:
                ip_address = vpn_ip
            else:
                ip_address = f"{ip_segment}.{ip}"
            file.write(f"upstream {type}-{port} {
   { server {ip_address}:{port}; }} # {type}\n")
            file.write(f"server {
   { listen {port}; proxy_pass {type}-{port}; }} # {type}\n\n")

# 创建范围类型端口
def createRangePort():
    with open(os.path.join(tcp_file_dir, 'tcp.conf'), 'a') as file:
        file.write(f"#-------  {type}  ---------#\n")
        for port in range(portmin, portmax):
            if vpn_flag == 1:
                ip_address = vpn_ip
            else:
                ip_address = f"{ip_segment}.{ip}"
            file.write(f"upstream {type}-{port} {
   { server {ip_address}:{port}; }} # {type}\n")
            file.write(f"server {
   { listen {port}; proxy_pass {type}-{port}; }} # {type}\n\n")

# 创建源端口和目标端口映射类型
def createSouceDestPort():
    with open(os.path.join(tcp_file_dir, 'tcp.conf'), 'a') as file:
        file.write(f"#-------  {type}  ---------#\n")
        for i, ip_suffix in enumerate(ip):
            if vpn_flag == 1:
                ip_address = vpn_ip
                sport = dest_port[i]
                dport = dest_port[i]
            else:
                ip_address = f"{ip_segment}.{ip_suffix}"
                sport = source_port[i]
                dport = dest_port[i]

            file.write(f"upstream {type}-{dport} {
   { server {ip_address}:{sport}; }} # {type}\n")
            file.write(f"server {
   { listen {dport}; proxy_pass {type}-{dport}; }} # {type}\n\n")

if __name__ == '__main__':
    main()
相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助     相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
6天前
|
测试技术 开发者 Python
在 Python 中创建列表时,应该写 `[]` 还是 `list()`?
在 Python 中,创建列表有两种方法:使用方括号 `[]` 和调用 `list()` 函数。虽然两者都能创建空列表,但 `[]` 更简洁、高效。性能测试显示,`[]` 的创建速度比 `list()` 快约一倍。此外,`list()` 可以接受一个可迭代对象作为参数并将其转换为列表,而 `[]` 则需要逐一列举元素。综上,`[]` 适合创建空列表,`list()` 适合转换可迭代对象。
在 Python 中创建列表时,应该写 `[]` 还是 `list()`?
|
9天前
|
数据处理 Python
Python实用记录(十):获取excel数据并通过列表的形式保存为txt文档、xlsx文档、csv文档
这篇文章介绍了如何使用Python读取Excel文件中的数据,处理后将其保存为txt、xlsx和csv格式的文件。
27 3
Python实用记录(十):获取excel数据并通过列表的形式保存为txt文档、xlsx文档、csv文档
|
1天前
|
数据处理 开发者 Python
Python中的列表推导式:一种优雅的代码简化技巧####
【10月更文挑战第15天】 本文将深入浅出地探讨Python中列表推导式的使用,这是一种强大且简洁的语法结构,用于从现有列表生成新列表。通过具体示例和对比传统循环方法,我们将揭示列表推导式如何提高代码的可读性和执行效率,同时保持语言的简洁性。无论你是Python初学者还是有经验的开发者,掌握这一技能都将使你的编程之旅更加顺畅。 ####
9 1
|
9天前
|
关系型数据库 MySQL 数据库
Mysql学习笔记(四):Python与Mysql交互--实现增删改查
如何使用Python与MySQL数据库进行交互,实现增删改查等基本操作的教程。
20 1
|
10天前
|
开发者 Python
探索Python中的列表推导式:简化代码的利器
在Python编程中,列表推导式是一种简洁而强大的工具,它允许开发者以一行代码实现复杂的列表操作。本文将深入探讨列表推导式的语法、优势以及实际应用,帮助读者更好地利用这一特性来优化代码。
|
11天前
|
大数据 数据处理 Python
探索Python中的列表推导式
【10月更文挑战第6天】 在Python编程中,列表推导式(List Comprehension)是一种简洁而强大的工具,用于生成列表。通过结合循环和条件语句,列表推导式可以在一行代码中实现复杂的列表操作。本文将深入探讨列表推导式的语法、常见用法以及一些高级技巧,帮助你更有效地使用这一特性。
14 1
|
14天前
|
存储 Python
python列表操作和方法
python列表操作和方法
15 1
|
17天前
|
存储 索引 Python
反转Python列表的4种方法
反转Python列表的4种方法
19 2
|
18天前
|
存储 大数据 数据处理
Python 中的列表推导式与生成器:特性、用途与区别
Python 中的列表推导式与生成器:特性、用途与区别
14 2
|
18天前
|
数据处理 Python
Python编程-利用datetime模块生成当前年份之前指定的间隔所有年份的日期列表和csv文件
Python编程-利用datetime模块生成当前年份之前指定的间隔所有年份的日期列表和csv文件
15 1

热门文章

最新文章