python3给防火墙添加放行

2023-05-19 17:27:22 浏览数 (3)

脚本如下

代码语言:javascript复制
from http.server import BaseHTTPRequestHandler
from urllib import parse
import subprocess

class GetHandler(BaseHTTPRequestHandler):

    secret_key = r'Hi93d4cfa5863770f9a0c87d8,b85a4ebc7'
    #secret_key = r'4AULgSBxBESAt3IaItH6C227ik4,fW5o6xr 1!7CfjJSCTf$5jxV) w7iImrx@'
    #secret_key = r'4AULgSBxBESAt3IaItH6C227ik4,fW5o6xr 1!7CfjJSCTf$5jxV) w7iImrx@'
    #commands = "iptables -A INPUT -s {}/32 -p tcp -m state --state NEW -m tcp --dport 443 -j ACCEPT && service iptables save"
    commands = r"""firewall-cmd --add-rich-rule="rule family="ipv4" source address="{}" port port="3306" protocol="tcp" accept" --zone=public --permanent && firew
all-cmd --reload """
    def process_command(self,client_ip):
        commands = self.commands.format(client_ip)
        try:
            process_result = subprocess.run(commands,stdout=subprocess.PIPE, shell=True, check=True)
            re_stdout = ''
            re_stderr = ''
            if process_result.stdout:
                re_stdout = str(process_result.stdout,encoding='utf-8')
            if process_result.stderr:
                re_stderr = str(process_result.stderr,encoding='utf-8')
            return (re_stdout, re_stderr)
        except subprocess.CalledProcessError as e:
            return "Process Command Error."

        #return subprocess.run(self.commands)

    def do_GET(self):
       # parsed_path = parse.urlparse(self.path)
        #parsed_header = parse.urlparse(self.headers)
        client_ip = self.address_string()
        #client_ip = self.headers['X-Real-IP']
        client_request_path = self.path[1:]
        if client_request_path != self.secret_key:
            self.send_error(403)

        r_result = self.process_command(client_ip)
        message = ''.join(r_result)
        self.send_response(200)
        self.send_header('Content-Type',
                         'text/plain; charset=utf-8')
        self.end_headers()
        self.wfile.write(message.encode('utf-8'))

if __name__ == '__main__':
    from http.server import HTTPServer
    server = HTTPServer(('0.0.0.0', 29999), GetHandler)
    print('Starting server, use <Ctrl-C> to stop')
    server.serve_forever()

0 人点赞