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

本文涉及的产品
实时数仓Hologres,5000CU*H 100GB 3个月
实时计算 Flink 版,5000CU*H 3个月
智能开放搜索 OpenSearch行业算法版,1GB 20LCU 1个月
简介: 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()
相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助     相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
2天前
|
数据可视化 关系型数据库 MySQL
ELK实现nginx、mysql、http的日志可视化实验
通过本文的步骤,你可以成功配置ELK(Elasticsearch, Logstash, Kibana)来实现nginx、mysql和http日志的可视化。通过Kibana,你可以直观地查看和分析日志数据,从而更好地监控和管理系统。希望这些步骤能帮助你在实际项目中有效地利用ELK来处理日志数据。
143 90
|
12天前
|
数据管理 关系型数据库 MySQL
数据管理服务DMS支持MySQL数据库的无锁结构变更
本文介绍了使用Sysbench准备2000万数据并进行全表字段更新的操作。通过DMS的无锁变更功能,可在不锁定表的情况下完成结构修改,避免了传统方法中可能产生的锁等待问题。具体步骤包括:准备数据、提交审批、执行变更及检查表结构,确保变更过程高效且不影响业务运行。
35 2
|
1月前
|
网络协议 Java Shell
java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
66 7
|
2月前
|
安全 网络协议 网络安全
【Azure APIM】APIM服务配置网络之后出现3443端口不通,Management Endpoint不健康状态
如果没有关联的网络安全组,则阻止所有网络流量通过子网和网络接口。
65 30
|
19天前
|
SQL 关系型数据库 MySQL
Python中使用MySQL模糊查询的方法
本文介绍了两种使用Python进行MySQL模糊查询的方法:一是使用`pymysql`库,二是使用`mysql-connector-python`库。通过这两种方法,可以连接MySQL数据库并执行模糊查询。具体步骤包括安装库、配置数据库连接参数、编写SQL查询语句以及处理查询结果。文中详细展示了代码示例,并提供了注意事项,如替换数据库连接信息、正确使用通配符和关闭数据库连接等。确保在实际应用中注意SQL注入风险,使用参数化查询以保障安全性。
|
4月前
|
传感器 物联网 机器人
定义微Python
MicroPython 是一种精简高效的 Python 解释器,专为微控制器和嵌入式系统设计,支持通过 Python 代码进行快速开发和调试。它具有低资源消耗的特点,适用于物联网设备。
126 62
|
3月前
|
关系型数据库 MySQL 数据库
Python处理数据库:MySQL与SQLite详解 | python小知识
本文详细介绍了如何使用Python操作MySQL和SQLite数据库,包括安装必要的库、连接数据库、执行增删改查等基本操作,适合初学者快速上手。
446 15
|
3月前
|
Shell Python
[oeasy]python049_[词根溯源]locals_现在都定义了哪些变量
本文介绍了Python中`locals()`函数的使用方法及其在调试中的作用。通过回顾变量赋值、连等赋值、解包赋值等内容,文章详细解释了如何利用`locals()`函数查看当前作用域内的本地变量,并探讨了变量声明前后以及导入模块对本地变量的影响。最后,文章还涉及了一些与“local”相关的英语词汇,如`locate`、`allocate`等,帮助读者更好地理解“本地”概念在编程及日常生活中的应用。
52 9
|
4月前
|
安全 网络安全 网络架构
什么是端口转发?什么是端口映射?如何设置端口映射
端口映射与端口转发是网络配置中两个常被混淆的概念。端口映射是指将外部网络请求通过路由器转发至内部网络特定主机的过程,增强了内网安全性。而端口转发则是指路由器依据端口将外部请求定向至具体设备,实现内外网通信。两者虽相似,但应用场景和原理有所不同。通过工具如花生壳,可轻松设置端口映射,实现外网访问内网服务。
653 1
|
4月前
|
安全 Linux 网络安全
nmap 是一款强大的开源网络扫描工具,能检测目标的开放端口、服务类型和操作系统等信息
nmap 是一款强大的开源网络扫描工具,能检测目标的开放端口、服务类型和操作系统等信息。本文分三部分介绍 nmap:基本原理、使用方法及技巧、实际应用及案例分析。通过学习 nmap,您可以更好地了解网络拓扑和安全状况,提升网络安全管理和渗透测试能力。
304 5

热门文章

最新文章