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

简介: 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()
相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。   相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情: https://www.aliyun.com/product/rds/mysql 
目录
相关文章
|
3月前
|
Unix Linux Shell
指定端口-SSH连接的目标(告别 22 端口暴力破解)
本文介绍了 SSH 命令 `ssh -p 44907 root@IP` 的含义与使用方法,包括命令结构拆解、完整示例及执行过程详解,帮助用户安全地远程登录服务器。
382 0
|
9月前
|
数据可视化 关系型数据库 MySQL
ELK实现nginx、mysql、http的日志可视化实验
通过本文的步骤,你可以成功配置ELK(Elasticsearch, Logstash, Kibana)来实现nginx、mysql和http日志的可视化。通过Kibana,你可以直观地查看和分析日志数据,从而更好地监控和管理系统。希望这些步骤能帮助你在实际项目中有效地利用ELK来处理日志数据。
701 90
|
9月前
|
关系型数据库 MySQL PHP
源码编译安装LAMP(HTTP服务,MYSQL ,PHP,以及bbs论坛)
通过以上步骤,你可以成功地在一台Linux服务器上从源码编译并安装LAMP环境,并配置一个BBS论坛(Discuz!)。这些步骤涵盖了从安装依赖、下载源代码、配置编译到安装完成的所有细节。每个命令的解释确保了过程的透明度,使即使是非专业人士也能够理解整个流程。
280 18
|
11月前
|
安全 网络协议 网络安全
【Azure APIM】APIM服务配置网络之后出现3443端口不通,Management Endpoint不健康状态
如果没有关联的网络安全组,则阻止所有网络流量通过子网和网络接口。
252 30
|
10月前
|
数据管理 关系型数据库 MySQL
数据管理服务DMS支持MySQL数据库的无锁结构变更
本文介绍了使用Sysbench准备2000万数据并进行全表字段更新的操作。通过DMS的无锁变更功能,可在不锁定表的情况下完成结构修改,避免了传统方法中可能产生的锁等待问题。具体步骤包括:准备数据、提交审批、执行变更及检查表结构,确保变更过程高效且不影响业务运行。
592 2
|
10月前
|
网络协议 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-优雅草卓伊凡解决方案
692 7
|
缓存 负载均衡 应用服务中间件
Nginx 实现一个端口代理多个前后端服务
【10月更文挑战第19天】Nginx 的强大功能不仅限于此,它还可以与其他技术和工具相结合,为我们的应用提供更强大的支持和保障。在不断发展的互联网时代,掌握 Nginx 的使用技巧将为我们的工作和生活带来更多的便利和效益。
|
安全 网络安全 网络架构
什么是端口转发?什么是端口映射?如何设置端口映射
端口映射与端口转发是网络配置中两个常被混淆的概念。端口映射是指将外部网络请求通过路由器转发至内部网络特定主机的过程,增强了内网安全性。而端口转发则是指路由器依据端口将外部请求定向至具体设备,实现内外网通信。两者虽相似,但应用场景和原理有所不同。通过工具如花生壳,可轻松设置端口映射,实现外网访问内网服务。
2574 1
|
安全 Linux 网络安全
nmap 是一款强大的开源网络扫描工具,能检测目标的开放端口、服务类型和操作系统等信息
nmap 是一款强大的开源网络扫描工具,能检测目标的开放端口、服务类型和操作系统等信息。本文分三部分介绍 nmap:基本原理、使用方法及技巧、实际应用及案例分析。通过学习 nmap,您可以更好地了解网络拓扑和安全状况,提升网络安全管理和渗透测试能力。
805 5
|
tengine 关系型数据库 MySQL
Tengine、Nginx安装MySQL数据库命令教程
本指南详细介绍了在Linux系统上安装与配置MySQL数据库的步骤。首先通过下载并安装MySQL社区版本,接着启动MySQL服务,使用`systemctl start mysqld.service`命令。若启动失败,可尝试使用`sudo /etc/init.d/mysqld start`。利用`systemctl status mysqld.service`检查MySQL的服务状态,确保其处于运行中。通过日志文件获取初始密码,使用该密码登录数据库,并按要求更改初始密码以增强安全性。随后创建一个名为`tengine`的数据库,最后验证数据库创建是否成功以及完成整个设置流程。

热门文章

最新文章

推荐镜像

更多