-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstart.py
928 lines (794 loc) · 35.6 KB
/
start.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
import os
import sys
import yaml
import time
import shutil
import getpass
import logging
import paramiko
import jnpr.junos
from pathlib import Path
from scp import SCPClient
from jnpr.junos import Device
from datetime import datetime
from jnpr.junos.factory.factory_loader import FactoryLoader
yml = """
---
bgpAdvertiseRoutes:
rpc: get-route-information
args:
advertising-protocol-name: bgp
extensive: True
item: route-table/rt
key: rt-destination
view: bgpAdvertiseView
bgpAdvertiseView:
fields:
rt_destination: rt-destination
rt_prefix_length: rt-prefix-length
rt_protocol_name: rt-entry/protocol-name
bgp_group_name: rt-entry/bgp-group-name
bgp_nh: rt-entry/nh/to
rt_med: rt-entry/med
rt_local_preference: rt-entry/local-preference
rt_as_path: rt-entry/as-path
rt_communities: rt-entry/communities/community
bgpSummary:
rpc: get-bgp-summary-information
"""
def login_details():
global varIP
global varUser
global varPassword
varIP = input("Please enter the Hostname or IP of your target Device: ")
varUser = input("Please Enter a Username (NOT ROOT): ")
varPassword = getpass.getpass()
if str(varUser) == 'root':
sys.exit(
' .----------.\n / .-. .-. \\\n / | | | | \\\n \\ `-\' `-\' _/\n /\\ .--. / |\n \\ | / / / /\n / | `--\' /\\ \\\n /`-------\' \\ \\ \n By choosing the name root you have doomed us all!\nBuy fear not - I have ended this script so the apocalypse is not today ;)\n')
def bgp_adv():
globals().update(FactoryLoader().load(yaml.safe_load(yml)))
with Device(varIP, port='22', user=varUser, passwd=varPassword) as dev:
op = dev.rpc.get_bgp_summary_information()
for i in op.xpath('bgp-peer/peer-address'):
# print(i.text)
load_bgp = bgpAdvertiseRoutes(dev).get(neighbor=i.text)
print("\n-----------------BGP Advertising Routes For:", i.text, "-----------------")
for item in load_bgp:
print('----------------------------------------------')
print("Advertising_Route:", item.rt_destination, "Prefix_Lengh:", item.rt_prefix_length, "MED:",
item.rt_med, "LP:", item.rt_local_preference, "AS_Path:", item.rt_as_path, "Communities:",
item.rt_communities)
print("\n")
print("\n")
def set_vlan():
devices = [
varIP,
]
varVlName = str(input("Please Enter the vlan Name to be deployed: "))
while True:
try:
varintVlID = int(input("Please Enter the vlan ID for " + varVlName + " between 1 and 4092: "))
except ValueError:
print("That is not a number!")
else:
if 1 < varintVlID <= 4092:
break
else:
print("Only numbers between 1 and 4092 are allowed. The IDs 0, 4093 and above are used internally.")
varVlID = str(varintVlID)
for switch in devices:
# Connect to switch and build ssh connection
remote_conn_pre = paramiko.SSHClient()
remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
remote_conn_pre.connect(switch, username=varUser, password=varPassword, look_for_keys=False, allow_agent=False)
print('SSH connection established to ' + switch)
remote_conn = remote_conn_pre.invoke_shell()
print('Interactive SSH session established')
# Print terminal to screen
output = remote_conn.recv(3000)
remote_conn.send('\n')
time.sleep(2)
print(output.decode())
# Username root requires getting into the cli
if varUser == 'root':
remote_conn.send('cli\n')
time.sleep(3)
output = remote_conn.recv(3000)
print(output.decode())
else:
pass
# Enter configuration mode
remote_conn.send('configure\n')
time.sleep(2)
output = remote_conn.recv(3000)
print(output.decode())
# SNMP Configuration
remote_conn.send('set vlans ' + varVlName + ' vlan-id ' + varVlID + '\n')
time.sleep(2)
output = remote_conn.recv(3000)
print(output.decode())
# Save configuration
remote_conn.send("commit and-quit\n")
time.sleep(6)
output = remote_conn.recv(3000)
print(output.decode())
# Exit configuration mode
remote_conn.send('exit\n')
time.sleep(2)
output = remote_conn.recv(3000)
print(output.decode())
if varUser == 'root':
remote_conn.send('exit\n')
time.sleep(2)
output = remote_conn.recv(3000)
print(output.decode())
else:
pass
def bgp_summary():
port_arg = 22
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(varIP, username=varUser, password=varPassword, port=port_arg)
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
channel = ssh.invoke_shell()
stdin, stdout, stderr = ssh.exec_command(
'show bgp summary\n')
exit_status = stdout.channel.recv_exit_status()
stdout = stdout.readlines()
print('\n'.join(stdout))
ssh.close()
print("\n")
print("\n")
except paramiko.AuthenticationException as error:
print("Error: The Credentials did not work or ssh / netconf is not enabled!")
print("\n")
print("\n")
def chassis_re():
port_arg = 22
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(varIP, username=varUser, password=varPassword, port=port_arg)
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
channel = ssh.invoke_shell()
stdin, stdout, stderr = ssh.exec_command(
'show chassis routing-engine\n')
exit_status = stdout.channel.recv_exit_status()
stdout = stdout.readlines()
print('\n'.join(stdout))
ssh.close()
print("\n")
print("\n")
except paramiko.AuthenticationException as error:
print("Error: The Credentials did not work or ssh / netconf is not enabled!")
print("\n")
print("\n")
def dev_script():
port_arg = 22
dev = Device(host=varIP, user=varUser, password=varPassword, gather_facts=True)
dev.open()
dev.timeout = 60
facts = dev.facts
print(dev.facts['serialnumber'])
print("\n")
print("\n")
def ospf_neighbors():
port_arg = 22
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(varIP, username=varUser, password=varPassword, port=port_arg)
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
channel = ssh.invoke_shell()
stdin, stdout, stderr = ssh.exec_command(
'show ospf neighbor\n')
exit_status = stdout.channel.recv_exit_status()
stdout = stdout.readlines()
print('\n'.join(stdout))
ssh.close()
print("\n")
print("\n")
except paramiko.AuthenticationException as error:
print("Error: The Credentials did not work or ssh / netconf is not enabled!")
print("\n")
print("\n")
def if_descr():
port_arg = 22
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(varIP, username=varUser, password=varPassword, port=port_arg)
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
channel = ssh.invoke_shell()
stdin, stdout, stderr = ssh.exec_command(
'show interfaces descriptions\n')
exit_status = stdout.channel.recv_exit_status()
stdout = stdout.readlines()
print('\n'.join(stdout))
ssh.close()
print("\n")
print("\n")
except paramiko.AuthenticationException as error:
print("Error: The Credentials did not work or ssh / netconf is not enabled!")
print("\n")
print("\n")
def get_device():
port_arg = 22
dev = Device(host=varIP, user=varUser, password=varPassword, gather_facts=True)
dev.open()
dev.timeout = 60
facts = dev.facts
print("Device has been identified as: " + dev.facts['model'])
print("Device has the following Serialnumber: " + dev.facts['serialnumber'])
print("Device is currently running on: " + dev.facts['version'])
print("\n")
print("\n")
def enable_netconf():
devices = [
varIP,
]
for switch in devices:
# Connect to switch and build ssh connection
remote_conn_pre = paramiko.SSHClient()
remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
remote_conn_pre.connect(switch, username=varUser, password=varPassword, look_for_keys=False, allow_agent=False)
print('SSH connection established to ' + switch)
remote_conn = remote_conn_pre.invoke_shell()
print('Interactive SSH session established')
# Print terminal to screen
output = remote_conn.recv(3000)
remote_conn.send('\n')
time.sleep(2)
print(output.decode())
# Username root requires getting into the cli
if varUser == 'root':
remote_conn.send('cli\n')
time.sleep(3)
output = remote_conn.recv(3000)
print(output.decode())
else:
pass
# Enter configuration mode
remote_conn.send('configure\n')
time.sleep(2)
output = remote_conn.recv(3000)
print(output.decode())
# SNMP Configuration
remote_conn.send('set system services netconf ssh\n')
time.sleep(2)
output = remote_conn.recv(3000)
print(output.decode())
# Save configuration
remote_conn.send("commit and-quit\n")
time.sleep(6)
output = remote_conn.recv(3000)
print(output.decode())
# Exit configuration mode
remote_conn.send('exit\n')
time.sleep(2)
output = remote_conn.recv(3000)
print(output.decode())
if varUser == 'root':
remote_conn.send('exit\n')
time.sleep(2)
output = remote_conn.recv(3000)
print(output.decode())
else:
pass
def disable_netconf():
devices = [
varIP,
]
for switch in devices:
# Connect to switch and build ssh connection
remote_conn_pre = paramiko.SSHClient()
remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
remote_conn_pre.connect(switch, username=varUser, password=varPassword, look_for_keys=False, allow_agent=False)
print('SSH connection established to ' + switch)
remote_conn = remote_conn_pre.invoke_shell()
print('Interactive SSH session established')
# Print terminal to screen
output = remote_conn.recv(3000)
remote_conn.send('\n')
time.sleep(2)
print(output.decode())
# Username root requires getting into the cli
if varUser == 'root':
remote_conn.send('cli\n')
time.sleep(3)
output = remote_conn.recv(3000)
print(output.decode())
else:
pass
# Enter configuration mode
remote_conn.send('configure\n')
time.sleep(2)
output = remote_conn.recv(3000)
print(output.decode())
# SNMP Configuration
remote_conn.send('delete system services netconf\n')
time.sleep(2)
output = remote_conn.recv(3000)
print(output.decode())
# Save configuration
remote_conn.send("commit and-quit\n")
time.sleep(6)
output = remote_conn.recv(3000)
print(output.decode())
# Exit configuration mode
remote_conn.send('exit\n')
time.sleep(2)
output = remote_conn.recv(3000)
print(output.decode())
if varUser == 'root':
remote_conn.send('exit\n')
time.sleep(2)
output = remote_conn.recv(3000)
print(output.decode())
else:
pass
def spanning_unblock():
port_arg = 22
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(varIP, username=varUser, password=varPassword, port=port_arg)
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
channel = ssh.invoke_shell()
stdin, stdout, stderr = ssh.exec_command(
'clear ethernet-switching bpdu-error\n')
exit_status = stdout.channel.recv_exit_status()
stdout = stdout.readlines()
print('\n'.join(stdout))
ssh.close()
print("\n")
print("\n")
except paramiko.AuthenticationException as error:
print("Error: The Credentials did not work or ssh / netconf is not enabled!")
print("\n")
print("\n")
def spanning_block():
port_arg = 22
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(varIP, username=varUser, password=varPassword, port=port_arg)
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
channel = ssh.invoke_shell()
stdin, stdout, stderr = ssh.exec_command(
'show ethernet-switching interface | match "Forwarding|Blocking|fe-|ge-|xe-|et-"\n')
exit_status = stdout.channel.recv_exit_status()
stdout = stdout.readlines()
print('\n'.join(stdout))
ssh.close()
print("\n")
print("\n")
except paramiko.AuthenticationException as error:
print("Error: The Credentials did not work or ssh / netconf is not enabled!")
print("\n")
print("\n")
def get_processes():
port_arg = 22
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(varIP, username=varUser, password=varPassword, port=port_arg)
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
channel = ssh.invoke_shell()
stdin, stdout, stderr = ssh.exec_command(
'start shell command "top | egrep \\"root|PID|last pid\\" | egrep -v \\" 0.00%\\"" \n')
exit_status = stdout.channel.recv_exit_status()
stdout = stdout.readlines()
print('\n'.join(stdout))
ssh.close()
print("\n")
print("\n")
except paramiko.AuthenticationException as error:
print("Error: The Credentials did not work or ssh / netconf is not enabled!")
print("\n")
print("\n")
def njsupport():
now = datetime.now()
dir_config = 'configuration'
dir_rsi = 'rsi'
dir_core = 'core-dumps'
dir_logfiles = 'logfiles'
dir_root = 'upload'
date_arg = now.strftime("%Y-%m-%d_%H-%M-%S")
# Set up logging
log = "njs.log"
logging.basicConfig(filename=log, level=logging.DEBUG, format='%(asctime)s %(message)s',
datefmt='%d/%m/%Y %H:%M:%S')
buff = ''
resp = ''
while True:
try:
varPath = str(input("Do you want the support package [R]emote (on the box) or [L]ocal (download to this PC)?: "))
except ValueError:
print("Please choose either R for Remote or L for Local")
else:
if varPath=="R" or varPath=="L":
break
else:
print("Please choose either R for Remote or L for Local")
print("\n")
print("\n")
print("\n")
print("###############################################################################")
print("# #")
print("# WARNING: Please leave this Window open and running. #")
print("# #")
print("###############################################################################")
print("\n")
print("\n")
print("\n")
print("Script is starting...")
logging.info('Script is starting...')
time.sleep(2)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(varIP, username=varUser, password=varPassword)
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
channel = ssh.invoke_shell()
# Creating necessary folders (if they don't exist) so root folder does not get messy
logging.info('Trying to create necessary folders')
if not os.path.exists(dir_root + '-' + varIP + '-' + date_arg):
os.mkdir(dir_root + '-' + varIP + '-' + date_arg)
logging.info('Info: root directory created successfully')
else:
logging.info('Info: root directory already existed!')
if not os.path.exists(dir_root + '-' + varIP + '-' + date_arg + '/' + dir_config):
os.mkdir(dir_root + '-' + varIP + '-' + date_arg + '/' + dir_config)
logging.info('Info: directory for configuration-files created successfully')
else:
logging.info('Info: directory for configuration-files already existed!')
if not os.path.exists(dir_root + '-' + varIP + '-' + date_arg + '/' + dir_rsi):
os.mkdir(dir_root + '-' + varIP + '-' + date_arg + '/' + dir_rsi)
logging.info('Info: directory for rsi-files created successfully')
else:
logging.info('Info: directory for rsi-files already existed!')
if not os.path.exists(dir_root + '-' + varIP + '-' + date_arg + '/' + dir_core):
os.mkdir(dir_root + '-' + varIP + '-' + date_arg + '/' + dir_core)
logging.info('Info: directory for core-dumps created successfully')
else:
logging.info('Info: directory for core-dumps already existed!')
if not os.path.exists(dir_root + '-' + varIP + '-' + date_arg + '/' + dir_logfiles):
os.mkdir(dir_root + '-' + varIP + '-' + date_arg + '/' + dir_logfiles)
logging.info('Info: directory for logfiles created successfully')
else:
logging.info('Info: directory for logfiles already existed!')
# Saving the config
print("\n")
print("Step 1/5: Saving the active configuration in set-format (including secrets)")
logging.info('Step1/5: Saving the active configuration in set-format (including secrets)')
stdin, stdout, stderr = ssh.exec_command(
'show configuration | display set | no-more | save /var/tmp/active-config-' + date_arg + '.txt\n')
exit_status = stdout.channel.recv_exit_status()
if exit_status == 0:
logging.info('Info: Configuration saved successfully.')
else:
logging.info('Error: Could not save configuration.')
# Creating the RSI (save to file) and wait for it to complete
# See https://www.juniper.net/documentation/en_US/junos/topics/reference/command-summary/request-support-information.html
print("\n")
print("Step 2/5: Creating the RSI")
logging.info('Step 2/5: Creating the RSI')
stdin, stdout, stderr = ssh.exec_command('request support information | save /var/tmp/rsi-' + date_arg + '.txt\n')
exit_status = stdout.channel.recv_exit_status()
if exit_status == 0:
logging.info('Info: RSI created successfully.')
else:
logging.info('Error: Could not create RSI. Please check the device manually.')
# Compressing the Logfiles
# See https://www.juniper.net/documentation/en_US/junos/topics/task/troubleshooting/troubleshooting-logs-compressing.html
print("\n")
print("Step 3/5: Compressing the Logfiles")
logging.info('Step 3/5: Compressing the Logfiles')
stdin, stdout, stderr = ssh.exec_command(
'file archive compress source /var/log/* destination /var/tmp/logfiles-' + date_arg + '.tgz\n')
exit_status = stdout.channel.recv_exit_status()
if exit_status == 0:
logging.info('Info: Logfiles compressed successfully.')
else:
logging.info('Error: Logfiles not compresses successfully. Check Device manually.')
if varPath == "L":
# Now downloading all the files created on the device via scp
print("\n")
print("Step 4/5: Fetching the files created earlier")
logging.info('Step 4/5: Fetching the files created earlier')
logging.info('Info: Fetching RSI...')
try:
with SCPClient(ssh.get_transport(), sanitize=lambda x: x) as scp:
scp.get(remote_path='/var/tmp/rsi-' + date_arg + '.txt',
local_path='./' + dir_root + '-' + varIP + '-' + date_arg + '/' + dir_rsi + '/')
except:
logging.info('Error: Could not fetch RSI - something went wrong...')
scp.close()
finally:
logging.info('Info: RSI successfully fetched.')
scp.close()
logging.info('Info: Fetching Logfiles...')
try:
with SCPClient(ssh.get_transport(), sanitize=lambda x: x) as scp:
scp.get(remote_path='/var/tmp/logfiles-' + date_arg + '.tgz',
local_path='./' + dir_root + '-' + varIP + '-' + date_arg + '/' + dir_logfiles + '/')
except:
logging.info('Error: Could not fetch Logfiles - something went wrong...')
scp.close()
finally:
logging.info('Info: Logfiles successfully fetched.')
scp.close()
logging.info('Info: Fetching Configuration...')
try:
with SCPClient(ssh.get_transport(), sanitize=lambda x: x) as scp:
scp.get(remote_path='/var/tmp/active-config-' + date_arg + '.txt',
local_path='./' + dir_root + '-' + varIP + '-' + date_arg + '/' + dir_config + '/')
except:
logging.info('Error: Could not fetch active Configuration - something went wrong...')
scp.close()
finally:
logging.info('Info: Configuration successfully fetched.')
scp.close()
logging.info('Info: Now fetching the crash-dumps (core-dumps) if they exist...')
try:
with SCPClient(ssh.get_transport(), sanitize=lambda x: x) as scp:
scp.get(remote_path='/var/crash/*',
local_path='./' + dir_root + '-' + varIP + '-' + date_arg + '/' + dir_core + '/')
except:
logging.info('Info: No crash-dumps (core-dumps) found - this is a good sign.')
scp.close()
finally:
logging.info('Warning: crash-dumps (core-dumps) found and transferred...')
scp.close()
print("\n")
print("Step 5/5: Deleting files from remote device to gain space back and finishing script")
logging.info('Step 5/5: Deleting files from remote device to gain space back and finishing script')
logging.info('Info: Deleting /var/tmp/rsi-' + date_arg + '.txt')
channel.send('file delete /var/tmp/rsi-' + date_arg + '.txt\n')
logging.info('Info: File deleted successfully.')
time.sleep(2)
logging.info('Info: Deleting /var/tmp/logfiles-' + date_arg + '.tgz')
channel.send('file delete /var/tmp/logfiles-' + date_arg + '.tgz\n')
logging.info('Info: File deleted successfully.')
time.sleep(2)
logging.info('Info: Deleting /var/tmp/active-config-' + date_arg + '.txt')
channel.send('file delete /var/tmp/active-config-' + date_arg + '.txt\n')
logging.info('Info: File deleted successfully.')
resp = channel.recv(9999)
output = resp.decode().split(',')
# print(''.join(output)) #commented out so its not shown on the console (debug)
time.sleep(1)
ssh.close()
time.sleep(1)
shutil.make_archive('njs-package_' + varIP + '_' + date_arg, 'zip', dir_root + '-' + varIP + '-' + date_arg)
shutil.rmtree(dir_root + '-' + varIP + '-' + date_arg, ignore_errors=True)
print("\n")
print("Finished!")
pathdisplay = Path(__file__).parent.absolute()
print("The file has been downloaded to: " + str(pathdisplay))
elif varPath == "R":
print("\n")
print("Step 4/5 and 5/5: Skipping this steps because you selected that the file should remain on the box.")
logging.info('Step 4/5 and 5/5: Skipping this steps because you selected that the file should remain on the box.')
print("The package can be found at /var/tmp/")
logging.info('The package can be found at /var/tmp/')
print("\n")
print("Finished!")
else:
print("\n")
print("Error: Something went horribly wrong for reasons we do not know yet. Exiting...")
logging.info('Error: Something went horribly wrong for reasons we do not know yet. Exiting...')
def mass_command():
varMassFile = input("Please enter the Path and Filename of your IP List (txt-file with one IP per line): ")
with open(varMassFile, 'r') as f:
devices = [line.strip() for line in f]
for switch in devices:
port_arg = 22
dev = Device(host=switch, user=varUser, password=varPassword, gather_facts=True)
dev.open()
dev.timeout = 60
facts = dev.facts
print(switch + " is currently running: " + dev.facts['version'])
print("\n")
def burstsize():
mbpslimit = input("What's the Speed that you want to limit the Port to in Mbps?")
bpslimit = int(mbpslimit)*int(1000000)
onems = int(bpslimit)/int(1000)
fivems = int(onems)*int(5)
burstsize = int(fivems)/int(8)
print("")
print("To limit your Port to" ,mbpslimit + "Mbps you probably need to use a burst size of" ,int(burstsize))
print("This results in the following Config:")
print("")
print("set firewall family inet filter",mbpslimit + "M-Ratelimit term default then policer" ,mbpslimit + "M-Policer")
print("set firewall policer",mbpslimit + "M-Policer if-exceeding bandwidth-limit",mbpslimit + "m")
print("set firewall policer",mbpslimit + "M-Policer if-exceeding burst-size-limit",int(burstsize))
print("set firewall policer",mbpslimit + "M-Policer then discard")
print("")
def find_config():
port_arg = 22
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(varIP, username=varUser, password=varPassword, port=port_arg)
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
channel = ssh.invoke_shell()
stdin, stdout, stderr = ssh.exec_command(
'show configuration | display set | no-more')
exit_status = stdout.channel.recv_exit_status()
stdout = stdout.readlines()
remote_char_01 = str(stdout).replace('\\n','').replace('\'','').replace(']','').replace('[','')
# mylist = []
# mylist.append(remote_char_01)
# print(mylist)
# print(len(mylist))
# print(str(stdout))
print(f'List of Items in CSV ={str(stdout).split(",")}')
ssh.close()
print("\n")
print("\n")
except paramiko.AuthenticationException as error:
print("Error: The Credentials did not work or ssh / netconf is not enabled!")
print("\n")
print("\n")
def main():
global varVersion
varVersion = "2020.09.09.04"
loop_condition_main = True
loop_condition_routing = True
print(
" _ _ _ _ ___ _ _ _____ _ \n | \\| |___| |_ __| |_ _ _ ___ _ _ | \\ __ _(_) |_ _ |_ _|__ ___| |___\n | .` / -_) _/ _| \' \\| \'_/ _ \\ \' \\ | |) / _` | | | || | | |/ _ \\/ _ \\ (_-<\n |_|\\_\\___|\\__\\__|_||_|_| \\___/_||_| |___/\\__,_|_|_|\\_, | |_|\\___/\\___/_/__/\n |__/ ")
print(
" ____\n / . .\\\n \\ ---<\n \\ /\n __________/ /\n -=:___________/ Script-Version: " + varVersion + " \n")
login_details()
while loop_condition_main:
print("#######################################")
print("# Main Menu #")
print("#######################################")
print("Current Device: " + varIP)
print("Current User: " + varUser)
print(" ")
print("[1] - Change Login Details / Switch Device")
print("[2] - Collect Logs and RSI (Support-Information)")
print("[3] - Routing-Engine Menu")
print("[4] - Spanning-Tree Menu")
print("[5] - Routing Menu")
print("[6] - Script Menu")
print("[8] - Version Mass-Fetch")
print("[9] - Exit the Tool")
print(" ")
loop_condition_routing = True
loop_condition_engine = True
loop_condition_spanning = True
loop_condition_command = True
main_input = int(input("Waiting for user input>> "))
print("#######################################")
print("\n")
if main_input == 9:
print("This tool was coded for you by Christian Scholz (@chsjuniper).")
print("This tool is able to run in IPv6 only environments!")
loop_condition_main = False
break
else:
if main_input == 1:
login_details()
elif main_input == 2:
njsupport()
elif main_input == 3:
while loop_condition_engine:
print("#######################################")
print("# Routing Engine Menu #")
print("#######################################")
print("Current Device: " + varIP)
print("Current User: " + varUser)
print(" ")
print("[1] - Check CPU usage")
print("[2] - Get device infos")
print("[3] - Get top process informations")
print("[4] - Back")
print(" ")
main_input = int(input("Waiting for user input>> "))
print("#######################################")
print("\n")
if main_input == 4:
loop_condition_engine = False
break
else:
if main_input == 1:
chassis_re()
elif main_input == 2:
get_device()
elif main_input == 3:
get_processes()
elif main_input == 4:
while loop_condition_spanning:
print("#######################################")
print("# Spanning Tree Menu #")
print("#######################################")
print("Current Device: " + varIP)
print("Current User: " + varUser)
print(" ")
print("[1] - Check interface descriptions")
print("[2] - Check blocked interfaces")
print("[3] - Unblock interfaces")
print("[4] - Back")
print(" ")
main_input = int(input("Waiting for user input>> "))
print("#######################################")
print("\n")
if main_input == 4:
loop_condition_spanning = False
break
else:
if main_input == 1:
if_descr()
elif main_input == 2:
spanning_block()
elif main_input == 3:
spanning_unblock()
elif main_input == 5:
while loop_condition_routing:
print("#######################################")
print("# Routing Menu #")
print("#######################################")
print("Current Device: " + varIP)
print("Current User: " + varUser)
print(" ")
print("[1] - Check BGP-Routes")
print("[2] - Check OSPF-Neighbors")
print("[3] - BGP Advertisement checker")
print("[4] - Back")
print(" ")
main_input = int(input("Waiting for user input>> "))
print("#######################################")
print("\n")
if main_input == 4:
loop_condition_routing = False
break
else:
if main_input == 1:
bgp_summary()
elif main_input == 2:
ospf_neighbors()
elif main_input == 3:
bgp_adv()
elif main_input == 6:
while loop_condition_command:
print("#######################################")
print("# Script Menu #")
print("#######################################")
print("Current Device: " + varIP)
print("Current User: " + varUser)
print(" ")
print("[1] - Enable netconf")
print("[2] - Disable netconf")
print("[3] - Create VLAN")
print("[4] - Find String in config")
print("[5] - Burstsize calculator (Port-Shaping)")
print("[6] - Back")
print(" ")
main_input = int(input("Waiting for user input>> "))
print("#######################################")
print("\n")
if main_input == 6:
loop_condition_command = False
break
else:
if main_input == 1:
enable_netconf()
elif main_input == 2:
disable_netconf()
elif main_input == 3:
set_vlan()
elif main_input == 4:
find_config()
elif main_input == 5:
burstsize()
elif main_input == 7:
print(" Do you always press numbers you are not supposed to? ;) ")
elif main_input == 8:
mass_command()
if __name__ == "__main__":
main()