fightclub

将组策略导出成excel

最近有个需求,要把windows组策略导出成excel,这真是无聊的需求。本来可以直接导出html格式还是很好看的。非要做这种无聊的事情。

因为组策略直接的导出是xml或者html格式,相当于nosql的文档类型。而excel则是类似关系数据库的类型,因此需要做些格式转换。

组策略导出

组策略导出使用了powershell,将全部组策略导出到指定路径下。当然也可以指定ldap的路径来进行导出。

ExportGPReport.ps1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
param(
[string]$LdapPath = "All",
[string]$OutPut = $(pwd).Path
)
if($LdapPath -eq "ALL"){
$s=Get-GPO -All
}
else{
$s=(Get-GPInheritance -Target $LdapPath).GpoLinks
}
foreach ($gpo in $s){
$out=$OutPut+"\"+$gpo.DisplayName+".html"
Get-GPOReport -Name $gpo.DisplayName -ReportType Html -Path $out
}

使用方法例如.\ExportGPReport.ps1 -OutPut c:\gpo

Get-GPOReport导出xml格式的文档会损失很多信息,看来只能导出成html再进行解析了。

格式转换

如果利用excel直接进行转换,效果简直惨不忍睹。因此只能自己设想样式进行导出。我先预想使用合并单元格的方式描绘树状图。但是导出的效果非常之烂,因此只能换一种格式。采用高级标题使用更多单元格合并的方式来展现。虽然还是很难看,不过稍微好了点。

