源项目地址:https://github.com/xmapst/rinetdweb
因为公司经常需要把内网服务映射出去,领导为了便于管理,故提出实施web化管理。
本着充分利用网络资源原则,采用了上面的项目地址。
由于具体脚本写的缺乏细节,故根据自己需求,进行了修改。
有些配置原来写死了,为考虑通用性,尽量采用变量和主动获取方式。
提示uwsgi采用pip安装,rpm包的兼容版本不知道是哪个,自动安装的没法用
依赖:pip install uwsgi
2021.03.10由于之前页面不支持增加说明信息,有些配置时间长了会忘记做什么用的,因此要增加说明信息并显示
***** 表示此次修改的部分
前端页面比较简单,增加两行代码而已
补充了一些注释,现在应该很容易明白了。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# @Author : lijunye
# @File : webserver.py
# @Time : 2019/1/10
# @Uptime :
# @Version : 0.1
# @Features :
# @Desc : rinted端口转发 WEB界面操作
"""
import web
import os
import re
import time
import commands
import subprocess
render = web.template.render('templates/')
rinstate, rinetd_bin = commands.getstatusoutput('which rinetd')
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
CONF = "/root/data/rinetdweb/rinetd.conf" # 根据实际修改
PID = """ps -elf |grep rinetd|grep -v grep |awk '{print $4}'""" # 获取rinetd的pid
# 判断本机是否安装rinetd
if rinstate != 0:
print("rinetd is not find")
os._exit()
# URL路由
urls = (
'/', 'Index',
'/add', 'Add',
'/del', 'Del',
'/op(.*)', 'Operate'
)
app = web.application(urls, globals())
# 获取有效配置
def getConf():
i = 0
result = {}
with open( CONF, 'r') as fobj:
lines = fobj.readlines()
for line in lines:
line = line.strip('\n')
if line.startswith('0.0.0'): # 默认源ip 0.0.0.0,建议采用默认
# line = re.sub('#.*', '', line) # 为了便于管理,有些配置后面增加了注释
line = re.sub('#', '', line) #*****获取注释内容,去掉注释符号
result[i] = line
i += 1
print line
# k = ['SocIP', 'SocPort', 'DesIP', 'DesPort'] # 向页面传递配置的字段
k = ['SocIP', 'SocPort', 'DesIP', 'DesPort', 'Comment'] # 添加描述字段
for line in result.keys(): # 获取每行配置的键值
v = str(result[line]).split() # 切割每行有效配置的
# result[line] = dict(zip(k, v)) # 把配置文件的值赋予字段意义,变成字典格式重新赋值回去
C = "" #**** 用于接受描述字段内容,因为描述里可能有空格,会生成不定长列表
if v[4:]: #***** 从第5个字段开始是说明内容
for i in v[4:]:
C = C + i + " "
result[line] = { k[0]:v[0], k[1]:v[1], k[2]:v[2], k[3]:v[3], k[4]:C } # ****返回结果字典
return result
# 获取rinetd运行状态
def rinetd_state():
pid = commands.getoutput( PID )
if pid == "":
return "Rinetd 已停止"
else:
return "Rinetd 正在运行"
# 定义首页类
class Index():
def GET(self):
result = getConf()
port_state = commands.getoutput('netstat -lnt').split("\n")
status = rinetd_state()
return render.index(result, status, port_state, msg=None)
# 定义增加配置方法类
class Add():
def POST(self):
form = web.input()
result = getConf()
status = rinetd_state()
port_state = commands.getoutput('netstat -lnt').split("\n")
p = []
for i,n in enumerate(port_state):
if i > 1:
s = ' '.join(n.split())
p.append(s.split()[3].split(":")[-1])
if form['SocIP'] != "" and form['SocPort'] != "" and form['DesIP'] != "" and form['DesPort'] != "":
for line in result.values():
if line['SocPort'] == form['SocPort'] or form['SocPort'] in p:
msg = "端口已存在"
return render.index(result, status, port_state, msg)
# new_result = "%s %s %s %s" % (form['SocIP'], form['SocPort'], form['DesIP'], form['DesPort'])
new_result = "%s %s %s %s #%s" % (form['SocIP'], form['SocPort'], form['DesIP'], form['DesPort'], form['Comment']) # ****获取新增加配置
with open( CONF, mode='a') as data:
data.write(new_result.encode("utf-8") + '\n') # ****由于传入内容有非ASCII字符,因此需要编码
# data.write(new_result + '\n')
msg = "添加成功"
return render.index(result, status, port_state, msg)
else:
msg = "不允许为空"
return render.index(result, status, port_state, msg)
# 定义删除配置方法类
class Del():
def POST(self):
form = web.input()
result = getConf()
status = rinetd_state()
port_state = commands.getoutput('netstat -lnt').split("\n")
lists = []
for line in result.values():
lists.append(line['SocPort'])
if form['SocIP'] != "" and form['SocPort'] != "" and form['DesIP'] != "" and form['DesPort'] != "":
with open( CONF, 'r') as fobj:
lines = fobj.readlines()
for line in lines:
line = line.strip()
if line.startswith('0.0.0'):
line = re.sub('#.*', '', line)
else:
continue
new_result = line.split(" ")[1]
if form['SocPort'] in lists and form['SocPort'] == new_result:
count = 0
while count < len(lines): # 动态计算,防止最后索引超出范围
# 此处的len函数是因为配置文件中有的注释只有连续的几个字,甚至只有一个注释符号,不判断直接比较,后面的[1]会出现索引超出范围
# 如果有特殊需求,可以 增加SocIP判断
if len(lines[count]) > 2 and new_result == lines[count].split(" ")[1]:
lines.pop(count) # 如果排除修改出现重复错误,可以此处退出循环
else:
count += 1
with open( CONF, 'w') as wobj: # 回写新配置文件
wobj.writelines(lines)
print line
msg = "删除成功"
return render.index(result, status, port_state, msg)
else:
msg = "记录不存在"
return render.index(result, status, port_state, msg)
class Operate():
def POST(self,operate=None):
form = web.input()
result = getConf()
if form['pm'] == 'start':
pid = commands.getoutput( PID )
if pid != "":
raise web.seeother('/')
stats = subprocess.Popen( rinetd_bin + ' -c ' + CONF + ' &' , shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)
time.sleep(0.3)
raise web.seeother('/')
elif form['pm'] == 'stop':
pid = commands.getoutput( PID )
if pid == "":
raise web.seeother('/')
commands.getstatusoutput('killall rinetd')
raise web.seeother('/')
elif form['pm'] == 'reload':
pid = commands.getoutput( PID )
if pid == "":
raise web.seeother('/')
# 此处使用kill -1 重新加载,避免直接重启进程,而断掉其他正在使用的链接
commands.getstatusoutput("kill -1 `ps -elf |grep rinetd|grep -v grep |awk '{print $4}'`")
# stats = subprocess.Popen( rinetd_bin + ' -c ' + CONF + ' &' , shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)
time.sleep(0.3)
raise web.seeother('/')
application = app.wsgifunc()
最终效果如图

image.png