-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode.py
More file actions
2320 lines (2038 loc) · 95.4 KB
/
Copy pathnode.py
File metadata and controls
2320 lines (2038 loc) · 95.4 KB
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#coding:utf-8
# Author: Jianpo Ma
# Purpose:
# Created: 2013/6/17
import sys
import datetime
from fabric.api import run, env, task, parallel, settings, hide, open_shell
from fabric.utils import puts
from fabric.colors import *
from fabric.tasks import execute
from fabric.exceptions import NetworkError
from fabric.contrib.files import exists as fexists
from fabric.state import connections
import traceback
import uuid as muuid
from itertools import izip
import pdb
import pprint
import string
import ConfigParser
import os.path
import time
import threading
import thread
from Queue import Queue
import prettytable
reload(sys)
sys.setdefaultencoding('latin1')
########################################################################
class NodeNet(object):
""""""
# the node that watched by someone on this net
current_node = None
# db table name
__dbtable__= None
# db table class
__dbclass__ = None
# the map of objects
__nodemap__ = {}
# foreign class
__foreignclass__ = None
# encoding
encoding = 'gbk'
#----------------------------------------------------------------------
@classmethod
def get_dbclass(cls):
if cls.__dbclass__ is not None:
return cls.__dbclass__
if cls.__dbtable__ is None:
return None
dbclassname=cls.__dbtable__
dbclass = None
import importlib
module_name='dbi'
mo = importlib.import_module(module_name)
if mo:
if hasattr(mo, dbclassname):
dbclass = getattr(mo, dbclassname)
if dbclass :
cls.__dbclass__ = dbclass
return dbclass
else:
raise "There is no class of %s in %s module" % ( dbclassname, module_name)
else:
return None
else:
return None
def __init__(self, node_id , foreignclass=None):
"""Constructor"""
# search __nodemap__
if self.__nodemap__.has_key(node_id):
self=self.__nodemap__[node_id]
return
# mapped into db table class
if self.__dbclass__ is None and self.__dbtable__ is not None:
self.get_dbclass()
# node relation property
self.s = self.get_dbclass().get(node_id,first=True) if self.__dbclass__ else None
if self.s is None:
raise Exception("Error: Can't find the information record: %s" % node_id)
self.dbid = None if self.s is None else self.s.id
self.parent = None
self.childs = None
self.root = self
self.level = 0
self._iter_step = None
self._iter_parent = None
# join __nodemap__
if self.dbid and not self.__nodemap__.has_key(self.dbid):
self.__nodemap__[self.dbid] = self
# cross to foreignclass node map
if foreignclass:
self.__foreignclass__ = foreignclass
self.foreignnode=None
self.dockapply()
# init current node if not exists
self.set_current_node(self)
def add_child(self, child):
if child is None or not isinstance(child, self.__class__):
return False
if self.childs is None:
self.childs = {}
child.root = self.root
child.level = self.level + 1
child.parent = self
self.childs[child.dbid] = child
return True
@classmethod
def get_node(cls, dbid):
if cls.__nodemap__.has_key(dbid):
return cls.__nodemap__[dbid]
dbinfo = cls.get_dbclass().get(dbid,first=True)
if not dbinfo:
raise Exception("Error: no information while id=[%s] in table %s" % (dbid,cls.__dbtable__) )
parent_node = cls.get_node(dbinfo.pid)
# if dbinfo.pid != 0 and parent_node is None:
# return None
self_node = cls(dbid, cls.__foreignclass__)
if dbinfo.pid != 0:
parent_node.breed()
parent_node.add_child(self_node)
return self_node
def breed(self, recursion=False):
'''依据自身.dbid值,繁殖子节点:返回子嗣数量'''
if not (self.childs is None) and len(self.childs) > 0:
return len(self.childs)
for child_info in self.get_dbclass().get(self.dbid,"pid"):
if self.childs is None:
self.childs={}
if self.__nodemap__.has_key(child_info.id):
continue
child_node=self.__class__(child_info.id,self.__foreignclass__)
self.add_child(child_node)
if recursion:
child_node.breed(recursion)
return 0 if self.childs is None else len(self.childs)
#if result is None or len(result) == 0:
#self.childs = {}
#return 0
#for i in result:
#child_node = self.__class__(i.id, self.__foreignclass__)
#self.add_child(child_node)
#child_count += 1
#if recursion:
#child_count += child_node.breed(recursion)
#return len(self.childs)
def __iter__(self):
self._iter_step = self.level - 1
self._iter_parent = self
return self
def next(self):
if self._iter_step < 0:
self._iter_step = self.level
raise StopIteration
self._iter_parent = self._iter_parent.parent
self._iter_step -= 1
return self._iter_parent
@classmethod
def set_current_node(cls,node,force=False):
if cls.current_node is None:
cls.current_node=node
if force:
cls.current_node=node
def print_structure(self):
print "%s+-%s" % (string.ljust('', self.level * 4), self)
if self.childs:
for i in self.childs.values():
i.print_structure()
def pwd(self):
for i in self:
print "%s+-%s" % (string.ljust('', i.level * 4), i)
def dockapply(self):
if (self.s is None or
self.__dbclass__ is None or
self.__foreignclass__ is None or
self.__dbclass__ is None or
not hasattr(self.__dbclass__, string.lower("%s_id" % self.__foreignclass__.__name__))):
return False
foreignid = getattr(self.s, string.lower("%s_id" % self.__foreignclass__.__name__))
if foreignid:
self.__foreignclass__.dockhandle(self, foreignid)
return True
else:
return False
@classmethod
def dockhandle(cls, applicant, searchid):
the_node = cls.get_node(searchid)
if the_node is None:
return False
else:
the_node.foreignnode = applicant
applicant.foreignnode = the_node
@classmethod
def cd(cls, dbid):
dbid = string.strip(dbid)
cnode = cls.current_node
if dbid == '.':
cnode = cls.current_node
elif dbid == '..':
if cls.current_node.parent is not None:
cnode = cls.current_node.parent
elif dbid == '~':
cnode = cls.current_node.root
else:
cdbid = int(dbid)
if cdbid is None or cdbid == 0:
return cls.current_node
else:
if cdbid is not None and cdbid != 0:
if cls.current_node.childs.has_key(cdbid):
cnode = cls.current_node.childs[cdbid]
else:
cnode=cls.get_node(cdbid)
if cnode.childs is None:
cnode.breed()
cls.current_node = cnode
return cls.current_node
class Feature(NodeNet):
""""""
__nodemap__ = {}
current_node = None
def __init__(self, dbid=None, tablename=None, foreignclass=None):
super(Feature, self).__init__(dbid, tablename,foreignclass)
def __str__(self):
return "<%s:%s>" % (self.s.feature, self.s.detail)
def print_structure(self):
print "%s+-%s" % (string.ljust('', self.level * 4), "%s---%s->%s" % (
self, self.foreignnode.__class__.__name__, self.foreignnode) if self.foreignnode else self)
for i in self.childs.values():
i.print_structure()
def __str__(self):
if self.s is None:
return 'None'
return ("%s[%s:%s]%s" % (self.s.detail, self.dbid, '' if self.parent is None else self.parent.s.detail,
'' if self.foreignnode is None else "-->%s" % self.foreignnode))
class ExecuteOut(object):
def __init__(self, inst=None):
self.return_code = -99
self.result = ''
self.succeed = False
self.elapsed = 0
self.instance = inst
def __str__(self):
return """Code: %s Result: \n%s""" % (self.return_code, self.result)
class Server(NodeNet):
"""Server.s ---> sqlobject ---> TABLE:servers"""
__nodemap__ = {}
current_node = None
__dbtable__ = 't_server'
def __init__(self, dbid=0, foreignclass=None):
"""Constructor"""
super(Server, self).__init__(dbid,
foreignclass)
def run(self):
pass
def __getitem__(self, index):
'''Get the item of the access way'''
#print 'getitem_index: %s' % index
try:
for i in range(self.level - index):
it = it.parent
return it
except Exception, e:
self._print_error(e)
def __str__(self):
return (
"%s:%s:%s[%03d:%s]" % (
self.s.region, self.s.product, self.s.ip_oper, self.dbid, self.s.description)).encode(
self.encoding)
def __len__(self):
return self.level
def _print_error(self, e):
puts('%s Error: #%d %s' % (self.s.ip_oper, e.args[0], e.args[1]))
def search(self, addr):
def _search(addr, start):
if start.s.ip_oper == addr:
return start
for value in start.childs.values():
result = _search(addr, value)
if result:
return result
root = self if (self.root is None) else self.root
return _search(addr, root)
@classmethod
def disconnect_all(cls):
for key in connections.keys():
connections[key].close()
del connections[key]
def execute(self, cmd,
hide_running=True, hide_stdout=True, hide_stderr=False, hide_puts=False, showprefix=None,
hide_warning=True, password=None, abort_on_prompts=True, hide_server_info=False):
class FabricAbortException(Exception):
def __str__(self):
return repr('Fabric Abort Exception:%s', self.message)
def __call__(self,x):
print "Error Fabric Abort Exception: %s -%s" % (self.message,str(x))
out = ExecuteOut(inst=self)
out.return_code = -99
out.result = ''
out.succeed = False
starttime = time.time()
host_string = '%s@%s' % (self.s.loginuser, '127.0.0.1' if self.root == self else self.s.ip_oper)
gateway_string = "%s@%s" % (
self.parent.s.loginuser, self.parent.s.ip_oper) if self.level == 2 and self.parent is not None else None
try:
if self.s.role in ['rds']:
raise Exception("This server role is %s: can't execute any cmd" % self.s.role)
hiding_clause = (
'running' if hide_running else None, 'stdout' if hide_stdout else None,
'stderr' if hide_stderr else None)
hiding_clause = [x for x in hiding_clause if x]
with settings(hide(*hiding_clause),
host_string=host_string,
gateway=gateway_string,
skip_bad_hosts=True,
abort_exception=FabricAbortException(),
connection_attempts=1,
disable_known_hosts=True,
timeout=5,
command_timeout=5,
colorize_errors=True,
abort_on_prompts=abort_on_prompts,
warn_only=hide_warning,
password=password if password else None,
output_prefix=False,
eagerly_disconnect=True,
keepalive=5,
parallel=True):
result = run(cmd, shell=False, timeout=5)
out.result = str(result)
if hasattr(result, 'return_code'):
out.return_code = result.return_code
if not hide_server_info:
puts(yellow(
"%s ReturnCode:%s" % (str(self), result.return_code if hasattr(result, 'return_code') else '')),
show_prefix=showprefix, flush=True)
if result.succeeded:
if not hide_puts:
puts(green(result), show_prefix=showprefix, flush=True)
out.succeed = True
if result.failed:
out.succeed = False
if not hide_puts:
puts(red(result), show_prefix=showprefix, flush=True)
except NetworkError, e:
out.succeed = False
out.result = "Error: %s \n #%s" % (host_string, e)
if not hide_puts:
puts(red(out.result))
except Exception, e:
# traceback.print_exc()
out.succeed = False
out.result = "Error: %s \n #%s" % (host_string, e)
if not hide_puts:
puts(red(out.result))
# print '%s Error: #%d %s' % (target.address, e.args[0], e.args[1])
finally:
endtime = time.time()
out.result = string.strip(out.result)
out.elapsed = endtime - starttime
return out
def login(self, cmd=None):
if self.s.role in ['rds']:
print "This server role is %s: can't login " % self.s.role
return
host_string = '%s@%s' % (self.s.loginuser, '127.0.0.1' if self.root == self else self.s.ip_oper)
gateway_string = "%s@%s" % (
self.parent.s.loginuser, self.parent.s.ip_oper) if self.level == 2 and self.parent is not None else None
try:
#if self.level > 2:
# raise Exception("Don't supply operation on 4 round")
with settings(host_string=host_string,
gateway=gateway_string,
eagerly_disconnect=True,
remote_interrupt=False):
#hiding_clause = (
#'running' if hide_running else None, 'stdout' if hide_stdout else None, 'stderr' if hide_stderr else None)
#hiding_clause = [x for x in hiding_clause if x]
#with settings(hide(*hiding_clause), warn_only=True):
# #env.skip_bad_hosts=True
# env.connection_attempts = 2
# #env.disable_known_hosts=True
# env.eagerly_disconnect=True
# env.abort_on_prompts = True
# #env.warn_only=True
# env.output_prefix = False if hide_output_prefix else False
open_shell(cmd)
except NetworkError, e:
#pdb.set_trace()
#traceback.print_exc()
# print '%s Error: #%d %s' % (target.address, e.args[0], e.args[1])
# return ''
# puts('%s Error: #%d %s' % (target.address,e.args[0], e.args[1]))
puts(red("Error: %s \n #%s" % (host_string, e)))
return 0
except Exception, e:
#pdb.set_trace()
#traceback.print_exc()
# puts('%s Error: #%d %s' % (target.address,e.args[0], e.args[1]))
# print '%s Error: #%d %s' % (target.address, e.args[0], e.args[1])
puts(red("Error: %s \n #%s" % (host_string, e)))
return 0
@staticmethod
def _print_result(result, showprefix=None, info=''):
puts(yellow("%s ReturnCode:%s" % (info, result.return_code if hasattr(result, 'return_code') else '')),
show_prefix=showprefix, flush=True)
if result.succeeded:
puts(green(result), showprefix=showprefix, flush=True)
if result.failed:
puts(yellow(red(result), show_prefix=showprefix, flush=True))
#def infect_execute(self,cmd,extent=False):
#'''infect a file or command to childs or whole'''
#if self.childs is None:
#self.breed()
#for i in self.childs.values():
#i.execute(cmd)
#if extent:
#i.infect_execute(cmd,extent)
def get_childs(self, recursion=False):
serverlist = []
if self.childs is None:
self.breed()
for i in self.childs.values():
serverlist.append(i)
if recursion:
serverlist += i.get_childs(recursion)
return serverlist
def exists(self, path):
host_string = '%s@%s' % (self.s.loginuser, '127.0.0.1' if self.root == self else self.s.ip_oper)
gateway = self.parent.s.ip_oper if self.level == 2 and self.parent is not None else None
result = False
try:
with settings(host_string=host_string,
gateway=gateway,
skip_bad_hosts=True,
connection_attempts=2,
disable_known_hosts=True,
eagerly_disconnect=True,
abort_on_prompts=True,
warn_only=False
):
result = fexists(path)
except NetworkError, e:
result = False
except Exception, e:
result = False
finally:
return result
return result
@classmethod
def piece(cls, line):
if cls.__dbclass__ is None:
return None
#dbids = cls.__dbclass__.piece(line)
serverlist = []
for i in cls.get_dbclass().piece(line):
tnode = cls.get_node(i)
if tnode:
serverlist.append(tnode)
return serverlist
def add_child_info(self, region, product, role, ip_oper, description, loginuser='root'):
self.get_dbclass().add(pid=self.dbid,
ip_oper=ip_oper,
description=description,
region=region,
product=product,
role=role,
loginuser=loginuser
)
@classmethod
def walk(cls, source_server, dest_server):
#seach child
if source_server is None or dest_server is None or type(source_server) != cls or type(dest_server) != cls:
return []
start = [source_server] + [x for x in source_server]
end = [dest_server] + [x for x in dest_server]
same = [x for x in start if x in end]
result = start[:start.index(same[0])] + same[0:1] + end[:end.index(same[0])][::-1]
# end=end.reverse()
#tmp=start + end
#result=sorted(set(tmp),key=tmp.index)
return result
def _transfer(self):
walkpath = self.server.walk(self.server, value)
for (src_srv, dst_srv) in map(None, walkpath, walkpath[1:]):
if src_srv is not None and not self.trans_list.has_key(src_srv.dbid):
self.trans_list[src_srv.dbid] = [src_srv, 0, None]
if dst_srv is not None and not self.trans_list.has_key(dst_srv.dbid):
self.trans_list[dst_srv.dbid] = [dst_srv, 0, None]
if dst_srv is None and self.trans_list.has_key(src_srv.dbid):
print "%s+-->%s" % (string.ljust(' ', src_srv.level * 4, ) + str(src_srv), str(dst_srv)),
if self.trans_list[src_srv.dbid][1] == 1:
if src_srv.exists(os.path.join(self.tmppath, self.uuid)):
if not src_srv.exists(dest_path):
src_srv.execute("mkdir -p %s" % dest_path, hide_stdout=True,
hide_puts=True, hide_server_info=True)
exe_result = src_srv.execute("""mv %s %s %s %s""" % (
os.path.join(self.tmppath, self.uuid), os.path.join(dest_path, self._lfile)
, (" && chmod -R %s %s" % (mode, os.path.join(dest_path, self._lfile))) if mode else ''
,
(" && chown -R %s %s" % (owner, os.path.join(dest_path, self._lfile))) if owner else ''
), hide_stdout=True, hide_puts=True, hide_server_info=True)
if exe_result.succeed:
self.trans_list[src_srv.dbid][1] = 0
print 'move finished'
else:
print 'move failed:%s' % exe_result.result
else:
print 'No target:%s' % os.path.join(self.tmppath, self.uuid)
elif self.trans_list[src_srv.dbid][1] > 1:
if src_srv.exists(os.path.join(self.tmppath, self.uuid)):
if not src_srv.exists(dest_path):
src_srv.execute("mkdir -p %s" % dest_path, hide_stdout=True,
hide_puts=True, hide_server_info=True)
exe_result = src_srv.execute("""cp -r %s %s %s %s""" % (
os.path.join(self.tmppath, self.uuid), os.path.join(dest_path, self._lfile)
, (" && chmod -R %s %s" % (mode, os.path.join(dest_path, self._lfile))) if mode else ''
,
(" && chown -R %s %s" % (owner, os.path.join(dest_path, self._lfile))) if owner else ''
), hide_stdout=True, hide_puts=True, hide_server_info=True)
if exe_result.succeed:
# self.trans_list[src_srv.dbid][1]=0
print 'copy finished'
else:
print 'copy failed:%s' % exe_result.result
else:
print 'No target:%s' % os.path.join(self.tmppath, self.uuid)
continue
if src_srv.level > dst_srv.level and self.trans_list.has_key(src_srv.dbid) and self.trans_list.has_key(
dst_srv.dbid):
if self.trans_list[dst_srv.dbid][1] > 0 or dst_srv.exists(os.path.join(self.tmppath, self.uuid)):
self.trans_list[dst_srv.dbid][1] += 1
else:
print "%s+-->%s" % (string.ljust(' ', src_srv.level * 4, ) + str(src_srv), str(dst_srv)),
exe_result = dst_srv.execute(
"scp -r %s:%s %s" % ("%s@%s" % (src_srv.s.loginuser, src_srv.s.ip_oper)
, self.source_path if src_srv == self.server else os.path.join(
self.tmppath, self.uuid)
, os.path.join(self.tmppath,
self.uuid) if src_srv == self.server else os.path.join(
self.tmppath)
), hide_stdout=True, hide_puts=True, hide_server_info=True)
if exe_result.succeed:
self.trans_list[dst_srv.dbid][1] += 1
self.trans_list[dst_srv.dbid][2] = 'OK'
print 'ok'
else:
self.trans_list[dst_srv.dbid][2] = 'Error:%s' % exe_result.result
print 'Error:%s' % exe_result.result
break
elif src_srv.level < dst_srv.level and self.trans_list.has_key(
src_srv.dbid) and self.trans_list.has_key(dst_srv.dbid):
if self.trans_list[dst_srv.dbid][1] > 0 or dst_srv.exists(os.path.join(self.tmppath, self.uuid)):
self.trans_list[dst_srv.dbid][1] += 1
else:
print "%s+-->%s" % (string.ljust(' ', src_srv.level * 4, ) + str(src_srv), str(dst_srv)),
exe_result = src_srv.execute("scp -r %s %s:%s" % (
self.source_path if src_srv == self.server else os.path.join(self.tmppath, self.uuid)
, "%s@%s" % (dst_srv.s.loginuser, dst_srv.s.ip_oper)
,
os.path.join(self.tmppath, self.uuid) if src_srv == self.server else os.path.join(
self.tmppath)
), hide_stdout=True, hide_puts=True, hide_server_info=True)
if exe_result.succeed:
self.trans_list[dst_srv.dbid][1] += 1
self.trans_list[dst_srv.dbid][2] = 'OK'
print 'ok'
else:
self.trans_list[dst_srv.dbid][2] = 'Error:%s' % exe_result.result
print 'Error:%s' % exe_result.result
break
def gets(self):
pass
def puts(self):
pass
########################################################################
####http://blog.csdn.net/treesky/article/details/7088284###
__metaclass__ = type
class Operation(object):
# db table name
__dbtable__ = None
# db table class
__dbclass__ = None
# server instance
server = None
def __init__(self,server):
"""Constructor"""
# pdb.set_trace()
if not isinstance(server,Server):
raise Exception("Init Error: %s is not <Server> instance" % str(server))
self.server=server
if self.__dbclass__ is None and self.__dbtable__ is not None :
self.get_dbclass()
#@classmethod
#def get_dbclass(cls,table_name=None):
#if cls.__dbclass__ is not None:
#return cls.__dbclass__
#if table_name is None:
#return None
##if table_name is None:
##selfclassname = cls.__name__
##dbclassname = "t_%s" % string.lower(selfclassname)
##else:
#dbclassname=table_name
#dbclass = None
#import importlib
#mo = importlib.import_module('dbi')
#if mo:
#if hasattr(mo, dbclassname):
#dbclass = getattr(mo, dbclassname)
#if dbclass :
#cls.__dbclass__ = dbclass
#return dbclass
#else:
#return None
#else:
#return None
@classmethod
def get_dbclass(cls):
if cls.__dbclass__ is not None:
return cls.__dbclass__
if cls.__dbtable__ is None:
return None
dbclassname=cls.__dbtable__
dbclass = None
import importlib
module_name='dbi'
mo = importlib.import_module(module_name)
if mo:
if hasattr(mo, dbclassname):
dbclass = getattr(mo, dbclassname)
if dbclass :
cls.__dbclass__ = dbclass
return dbclass
else:
raise "There is no class of %s in %s module" % ( dbclassname, module_name)
else:
return None
else:
return None
class IPsec(Operation):
__dbtable__ = 't_ipsec'
def __init__(self, server):
# Operation.__init__(self,server,"t_%s" % string.lower(self.__class__.__name__))
super(IPsec, self).__init__(server)
def add_filter(self, protocal, source_addr, dport, description, status=0, chain='INPUT'):
try:
self.get_dbclass().add(server_id=self.server.dbid,
protocal=protocal,
source_addr=source_addr,
dport=dport,
description=description,
status=status,
chain=chain)
except:
pass
def del_filter(self, dbid):
pass
def get_filters(self):
exec_result=self.server.execute("iptables-save", hide_puts=True, hide_server_info=True)
if exec_result.succeed:
dbsession,dbclass = self.get_dbclass()
for line in exec_result.result.splitlines(True):
if not line.startswith('-A'):
continue
line=iter(line.strip().split())
line=dict(zip(line,line))
if (line.has_key('-m') and line['-m'] == 'state') and line.has_key('--state'):
continue
if line['-j'] == 'ACCEPT':
self.add_filter(line['-p'] if line.has_key('-p') else 'all',
line['-s'],
line['--dports'] if line.has_key('--dports') else None ,
None,
1,
line['-A'])
print "Collect from %s: Finished" % self.server
else:
print "Collect from %s: Failed -> %s" % (self.server,exec_result.result)
def clear_filters(self):
try:
self.get_dbclass().delete(self.server.dbid,"server_id")
print "clear finished"
except:
pass
def print_filter(self):
res_title=["dbid", "chain", 'source', 'dport', 'description']
#res_list = self.get_dbinfo()
res_table=prettytable.PrettyTable(res_title)
for col_name in res_title[1:]:
res_table.align[col_name]='l'
res_table.padding_width = 1
res_table.encoding = self.server.encoding
#for i in res_list:
for i in self.get_dbclass().get(self.server.dbid,"server_id"):
res_table.add_row([i.id, i.chain, i.source_addr, i.dport, i.description])
print res_table
def make_script(self):
filterlist = ''
if self.server.parent is not None:
if self.server.parent.s.ip_public is None or self.server.parent.s.ip_private is None:
print 'Please fill in the public and private address. And repeat'
return None
parent_iplist = []
parent_iplist.append(self.server.parent.s.ip_public)
parent_iplist.append(self.server.parent.s.ip_private)
parent_iplist.append(self.server.parent.s.ip_oper)
parent_iplist = [i for i in parent_iplist if i]
parent_iplist = list(set(parent_iplist))
for item in parent_iplist:
filterlist += '''$IPTABLES -I INPUT -s %s -p tcp --dport 22 -j ACCEPT; #cc:%s\n''' % (
item, self.server.parent)
for i in self.get_dbclass().get(self.server.dbid,"server_id"):
filterlist += '''$IPTABLES -I %s -s %s -p %s -m multiport --dport %s -j ACCEPT; #%s\n''' % (
i.chain, i.source_addr, i.protocal, i.dport, i.description)
ipsec_temp = '''
IPTABLES=/sbin/iptables;
$IPTABLES -F;
$IPTABLES -Z;
$IPTABLES -X;
$IPTABLES -t mangle -F;
$IPTABLES -t mangle -Z;
$IPTABLES -t mangle -X;
$IPTABLES -P INPUT ACCEPT;
$IPTABLES -I INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT;
$IPTABLES -I OUTPUT -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT ;
%s
$IPTABLES -I INPUT -s 127.0.0.1 -j ACCEPT;
$IPTABLES -P INPUT DROP;
$IPTABLES -P FORWARD DROP ;
$IPTABLES -P OUTPUT ACCEPT ;
service iptables save;
chkconfig --level=2345 iptables on
''' % filterlist
return ipsec_temp
def reload(self):
script = self.make_script()
if script:
self.server.execute(script)
def status(self):
cmd = "iptables -nvL"
return self.server.execute(cmd)
def script(self):
print self.make_script()
class Iptables_rules(object):
# db table class
__dbclass__ = None
# db session
__dbsession__ = None
#----------------------------------------------------------------------
@classmethod
def _get_dbclass(cls):
if cls.__dbsession__ and cls.__dbclass__:
return True
selfclassname = cls.__name__
dbclassname = "t_%s" % string.lower(selfclassname)
dbclass = None
dbsession = None
import importlib
mo = importlib.import_module('dbi')
if mo:
if hasattr(mo, dbclassname):
dbclass = getattr(mo, dbclassname)
if hasattr(mo, 'session'):
dbsession = getattr(mo, 'session')
if dbclass and dbsession:
cls.__dbsession__ = dbsession
cls.__dbclass__ = dbclass
return True
else:
return False
@classmethod
def _get_dbinfo(cls, dbid=None):
if not cls._get_dbclass():
return None
result = None
if dbid is not None:
result = cls.__dbsession__.query(cls.__dbclass__).filter(cls.__dbclass__.server_id == dbid).all()
cls.__dbsession__.close()
return result
def _generate_rules(self, raw_rules=None, trx_id=None):
try:
status = None
rules = {trx_id: []}
Table = None
for line in raw_rules:
line = line.strip()
if line.startswith('# Generated'):
status = "started"
elif line.startswith('*'):
Table = line.strip('*')
elif line.startswith(':'):
if status == "started" and Table:
Index = 0
Chain = line.strip(':').split()[0]
Policy = line.strip(':').split()[1]
rule = {Table: {Chain: {Index: {'POLICY': Policy}}}}
rules[trx_id].append(rule)
else:
raise "Logical errors during parsing iptables rules"
elif line.startswith('-'):
if status == "started" and Table:
Index += 1
line = line.split()
Chain = line[1]
i = iter(line)
rule = {Table: {Chain: {Index: dict(zip(i, i))}}}
rules[trx_id].append(rule)
else:
raise "Logical errors during parsing iptables rules"
elif line.startswith('# Completed'):
status = "Ended"
except:
pass
return rules
def _load_rules(self, trx_id=None):
pass
def __init__(self, srv, raw_rules=None, trx_id=None):
if srv is None:
raise "Server Is Null"
if type(srv) != Server:
raise "param type is not Server"
self.server = srv
self.trx_id = trx_id
self.rules = None
if raw_rules and self.trx_id:
self.rules = self._generate_rules(raw_rules=raw_rules, trx_id=self.trx_id)
elif not raw_rules and self.trx_id:
self.rules = self._load_rules(trx_id=self.trx_id)
if self.__class__.__dbsession__ is None or self.__class__.__dbclass__ is None:
self._get_dbclass()
def save_rules_to_db(self):
dbsession = self.__class__.__dbsession__
dbclass = self.__class__.__dbclass__
try:
for rule in self.rules[self.trx_id]:
for table, table_rule in rule.items():
for chain, chain_rule in table_rule.items():
for index, rule_args in chain_rule.items():
for opt, arg in rule_args.items():
dbsession.add(dbclass(
trx_id=self.trx_id,
index=index,
table=table,
chain=chain,
opt=opt,
arg=arg
))
dbsession.commit()
dbsession.close()
except Exception as e:
print "Error: %s" % e
class Iptables(object):
# db table class
__dbclass__ = None
# db session
__dbsession__ = None
#----------------------------------------------------------------------
@classmethod
def _get_dbclass(cls):
if cls.__dbsession__ and cls.__dbclass__:
return True
selfclassname = cls.__name__
dbclassname = "t_%s" % string.lower(selfclassname)
dbclass = None
dbsession = None
import importlib
mo = importlib.import_module('dbi')
if mo:
if hasattr(mo, dbclassname):
dbclass = getattr(mo, dbclassname)
if hasattr(mo, 'session'):
dbsession = getattr(mo, 'session')
if dbclass and dbsession:
cls.__dbsession__ = dbsession
cls.__dbclass__ = dbclass
return True
else:
return False