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

本文涉及的产品
智能开放搜索 OpenSearch行业算法版,1GB 20LCU 1个月
实时数仓Hologres,5000CU*H 100GB 3个月
实时计算 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()
AI 代码解读
相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助     相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
打赏
0
0
0
0
29
分享
相关文章
Python列表推导式:简洁高效的数据处理利器
Python列表推导式:简洁高效的数据处理利器
148 80
淘宝关键词搜索商品列表API接入指南(含Python示例)
淘宝关键词搜索商品列表API是淘宝开放平台的核心接口,支持通过关键词检索商品,适用于比价、选品、市场分析等场景。接口提供丰富的筛选与排序功能,返回结构化数据,含商品ID、标题、价格、销量等信息。开发者可使用Python调用,需注意频率限制与错误处理,建议先在沙箱环境测试。
[oeasy]python094_使用python控制音符列表_midi_文件制作
本文介绍了如何使用Python控制音符列表制作MIDI文件。首先回顾了列表下标索引(正数和负数)的用法,接着通过`mido`库实现MIDI文件生成。以《两只老虎》为例,详细解析了代码逻辑:定义音高映射、构建旋律列表、创建MIDI文件框架,并将音符插入音轨。还探讨了音符时值与八度扩展的实现方法。最终生成的MIDI文件可通过不同平台播放或编辑。总结中提到,此技术可用于随机生成符合调性的旋律,同时引发对列表其他实际应用的思考。
50 5
[oeasy]python089_列表_删除列表项_remove_列表长度_len
本文介绍了Python列表(list)的操作方法,重点讲解了`remove`方法的使用。通过实例演示如何删除列表中的元素,探讨了`ValueError`异常产生的原因,并分析了时间复杂度O(n)的概念。同时提及了`clear`方法清空列表的功能及`len`函数获取列表长度的用法。最后以购物清单为例,展示列表的实际应用场景,并预告快速生成列表的方法将在后续内容中介绍。
155 62
深入研究: 亚马逊 amazon商品列表API接口 Python 攻略
本内容介绍了亚马逊商品列表API接口的应用价值与操作方法。在电商数据分析驱动决策的背景下,该接口可自动化获取商品基本信息(如名称、价格、评价等),助力市场调研、竞品分析及价格监控等场景。接口通过设置搜索条件(关键词、类目、价格范围等)筛选商品列表,以GET请求方式调用,返回JSON或XML格式数据,包含商品基本信息、价格、评价、图片链接及库存状态等内容。合理使用此接口可提升运营效率、降低人力成本并及时掌握市场动态。
深入浅出:拼多多商品列表API接口Python攻略
拼多多是中国领先的社交电商平台,为开发者提供了丰富的API接口,用于集成商品数据到第三方应用。通过Python可以轻松调用这些API获取商品列表。主要步骤包括:1) 安装必要库(如`requests`);2) 使用AppKey和AppSecret获取访问令牌;3) 调用商品列表API,传入参数如商品ID、页码等;4) 解析返回的JSON数据提取所需信息。按照此流程,开发者能够快速实现与拼多多平台的数据交互。
ELK实现nginx、mysql、http的日志可视化实验
通过本文的步骤,你可以成功配置ELK(Elasticsearch, Logstash, Kibana)来实现nginx、mysql和http日志的可视化。通过Kibana,你可以直观地查看和分析日志数据,从而更好地监控和管理系统。希望这些步骤能帮助你在实际项目中有效地利用ELK来处理日志数据。
387 90
[oeasy]python091_列表_索引_index_中括号_索引函数
本文介绍了Python中列表与字符串的索引及index函数用法。通过range生成列表,使用索引[]访问和修改列表元素,index函数查找元素位置。字符串支持索引访问但不可直接修改。还探讨了16进制数在Python中的表示方法,以及日期、月份等特殊字符的Unicode范围。最后总结了列表与字符串操作的区别,并预告后续内容,提供蓝桥云课、GitHub和Gitee链接供进一步学习。
90 20
如何将Python元组转换为列表
本文介绍了在Python中将元组转换为列表的方法。通过内置的`list()`函数,可以轻松地将一个元组转换为列表。此外,文章还提供了如何使用列表推导式和`itertools.chain()`方法将包含多个元组的列表展平为单一列表的示例。这些方法对于数据处理和转换非常实用,能够帮助开发者高效操作序列类型数据。文中附有代码实例及输出结果,便于理解与实践。

热门文章

最新文章

推荐镜像

更多
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等

登录插画

登录以查看您的控制台资源

管理云资源
状态一览
快捷访问