יחידה:IPTables.lua
מראה
ניתן ליצור תיעוד על היחידה הזאת בדף יחידה:IPTables.lua/תיעוד
-- Module:IPTables
-- A MediaWiki Lua module for managing iptables with appropriate permissions
-- Path to the temporary script file
local script_path = "/tmp/manage_iptables.sh"
-- Function to create the bash script
local function create_script()
local script_content = [[#!/bin/bash
# A script to manage iptables rules
# Ensure the script is run with proper permissions
if [ "$(id -u)" -ne 0 ]; then
echo "This script must be run as root" >&2
exit 1
fi
# Execute the iptables command
/sbin/iptables "$@"
]]
local file = io.open(script_path, "w")
if not file then
mw.log("Failed to open script file for writing.")
return false, "Failed to create script"
end
file:write(script_content)
file:close()
-- Make the script executable
local chmod_result = os.execute("chmod +x " .. script_path)
if chmod_result ~= 0 then
mw.log("Failed to make script executable.")
return false, "Failed to set script permissions"
end
return true
end
-- Function to execute a shell command using the bash script
local function execute_command(args)
local full_cmd = script_path .. " " .. args
local handle = io.popen(full_cmd .. " 2>&1") -- Capture both stdout and stderr
local result = handle:read("*a")
handle:close()
-- Log and check the result
mw.log("Command executed: " .. full_cmd)
mw.log("Result: " .. result)
if result:match("error") or result:match("failed") then
return false, "Failed to execute command: " .. result
else
return true
end
end
function manage_iptable(operation, rule)
-- Validate the operation
if operation ~= "get" and operation ~= "add" and operation ~= "delete" then
return "Invalid operation. Valid operations are: get, add, delete."
end
-- Simulate the management of iptables rules
local result_message
if operation == "get" then
result_message = "Simulated: Getting iptables rules"
elseif operation == "add" then
if not rule or rule == "" then
return "Error: No rule specified for adding. Please provide a valid rule."
end
result_message = "Simulated: Adding rule " .. rule
elseif operation == "delete" then
if not rule or rule == "" then
return "Error: No rule specified for deletion. Please provide a valid rule."
end
result_message = "Simulated: Deleting rule " .. rule
end
return result_message
end
-- Return a table of exported functions
return {
manage_iptable = manage_iptable,
execute_command=execute_command
}