-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.py
executable file
·2099 lines (1675 loc) · 62.7 KB
/
test.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
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: utf8 -*-
# vim:set cc=80:
if 0:
# test OOB {{{1}}}
class Student(object):
__slots__ = ('name', 'age', 'score', '__privatename', '__grade')
def __init__(self, name, score):
self.name = name
self.score = score
self.__privatename = name
def print_score(self):
print '%s\'s score is %s' % (self.name, self.score)
# use __grade to test controlling method to a member
@property
def grade(self):
return self.__grade
@grade.setter
def grade(self, grade):
self.__grade = grade
jeremy = Student('jeremy', 92)
print "jeremy's name is %s" % jeremy.name
jeremy.print_score()
print "jeremy's private name is %s" % jeremy._Student__privatename
# print "private name is %s" % jeremy.__privatename
class Student_in_america(Student):
def print_score(self):
print '%s\'name is %s' % (self.name, self.score * 20)
xixi = Student_in_america('xixi', 4.7)
print "xixi's name is %s" % xixi.name
xixi.print_score()
'''
# test duotai {{{2}}}
print "is jeremy a student?"
isinstance(jeremy,Student)
print "is jeremy an america student?"
print isinstance(jeremy,Student_in_america)
print "is xixi a student?"
print isinstance(xixi,Student)
print "is xixi an america student?"
print isinstance(xixi,Student_in_america)
'''
'''
# test dir, len
print "dir of Student looks:-------------------------"
print dir('Student')
print len('Student')
print "dir of Student_in_america looks:-----------------------"
print dir('Student_in_america')
'''
# jeremy.set_grade(4)
# print jeremy.get_grade()
# test decoration {{{2}}}
jeremy.grade = 4
print jeremy.grade
# test for loop for object {{{2}}}
class Fib(object):
def __init__(self):
self.a, self.b = 0, 1 # 初始化两个计数器 a, b
def __iter__(self):
return self # 实例本身就是迭代对象,故返回自己
def next(self):
self.a, self.b = self.b, self.a + self.b # 计算下一个值
if self.a > 3: # 退出循环的条件
raise StopIteration()
return self.a # 返回下一个值
# pdb.set_trace()
for n in Fib():
print n
# test jason {{{1}}}
if 0:
import json
d = dict(name='Bob', age=20, score=88)
print "original dict looks %s" % d
j = json.dumps(d)
print "jsondump looks %s" % j
d1 = json.loads(j)
print "jsonloads looks %s" % d1
# test jason {{{2}}}
class Student(object):
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
s = Student('Bob', 20, 88)
# print(json.dumps(s))
def student2dict(std):
return {
'name': std.name,
'age': std.age,
'score': std.score
}
print "json dump looks %s" % json.dumps(s, default=student2dict)
# multi-tasking {{{1}}}
# multi-processing:
# multiprocessing -> Process, Pool, Queue
# multi-threading:
# threading ->
# multiprocessing {{{2}}}
'''
import os
print 'Process (%s) start...' % os.getpid()
pid = os.fork()
if pid==0:
print 'I am child process (%s) and my parent is %s.' % \
(os.getpid(), os.getppid())
else:
print 'I (%s) just created a child process (%s).' % \
(os.getpid(), pid)
'''
# multiprocessing.Process {{{3}}}
# create 1 or a few child processes...
if 0:
print "---------------multiprocessing.Process----------------------"
from multiprocessing import Process, Pool, Queue
import time
import os
import random
# 子进程要执行的代码
def run_proc(name):
print 'Run child process %s (%s)...' % (name, os.getpid())
print 'child process %s sleep 1s now' % name
time.sleep(1)
if __name__ == '__main__':
print 'Parent process %s.' % os.getpid()
p = Process(target=run_proc, args=('test',))
print 'will start a child process...'
p.start()
# wait for child process to end, before proceeding...
p.join()
print 'parent Process end.'
# multiprocessing.Pool {{{3}}}
# create a lot of child processes...
if 1:
print "----------------multiprocessing.Pool---------------------"
from multiprocessing import Process, Pool, Queue
import time
import os
import random
def long_time_task(name):
print 'Run task %s (%s)...' % (name, os.getpid())
start = time.time()
time.sleep(random.random() * 3)
end = time.time()
print 'Task %s runs %0.2f seconds.' % (name, (end - start))
if __name__ == '__main__':
print 'Parent process %s.' % os.getpid()
p = Pool()
for i in range(10):
p.apply_async(long_time_task, args=(i,))
print 'Waiting for all subprocesses done...'
p.close()
p.join()
# multiprocessing.Queue {{{3}}}
# inter process communication...
if 0:
print "----------------multiprocessing.Queue---------------------"
from multiprocessing import Process, Pool, Queue
import time
import os
import random
# 写数据进程执行的代码:
def write(q):
for value in ['A', 'B', 'C']:
print 'Put %s to queue...' % value
q.put(value)
time.sleep(random.random())
# 读数据进程执行的代码:
def read(q):
while True:
value = q.get(True)
print 'Get %s from queue.' % value
if __name__ == '__main__':
# 父进程创建 Queue,并传给各个子进程:
q = Queue()
pw = Process(target=write, args=(q,))
pr = Process(target=read, args=(q,))
# 启动子进程 pw,写入:
pw.start()
# 启动子进程 pr,读取:
pr.start()
# 等待 pw 结束:
pw.join()
# pr 进程里是死循环,无法等待其结束,只能强行终止:
pr.terminate()
# multiprocessing {{{2}}}
if 0:
import multiprocessing
import time
def func(msg):
for i in xrange(3):
print msg
time.sleep(1)
if __name__ == "__main__":
pool = multiprocessing.Pool(processes=4)
for i in xrange(10):
msg = "hello %d" %(i)
pool.apply_async(func, (msg, ))
pool.close()
pool.join()
print "Sub-process(es) done."
# multithreading {{{2}}}
if 0:
print "---------------multithreading----------------------"
# 启动一个线程就是把一个函数传入并创建 Thread 实例,然后调用 start()开始执行:
import threading
# 新线程执行的代码:
def loop():
print 'thread %s is running...' % threading.current_thread().name
n = 0
while n < 5:
n = n + 1
print '%s:thread %s >>> %s' % \
(time.time(), threading.current_thread().name, n)
time.sleep(1)
print 'thread %s ended.' % threading.current_thread().name
print 'thread %s is running...' % threading.current_thread().name
t = threading.Thread(target=loop, name='LoopThread')
t.start()
t.join()
print 'thread %s ended.' % threading.current_thread().name
'''
thread MainThread is running...
thread LoopThread is running...
1478741107.56:thread LoopThread >>> 1
1478741107.56:thread LoopThread >>> 2
1478741107.56:thread LoopThread >>> 3
1478741107.56:thread LoopThread >>> 4
1478741107.56:thread LoopThread >>> 5
thread LoopThread ended.
thread MainThread ended.
'''
# use global var without lock: wrong{{{3}}}
'''
problem of multi-threading:
global var are shared by all threads
and in multi-thread environment, things may get wrong
'''
from multiprocessing import Process, Pool, Queue
import threading
import time
import os
import random
balance = 0
def change_it(n):
# 先存后取,结果应该为 0:
global balance
balance = balance + n
balance = balance - n
def run_thread(n):
for i in range(100000):
change_it(n)
t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
print balance
'''
ping@ubuntu47-3:~/Dropbox/python$ python test.py
40
ping@ubuntu47-3:~/Dropbox/python$ python test.py
107
ping@ubuntu47-3:~/Dropbox/python$ python test.py
84
ping@ubuntu47-3:~/Dropbox/python$ python test.py
34
'''
# use global var withlock {{{3}}}
'''
one solution is to use thead lock
'''
from multiprocessing import Process, Pool, Queue
import time
import os
import random
import threading
balance = 0
lock = threading.Lock()
def change_it(n):
# 先存后取,结果应该为 0:
global balance
balance = balance + n
balance = balance - n
def run_thread(n):
for i in range(100000):
# 先要获取锁:
lock.acquire()
try:
# 放心地改吧:
change_it(n)
finally:
# 改完了一定要释放锁:
lock.release()
t1 = threading.Thread(target=run_thread, args=(5,))
t2 = threading.Thread(target=run_thread, args=(8,))
t1.start()
t2.start()
t1.join()
t2.join()
print balance
# multi-core support {{{3}}}
'''
python threads' multi-core support
'''
import threading
import multiprocessing
def loop():
x = 0
while True:
x = x ^ 1
for i in range(multiprocessing.cpu_count()):
t = threading.Thread(target=loop)
t.start()
# use local var with threading.local {{{3}}}
'''
thread1:
process_thread:
args: Alice, name:Thread-A
pass: Alice -> name
process_student(name)
thread2:
process_thread:
args: Bob, name:Thread-B
pass: Bob -> name
process_student(name)
'''
import threading
# 创建全局 ThreadLocal 对象:
local_school = threading.local()
def process_student():
print 'Hello, %s (in %s)' % \
(local_school.student, threading.current_thread().name)
def process_thread(name):
# 绑定 ThreadLocal 的 student:
local_school.student = name
process_student()
t1 = threading.Thread(target=process_thread,
args=('Alice',), name='Thread-A')
t2 = threading.Thread(target=process_thread,
args=('Bob',), name='Thread-B')
t1.start()
t2.start()
t1.join()
t2.join()
'''
distributed computing:
it looks for me, that server just dispatch a number (n in this case)
client to get this number from the queue, and then do the task
then client return the result (also a number) to server,
then server display it.
need to understand: how to use this in practical?
'''
role = 'server'
# role = 'client'
if role == 'server':
# taskmanager.py {{{4}}}
import random
import time
import Queue
from multiprocessing.managers import BaseManager
# 发送任务的队列:
task_queue = Queue.Queue()
# 接收结果的队列:
result_queue = Queue.Queue()
# 从 BaseManager 继承的 QueueManager:
class QueueManager(BaseManager):
pass
# 把两个 Queue 都注册到网络上, callable 参数关联了 Queue 对象:
QueueManager.register('get_task_queue', callable=lambda: task_queue)
QueueManager.register('get_result_queue', callable=lambda: result_queue)
# 绑定端口 5000, 设置验证码'abc':
manager = QueueManager(address=('', 5000), authkey='abc')
# 启动 Queue:
manager.start()
# 获得通过网络访问的 Queue 对象:
task = manager.get_task_queue()
result = manager.get_result_queue()
# 放几个任务进去:
for i in range(10):
n = random.randint(0, 10000)
print('Put task %d...' % n)
task.put(n)
# 从 result 队列读取结果:
print('Try get results...')
for i in range(10):
r = result.get(timeout=100)
print('Result: %s' % r)
# 关闭:
manager.shutdown()
else:
# taskworker.py {{{4}}}
import time
import sys
import Queue
from multiprocessing.managers import BaseManager
# 创建类似的 QueueManager:
class QueueManager(BaseManager):
pass
# 由于这个 QueueManager 只从网络上获取 Queue,所以注册时只提供名字:
QueueManager.register('get_task_queue')
QueueManager.register('get_result_queue')
# 连接到服务器,也就是运行 taskmanager.py 的机器:
server_addr = '127.0.0.1'
print('Connect to server %s...' % server_addr)
# 端口和验证码注意保持与 taskmanager.py 设置的完全一致:
m = QueueManager(address=(server_addr, 5000), authkey='abc')
# 从网络连接:
m.connect()
# 获取 Queue 的对象:
task = m.get_task_queue()
result = m.get_result_queue()
# 从 task 队列取任务,并把结果写入 result 队列:
for i in range(10):
try:
n = task.get(timeout=1)
print('run task %d * %d...' % (n, n))
r = '%d * %d = %d' % (n, n, n*n)
time.sleep(1)
result.put(r)
except Queue.Empty:
print('task queue is empty.')
# 处理结束:
print('worker exit.')
# pyez {{{1}}}
# Device module {{{2}}}
if 0:
# pprint print things in a prettier format
from pprint import pprint
from jnpr.junos import Device
# if __name__ == '__main__':
# connect to router {{{3}}}
# create an instance of class Device
myrouter = Device(host='172.19.161.129', user='labroot', passwd='lab123')
# start netconf-over-ssh connection to router
# this will return the same instance 'myrouter', represented as
# "Device(myrouter)"
myrouter.open()
from IPython.Shell import IPShellEmbed
IPShellEmbed([])()
# #above 2 lines can be merged into one line
# myrouter=Device(host='172.19.161.129',user='labroot',passwd='lab123').open()
# close the netconf connection
myrouter.close()
# myrouter.facts dict {{{3}}}
if 0:
# facts gathering is enabled by default, can be disabled to speed up:
# dev.open(gather_facts=False)
# and later can still be enabled:
# dev.facts_refresh()
pprint(myrouter.facts)
interface_lxml_element = myrouter.rpc.get_interface_information(terse=True)
list_of_interfaces = interface_lxml_element.findall('physical-interface')
print "list_of_interfaces looks %s:" % list_of_interfaces
for interface in list_of_interfaces:
# print "interface in the list looks: %s" % interface
print "Interface: %s Status: %s " % (
interface.findtext('name').strip(),
interface.findtext('oper-status').strip()
)
# myrouter.cli: send a command
print myrouter.cli("show interfaces terse fxp0")
# myrouter.close()
# yaml module {{{2}}}
if 0:
import yaml
ethport_yaml_file_path = \
'/usr/local/lib/python2.7/dist-packages/jnpr/junos/op/ethport.yml'
yaml_file = open(ethport_yaml_file_path, "r")
data = yaml.load(yaml_file)
print data
for key in data:
print "key: %s" % key
print "value: %s" % data[key]
# EthPortTable module {{{2}}}
if 0:
'''
EthPortTable module
'''
from jnpr.junos import Device
from jnpr.junos.op.ethport import EthPortTable
from pprint import pprint
myrouter = Device(host='172.19.161.129', user='labroot', passwd='lab123')
myrouter.open()
# create EthPortTable obj
eth_interfaces = EthPortTable(myrouter)
eth_interfaces.get()
print "eth_interface.keys() looks:\n ",
pprint(eth_interfaces.keys())
for interface in eth_interfaces:
print "interface.keys() looks:\n ",
print interface.keys()
print interface.name + "'s keys,name,admin,oper,macadd looks:"
print " " + interface.name, interface.admin,\
interface.oper, interface.macaddr
myrouter.close()
# Config module {{{2}}}
if 0:
from jnpr.junos import Device
from jnpr.junos.utils.config import Config
import time
import os
import sys
from jnpr.junos.exception import *
MAX_ATTEMPTS = 3
WAIT_BEFORE_RECONNECT = 10
# Assumes r0 already exists and is a connected device instance
for attempt in range(MAX_ATTEMPTS):
try:
myrouter = Device(host='172.19.161.129', user='labroot',
passwd='lab123')
myrouter.open()
cfg = Config(myrouter)
print "connection opened"
# load override abc.conf {{{3}}}
# this won't work, for some reason, has to use either absolute path,
# or change the dir first
config_file = "~/download_folder/backup.botanix.161101.jtac.conf"
# this works
config_file = \
"/home/ping/download_folder/backup.botanix.161101.jtac.conf"
cfg.load(path=config_file, format="text", merge=True)
# #this works
# os.chdir('/home/ping/download_folder')
# cfg.load(path="backup.botanix.161101.jtac.conf",overwrite=True)
print "config loaded"
# commit confirm {{{3}}}
cfg.commit(confirm=2)
time.sleep(10)
print "commit confirm 2"
# commit {{{3}}}
cfg.commit()
print "commited"
# edit exclusive {{{3}}}
cfg.lock()
# rollback 2 {{{3}}}
cfg.rollback(rb_id=2)
print "rollback 2"
# commit {{{3}}}
cfg.commit()
print "commited"
# unlock {{{3}}}
cfg.unlock()
# config one statement {{{3}}}
cfg.load("set system host-name mytest_python",
format="set", merge=True)
print cfg.diff()
cfg.rollback(0)
myrouter.close
except ConnectAuthError:
print "Authentication error!"
myrouter.close()
sys.exit()
except ConnectTimeoutError:
print "Timeout error!"
myrouter.close()
sys.exit()
except ConfigLoadError:
print "Couldn't unlock the config db!"
myrouter.close()
sys.exit()
except Exception as error:
if isinstance(error, RpcTimeoutError):
print "Rpc Timeout while loading the config!"
myrouter.close()
# elif type(error) is CommitError:
else:
print "Encountered an expected exception"
print error
sys.exit()
# route table {{{2}}}
if 0:
from jnpr.junos.op.routes import RouteTable
route_table = RouteTable(myrouter)
route_table.get('192.168.1.0/24')
route_table.get('12.123.73.43/32')
route_table.get()
route_table.get('192.168.4.0/24', table='inet.0', protocol='static')
route_table.get(protocol='isis')
for key in route_table:
print key.name + ' Nexthop: ' + key.nexthop + ' Via: ' + \
key.via + ' Protocol: ' + key.protocol
# a working example {{{2}}}
if 0:
#!/usr/bin/env python
"""Use interface descriptions to track the topology reported by LLDP.
This includes the following steps:
1) Gather LLDP neighbor information.
2) Gather interface descriptions.
3) Parse LLDP neighbor information previously stored in the descriptions.
4) Compare LLDP neighbor info to previous LLDP info from the descriptions.
5) Print LLDP Up / Change / Down events.
6) Store the updated LLDP neighbor info in the interface descriptions.
Interface descriptions are in the format:
[user-configured description ]LLDP: <remote system> <remote port>[(DOWN)]
The '(DOWN)' string indicates an LLDP neighbor which was previously
present, but is now not present.
"""
import sys
import getpass
import jxmlease
from jnpr.junos import Device
from jnpr.junos.utils.config import Config
import jnpr.junos.exception
TEMPLATE_PATH = 'interface_descriptions_template.xml'
# Create a jxmlease parser with desired defaults.
parser = jxmlease.EtreeParser()
class DoneWithDevice(Exception): pass
def main(): # {{{3}}}
"""The main loop.
Prompt for a username and password.
Loop over each device specified on the command line.
Perform the following steps on each device:
1) Get LLDP information from the current device state.
2) Get interface descriptions from the device configuration.
3) Compare the LLDP information against the previous snapshot of LLDP
information stored in the interface descriptions. Print changes.
4) Build a configuration snippet with new interface descriptions.
5) Commit the configuration changes.
Return an integer suitable for passing to sys.exit().
"""
if len(sys.argv) == 1:
print("\nUsage: %s device1 [device2 [...]]\n\n" % sys.argv[0])
return 1
rc = 0
# Get username and password as user input.
user = raw_input('Device Username: ')
password = getpass.getpass('Device Password: ')
for hostname in sys.argv[1:]:
try:
print("Connecting to %s..." % hostname)
dev = Device(host=hostname,
user=user,
password=password,
normalize=True
)
dev.open()
# retrieving LLDP info {{{4}}}
print("Getting LLDP information from %s..." % hostname)
lldp_info = get_lldp_neighbors(device=dev)
if lldp_info == None:
print(" Error retrieving LLDP info on " +\
hostname +\
". Make sure LLDP is enabled."
)
rc = 1
raise DoneWithDevice
# retrieving int desc info {{{4}}}
print("Getting interface descriptions from %s..." % hostname)
desc_info = get_description_info_for_interfaces(device=dev)
if desc_info == None:
print(" Error retrieving interface descriptions on %s." %
hostname)
rc = 1
raise DoneWithDevice
# check lldp change {{{4}}}
desc_changes = check_lldp_changes(lldp_info, desc_info)
if not desc_changes:
print(" No LLDP changes to configure on %s." % hostname)
raise DoneWithDevice
# load merge temp config {{{4}}}
if load_merge_template_config(
device=dev,
template_path=TEMPLATE_PATH,
template_vars={'descriptions': desc_changes}
):
print("Successfully committed configuration changes on %s."
% hostname)
else:
print(" Error committing description changes on %s." %
hostname)
rc = 1
raise DoneWithDevice
except jnpr.junos.exception.ConnectError as err:
print(" Error connecting: " + repr(err))
rc = 1
except DoneWithDevice:
pass
finally:
print(" Closing connection to %s." % hostname)
try:
dev.close()
except:
pass
return rc
def get_lldp_neighbors(device): # {{{3}}}
"""
Get current LLDP neighbor information.
Return a two-level dictionary with the LLDP neighbor information.
The first-level key is the local port (aka interface) name.
The second-level keys are 'system' for the remote system name
and 'port' for the remote port ID. On error, return None.
For example:
{'ge-0/0/1': {'system': 'r1', 'port', 'ge-0/0/10'}}
"""
lldp_info = {}
try:
resp = device.rpc.get_lldp_neighbors_information()
except (jnpr.junos.exception.RpcError,
jnpr.junos.exception.ConnectError) as err:
print " " + repr(err)
return None
for nbr in resp.findall('lldp-neighbor-information'):
local_port = nbr.findtext('lldp-local-port-id')
remote_system = nbr.findtext('lldp-remote-system-name')
remote_port = nbr.findtext('lldp-remote-port-id')
if local_port and (remote_system or remote_port):
lldp_info[local_port] = {
'system': remote_system,
'port': remote_port
}
return lldp_info
def get_description_info_for_interfaces(device): # {{{3}}}
"""
Get current interface description for each interface.
Parse the description into the user-configured description, remote system,
and remote port components.
Return a two-level dictionary. The first-level key is the local port (aka
interface) name. The second-level keys are 'user_desc' for the
user-configured description, 'system' for the remote system name, 'port'
for the remote port, and 'down', which is a Boolean indicating if LLDP was
previously down. On error, return None. For example: {'ge-0/0/1':
{'user_desc': 'test description', 'system': 'r1', 'port': 'ge-0/0/10',
'down': True}}
"""
desc_info = {}
try:
resp = parser(device.rpc.get_interface_information(descriptions=True))
except (jnpr.junos.exception.RpcError,
jnpr.junos.exception.ConnectError) as err:
print " " + repr(err)
return None
try:
pi = resp['interface-information']['physical-interface'].jdict()
except KeyError:
return desc_info
for (local_port, port_info) in pi.items():
try:
(udesc, _, ldesc) = port_info['description'].partition('LLDP: ')
udesc = udesc.rstrip()
(remote_system, _, remote_port) = ldesc.partition(' ')
(remote_port, down_string, _) = remote_port.partition('(DOWN)')
desc_info[local_port] = {
'user_desc': udesc,
'system': remote_system,
'port': remote_port,
'down': True if down_string else False
}
except (KeyError, TypeError):
pass
return desc_info
def check_lldp_changes(lldp_info, desc_info): # {{{3}}}
"""
Compare current LLDP info with previous snapshot from descriptions.
Given the dictionaries produced by get_lldp_neighbors() and
get_description_info_for_interfaces(), print LLDP up, change, and down
messages.
Return a dictionary containing information for the new descriptions
to configure.
"""
desc_changes = {}
# Iterate through the current LLDP neighbor state. Compare this
# to the saved state as retrieved from the interface descriptions.
for local_port in lldp_info:
lldp_system = lldp_info[local_port]['system']
lldp_port = lldp_info[local_port]['port']
has_lldp_desc = desc_info.has_key(local_port)
desc_system = desc_port = False
if has_lldp_desc:
desc_system = desc_info[local_port]['system']
desc_port = desc_info[local_port]['port']
down = desc_info[local_port]['down']
if not desc_system or not desc_port:
has_lldp_desc = False
if not has_lldp_desc:
print(" %s LLDP Up. Now: %s %s" \
% \
(local_port,lldp_system,lldp_port)
)
elif down:
print(" %s LLDP Up. Was: %s %s Now: %s %s" %
(local_port,desc_system,desc_port,lldp_system,lldp_port))
elif lldp_system != desc_system or lldp_port != desc_port:
print(" %s LLDP Change. Was: %s %s Now: %s %s" %
(local_port,desc_system,desc_port,lldp_system,lldp_port))
else:
# No change. LLDP was not down. Same system and port.
continue
desc_changes[local_port] = "LLDP: %s %s" % (lldp_system,lldp_port)
# Iterate through the saved state as retrieved from the interface
# descriptions. Look for any neighbors that are present in the
# saved state, but are not present in the current LLDP neighbor