1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
|
module (..., package.seeall)
require("fs")
require("posix")
-- require("procps")
-- require("daemoncontrol")
-- require("processinfo")
-- Set variables
local config_file = "/etc/ssh/sshd_config"
local packagename = "openssh"
local processname = "sshd"
-- valid keywords and default config
local default = {
Port = 22,
ListenAddress = "0.0.0.0",
PermitRootLogin = true,
PasswordAuthentication = true,
UseDNS = true
}
-- This function is used to get config_content.
local function process_status_text(procname)
local t = procps.pidof(procname)
if (t) and (#t > 0) then
return "Enabled"
else
return "Disabled"
end
end
-- return "Yes" or "No" on true/false or value as string
local function config_value(value)
if type(value) == "boolean" then
if value then
return "Yes"
else
return "No"
end
end
return tostring(value)
end
function read_config()
local conf = {}
local f = io.open(config_file, "r")
local line, key, _, k, v
if not f then
return nil
end
-- clone default conf
for k, v in pairs(default) do
conf[k] = v
end
for line in f:lines() do
line = string.gsub(line, "#.*", "")
for key, _ in pairs(default) do
local k,v = string.match(line, "^("..key..")%s+(.*)")
if k then
conf[k] = v
end
end
end
f:close()
return conf
end
function write_config(config)
local k, v, lines, i,j
local conf = {}
-- filter out unsupported keys
for k,v in pairs(config) do
if default[k] ~= nil then
conf[k] = v
end
end
lines = fs.read_file_as_array(config_file)
for i, j in ipairs(lines) do
for k, v in pairs(conf) do
if string.match(j, "^#?"..k.."%s+") then
lines[i] = k .. " " .. config_value(v)
conf[k] = nil
end
end
end
-- append config opts to end
for k,v in pairs(conf) do
table.insert(lines, k .. " " .. config_value(v))
end
-- write file
posix.mkdir(posix.dirname(config_file))
local f = io.open(config_file, "w")
for _,i in ipairs(lines) do
f:write(i.."\n")
end
f:close()
end
|