33from networkapi .equipamento .models import EquipamentoAcesso
44from networkapi .plugins .base import BasePlugin
55import logging
6+ from networkapi .system .facade import get_value
7+ import paramiko
8+ import requests , json , os
9+ from django .db .utils import DatabaseError
10+ from networkapi .system .exceptions import VariableDoesNotExistException
11+
612
713
814log = logging .getLogger (__name__ )
915
1016class GenericNetconf (BasePlugin ):
11- session_manager : manager = None
17+ session_manager = None
18+ alternative_variable_base_path_list = ['path_to_tftpboot' ]
19+ alternative_static_base_path_list = ['/mnt/scripts/tftpboot/' ]
20+
1221
1322 def __try_lock (self ):
1423 """
@@ -29,6 +38,8 @@ def connect(self):
2938
3039 log .info ("Connection to equipment method started" )
3140
41+
42+
3243 ### If equipment access was not provided, then search the access ###
3344 if self .equipment_access is None :
3445 try :
@@ -42,23 +53,40 @@ def connect(self):
4253 raise exceptions .InvalidEquipmentAccessException ()
4354 ### End block ###
4455
45- ### Getting device access data ###
46- device = self .equipment_access .fqdn
47- username = self .equipment_access .user
48- password = self .equipment_access .password
49- ### End block ###
50-
51- ### Runs connection ###
56+ #Bypassing connection
5257 try :
53- log .info ("Starting connection to '%s' using NCClient..." % device )
54- self .session_manager = manager .connect (
55- host = device ,
56- port = self .connection_port ,
57- username = username ,
58- password = password ,
59- hostkey_verify = False
60- )
61- log .info ('Connection succesfully...' )
58+ pass
59+
60+ # ### Getting device access data ###
61+ # device = self.equipment_access.fqdn
62+ # username = self.equipment_access.user
63+ # password = self.equipment_access.password
64+ # ### End block ###
65+
66+ # ### Runs connection ###
67+ # try:
68+ # log.info("Starting connection to '%s' using NCClient..." % device)
69+ # # transport = paramiko.Transport((device, 22))
70+ # # transport.get_security_options().kex = (
71+ # # 'curve25519-sha256',
72+ # # 'diffie-hellman-group14-sha1',
73+ # # 'diffie-hellman-group-exchange-sha256',
74+ # # )
75+ # # transport.get_security_options().ciphers = (
76+ # # 'aes128-ctr', 'aes256-ctr'
77+ # # )
78+
79+ # self.session_manager = manager.connect(
80+ # host = device,
81+ # port = self.connect_port,
82+ # username = username,
83+ # password = password,
84+ # # hostkey_verify = False,
85+ # # allow_agent=False,
86+ # # look_for_keys=False,
87+
88+ # )
89+ # log.info('Connection succesfully...')
6290
6391 ### Exception handler
6492 except IOError , e :
@@ -93,6 +121,61 @@ def ensure_privilege_level(self, privilege_level=None):
93121 """
94122 return True
95123
124+ def check_configuration_has_content (self , command , file_path ):
125+ pass
126+
127+ def check_configuration_file_exists (self , file_path ):
128+
129+ """
130+ This function try to find and build (if necessary) the configuration file path. The priorities are:
131+ (1) build the full path from system variable base and relative file path ('file_path'); or
132+ (2) build the full path from static variable base and relative file path ('file_path'); or
133+ (3) return the relative path it self ('file_path')
134+
135+ :param str file_path: Relative path, examples:
136+ 'networkapi/plugins/Juniper/JUNOS/samples/sample_command.txt' or
137+ 'networkapi/generated_config/interface/int-d_24823_config_ROR9BX3ATQG93TALJAMO2G'
138+
139+ :return: Return a valid configuration file path string. Ex.:
140+ 'networkapi/plugins/Juniper/JUNOS/samples/sample_command.txt' or
141+ '/mnt/scripts/tftpboot/networkapi/generated_config/interface/int-d_24823_config_ROR9BX3ATQG93TALJAMO2G'
142+ """
143+
144+ log .info ("Checking configuration file exist: {}" .format (file_path ))
145+
146+ # Check in system variables
147+ for variable in self .alternative_variable_base_path_list :
148+ try :
149+ base_path = get_value (variable )
150+ if base_path != "" :
151+ result_path = base_path + file_path
152+ if os .path .isfile (result_path ):
153+ log .info ("Configuration file {} was found by system variable {}!" .format (result_path , variable ))
154+ return result_path
155+ except (DatabaseError , VariableDoesNotExistException ):
156+ # DatabaseError means that variable table do not exist
157+ pass
158+ except Exception as e :
159+ log .warning ("Unknown error while calling networkapi.system.facade.get_value({}): {} {} " .format (
160+ variable , e .__class__ , e ))
161+
162+ # Check possible static variables
163+ for static_path in self .alternative_static_base_path_list :
164+ result_path = static_path + file_path
165+ if os .path .isfile (result_path ):
166+ log .info ("Configuration file {} was found by static variable {}!" .format (result_path , static_path ))
167+ return result_path
168+
169+ # Check if relative path is valid (for dev tests)
170+ if os .path .isfile (file_path ):
171+ log .info ("Configuration file {} was found by relative path" .format (file_path ))
172+ return file_path
173+
174+ message = "An error occurred while finding configuration file."
175+ log .error ("{} Could not find in: relative path ('{}'), system variables ({}) or static paths ({})" .format (
176+ message , file_path , self .alternative_variable_base_path_list , self .alternative_static_base_path_list ))
177+ raise exceptions .APIException (message )
178+
96179 def copyScriptFileToConfig (self , filename , use_vrf = '' , destination = '' ):
97180 """
98181 Receives the file path (usually in /mnt/scripts/tftpboot/networkapi/generated_config/interface/)
@@ -120,9 +203,9 @@ def copyScriptFileToConfig(self, filename, use_vrf='', destination=''):
120203 command = command_file .read ()
121204
122205 # Check if Configuration is not empty and raises exception if not contain
123- self .check_configuration_has_content (command = command , file_path = file_path )
206+ # self.check_configuration_has_content(command=command, file_path=file_path)
124207
125- log .info ("Load configuration from file {} successfully" .format (file_path ))
208+ # log.info("Load configuration from file {} successfully".format(file_path))
126209
127210 return self .exec_command (command = command )
128211
@@ -141,8 +224,22 @@ def exec_command(self, command, success_regex='', invalid_regex=None, error_rege
141224
142225 try :
143226 self .__try_lock () # Do nothing, will be executed by the locked method of ncclient
144- with self .session_manager .locked (target = 'running' ):
145- self .session_manager .edit_config (target = 'running' , config = command )
227+ # with self.session_manager.locked(target='running'):
228+ # self.session_manager.edit_config(target='running', config=command)
229+
230+ response = requests .post (
231+ url = "http://localhost:5000/deploy" ,
232+ headers = {"Content-type" : "application/json" },
233+ data = json .dumps ({
234+ "address" : self .equipment_access .fqdn ,
235+ "username" : self .equipment_access .user ,
236+ "password" : self .equipment_access .password ,
237+ "configuration" : command
238+ })
239+ )
240+
241+ if response .status_code != 200 :
242+ raise Exception
146243
147244 result_message = "Configuration was executed successfully on {}." .format (self .equipment_access .fqdn )
148245 log .info (result_message )
@@ -161,20 +258,21 @@ def close(self):
161258
162259 :returns: True if success or raise an exception on any error
163260 """
164- log .info ("Close connection started..." )
165- try :
166- if self .session_manager :
167- self .session_manager .close_session ()
168- log .info ('Connection closed successfully.' )
169- return True
170-
171- else :
172- raise Exception ("session_manager is None." )
173-
174- except Exception as e :
175- message = "Error while calling close session method on equipment %s" % self .equipment_access .fqdn
176- log .error (message )
177- log .error (e )
178-
179- raise exceptions .APIException (message )
261+ # log.info("Close connection started...")
262+ pass
263+ # try:
264+ # if self.session_manager:
265+ # self.session_manager.close_session()
266+ # log.info('Connection closed successfully.')
267+ # return True
268+
269+ # else:
270+ # raise Exception("session_manager is None.")
271+
272+ # except Exception as e:
273+ # message = "Error while calling close session method on equipment %s" % self.equipment_access.fqdn
274+ # log.error(message)
275+ # log.error(e)
276+
277+ # raise exceptions.APIException(message)
180278
0 commit comments