不知道怎么用powershell实现,于是又拿起了熟悉的python。
gpo.py

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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
#!/usr/bin/env python3
import os.path
import weakref
from glob import glob
from pyquery import PyQuery as pq
from argparse import ArgumentParser
import xlwt
style = xlwt.XFStyle()
ali = xlwt.Alignment()
borders = xlwt.Borders()
borders.left = xlwt.Borders.THICK
borders.right = xlwt.Borders.THICK
borders.top = xlwt.Borders.THICK
borders.bottom = xlwt.Borders.THICK
ali.horz = xlwt.Alignment.HORZ_CENTER
ali.vert = xlwt.Alignment.VERT_CENTER
ali.wrap = xlwt.Alignment.WRAP_AT_RIGHT
style.alignment = ali
style.borders = borders
class Node:
def __init__(self):
self._parent = None
self.height = 1
self.level = 1
@property
def parent(self):
return self._parent if self._parent is None else self._parent()
@parent.setter
def parent(self,node):
self._parent = weakref.ref(node)
def __repr__(self):
return type(self) + 'height: %s' % self.height
def show(self):
pass
def _grow(self, h):
if h == 0:
return
else:
p = self
p.height += h
if p.parent is not None:
p = p.parent
p._grow(h)
def _dive(self, d):
pass
class Branch(Node):
def __init__(self, name):
super(Branch, self).__init__()
self.name = name
self.children = []
def __str__(self):
s = 'Node:%s,height:%s' % (self.name, self.height)
return s
def show(self):
print(self)
for child in self.children:
child.show()
def add_node(self, node):
width = len(self.children)
self.children.append(node)
node.parent = self
node._dive(self.level)
if width >= 1:
self._grow(node.height)
else:
self._grow(node.height - 1)
def _dive(self, d):
self.level += d
for child in self.children:
child._dive(d)
class Leaf(Node):
def __init__(self):
super(Leaf, self).__init__()
self.table = []
def __str__(self):
return str(self.height)
def show(self):
print(self)
def add_data(self, data):
width = len(data)
if self.table == []:
width -= 1
self.table.extend(data)
self._grow(width)
def _dive(self, d):
self.level += d
def walk(p, cur_node):
for n in p.children():
child = pq(n)
if child.attr('class').startswith('he'):
for g in child.children():
grandchild = pq(g)
if grandchild.attr('class') == 'sectionTitle':
node = Branch(child.text())
cur_node.add_node(node)
cur_node = node
elif grandchild.is_('table'):
leaf = Leaf()
data = []
for t in grandchild('tr'):
td = pq(t).find('td')
if not td.attr('colspan') and td.eq(1).text() != '':
data.append((td.eq(0).text(), td.eq(1).text()))
cur_node.add_node(leaf)
leaf.add_data(data)
elif child.attr('class') == 'container':
walk(child, cur_node)
else:
continue
class GPOTree:
def __init__(self, title, ctree, utree):
self.title = title
self.ctree = ctree
self.utree = utree
@classmethod
def loadfile(cls, filename):
gpo = cls.__new__(cls)
with open(filename, 'rt', encoding='utf-16') as f:
d = pq(''.join(f.readlines()))
gpo.title = d('head').find('title').text().replace(' ', '_')[:31]
p = g = d('div.gposummary')
for i in range(10):
p = p.next()
if p.text() == '计算机配置(已启用)':
c = p.next()
C = Branch('计算机配置')
walk(c, C)
gpo.ctree = C
elif p.text() == '用户配置(已启用)':
u = p.next()
U = Branch('用户配置')
walk(u, U)
gpo.utree = U
break
return gpo
def export_to_excel_tree(self, filename):
def traval(node, ws, x, y, style):
if type(node) is Branch:
ws.write_merge(x, x + node.height - 1, y, y, node.name, style)
# print('write_merge(%s,%s,%s,%s,%s)'%(x,x+node.height-1,y,y,node.name))
y += 1
for child in node.children:
traval(child, ws, x, y, style)
x += child.height
elif type(node) is Leaf:
for i, entry in enumerate(node.table):
ws.write_merge(x + i, x + i, y, y, entry[0], style)
ws.write_merge(x + i, x + i, y + 1, y + 1, entry[1], style)
# print('write_merge(%s,%s,%s,%s,%s)'%(x+i,x+i,y,y,entry))
else:
return
wb = xlwt.Workbook(encoding='utf-8')
ws = wb.add_sheet(self.title)
traval(self.ctree, ws, 0, 0, style)
traval(self.utree, ws, self.ctree.height, self.ctree.height, style)
wb.save(filename)
def export_to_excel_table(self, filename):
header_map = {1: 5, 2: 4, 3: 3, 4: 2, 5: 1}
def traval(node, ws):
nonlocal line
if type(node) is Branch:
ws.write_merge(line, line, 0, header_map.get(
node.level, 1), node.name, style)
line += 2
for child in node.children:
traval(child, ws)
elif type(node) is Leaf:
for i, entry in enumerate(node.table):
ws.write(line + i, 0, entry[0], style)
ws.write(line + i, 1, entry[1], style)
line += node.height + 2
else:
return
wb = xlwt.Workbook(encoding='utf-8')
ws = wb.add_sheet(self.title)
line = 0
traval(self.ctree, ws)
traval(self.utree, ws)
wb.save(filename)
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument('-s', '--source', type=str,
required=True, help='组策略导出文件存储位置')
parser.add_argument('-o', '--output', type=str,
required=True, help='组策略文件导出位置')
args = parser.parse_args()
source = args.source
output = args.output
if not os.path.isdir(source):
raise SystemExit('source目录不存在')
if not os.path.isdir(output):
raise SystemExit('output目录不存在')
gpo_files = glob(os.path.join(source, '*.html'))
for f in gpo_files:
gpo = GPOTree.loadfile(f)
o = os.path.join(output, f.replace(
source, output).replace('html', 'xls'))
gpo.export_to_excel_table(o)

使用方法举例:

python3 -s 'c:\gpo' -o e:\grouppolicy

其他问题

  • 本来想着把两个脚本粘起来,后来又想想似乎没什么必要。
  • 原来想着使用单个文件多个表单的方式。结果发现xlutils copy的表单居然没有style。再想想不值得再花时间弄了,就这样吧。