我想构建一个网络界面,例如ISPConfig,cPanel,Webmin,该界面允许我使用网络浏览器来管理服务器,例如:单击网页上的按钮后,将显示“ dnf update”命令发送到服务器,服务器将被更新。
虽然Web界面本身可能不是一个大问题,但是为它构建一个可以接收和执行命令的引擎。
我现在想的一个解决方案是构建一个Python程序,该程序将创建一个非特权用户并从中读取命名管道,然后执行命令。 我是Python的初学者,这对我来说是一个学习更多的好机会。
这是到目前为止我要提出的:
#!/usr/bin/python3
import os
import sys
import atexit
import platform
# The UID ang GID of the pipe file to be owned by.
TARGET_UID=1000
TARGET_GID=1000
# Set up the FIFO
PIPE_FILE = 'comms.fifo'
### FUNCTION BLOCK ###
def check_OS():
"""Checking if the program is running on Linux."""
OS=platform.system()
if OS != "Linux":
print("This service can only run on Linux! It will be stopped now.")
quit()
def if_exists_FILE(FILE):
"""Check if a file is accessible/exists."""
try:
with open(FILE, encoding='utf-8') as f:
f.close()
except FileNotFoundError:
return False
return True
def exec_CMD(CMD):
"""Executes system command based on the permissions the program runs with. It's assumed that the command has already been filtered for security."""
print(f"\x1b[6;30;42m" + f">>>> COMMAND START : \"{CMD.strip()}\" <<<<" + "\x1b[0m")
os.system(CMD.strip())
print(f"\x1b[6;30;42m" + f">>>> COMMAND END : \"{CMD.strip()}\" <<<<" + "\x1b[0m" + "\n")
def prep_FIFO(PIPE_FILE):
"""Creates the named pipe and sets permissions."""
os.mkfifo(PIPE_FILE,0o600)
# Ownership of the pipe needs to be changed so that normal users
# can send stuff to it.
os.chown(PIPE_FILE, TARGET_UID, TARGET_GID)
### FUNCTION BLOCK ###
check_OS()
# Remove the PIPE_FILE if it already exists to avoid errors on the program's startup.
if if_exists_FILE(PIPE_FILE):
print("Pipe file already exists and it's going to be removed.")
os.remove(PIPE_FILE)
prep_FIFO(PIPE_FILE)
# Make sure to clean up after ourselves
def cleanup_PIPE():
os.remove(PIPE_FILE)
atexit.register(cleanup_PIPE)
print ("Waiting for commands.")
# Go into reading loop
while True:
with open(PIPE_FILE, 'r') as FIFO:
for LINE in FIFO:
exec_CMD(LINE)
我需要它可以在Linux上运行,安全并且必须根据最佳实践进行制作。 我不能只是让命令被接收并盲目执行。 我应该找出如何将其作为Linux守护程序正确运行,因此它应该能够记录消息/错误等。 我还需要以某种方式将命令输出返回到Web界面,以便能够查看状态。
我希望我能做到这一点。
预先感谢您的所有提示,想法。