From e85961aedc93e6463712ddf7c6ffdcad16f5f516 Mon Sep 17 00:00:00 2001 From: ciscodatacenter Date: Tue, 17 Oct 2017 15:43:15 +0530 Subject: [PATCH] TLS NXAPI Script and NDBActivator3.0_I5_Plus --- nexusdatabroker/NDBActivator3.0_I5_Plus.py | 495 ++++++++ .../TLSNXAPITool1.0/.OpenSSL.py.swp | Bin 0 -> 20480 bytes .../TLSNXAPITool1.0/.TLSScript.py.swp | Bin 0 -> 20480 bytes nexusdatabroker/TLSNXAPITool1.0/OpenSSL.py | 1078 +++++++++++++++++ .../TLSNXAPITool1.0/TLSNXAPITool.py | 122 ++ nexusdatabroker/TLSNXAPITool1.0/TLSScript.py | 296 +++++ .../Utilities/Input/inputfile.yaml | 55 + .../TLSNXAPITool1.0/Utilities/Log/Logfile.log | 0 8 files changed, 2046 insertions(+) create mode 100644 nexusdatabroker/NDBActivator3.0_I5_Plus.py create mode 100644 nexusdatabroker/TLSNXAPITool1.0/.OpenSSL.py.swp create mode 100644 nexusdatabroker/TLSNXAPITool1.0/.TLSScript.py.swp create mode 100755 nexusdatabroker/TLSNXAPITool1.0/OpenSSL.py create mode 100644 nexusdatabroker/TLSNXAPITool1.0/TLSNXAPITool.py create mode 100755 nexusdatabroker/TLSNXAPITool1.0/TLSScript.py create mode 100755 nexusdatabroker/TLSNXAPITool1.0/Utilities/Input/inputfile.yaml create mode 100644 nexusdatabroker/TLSNXAPITool1.0/Utilities/Log/Logfile.log diff --git a/nexusdatabroker/NDBActivator3.0_I5_Plus.py b/nexusdatabroker/NDBActivator3.0_I5_Plus.py new file mode 100644 index 00000000..16915cb5 --- /dev/null +++ b/nexusdatabroker/NDBActivator3.0_I5_Plus.py @@ -0,0 +1,495 @@ +# -*- coding: utf-8 -*- +from cli import * +import json +import os +import sys +import subprocess +import optparse +import logging +import time +import pdb +import zipfile +import re +import fileinput +import signal + + +def test_request(arg=None): + try: + cli("guestshell run pwd") + return arg + except: + time.sleep(11) + return arg + + +class Timeout(): + """Timeout class using ALARM signal.""" + class Timeout(Exception): + pass + + def __init__(self, sec): + self.sec = sec + + def __enter__(self): + signal.signal(signal.SIGALRM, self.raise_timeout) + signal.alarm(self.sec) + + def __exit__(self, *args): + signal.alarm(0) # disable alarm + + def raise_timeout(self, *args): + raise Timeout.Timeout() + + +if '--quiet' in sys.argv: + logger = logging.getLogger(__name__) + logger.setLevel(logging.DEBUG) + con_log_handler = logging.StreamHandler() + file_log_handler = logging.FileHandler("/bootflash/ndb_deploy.log") + file_log_handler.setLevel(logging.DEBUG) + con_log_handler.setLevel(logging.DEBUG) + formatter = logging.Formatter( + '%(asctime)s - %(name)s - %(levelname)s - %(message)s') + file_log_handler.setFormatter(formatter) + logger.addHandler(file_log_handler) +else: + logger = logging.getLogger(__name__) + logger.setLevel(logging.DEBUG) + con_log_handler = logging.StreamHandler() + file_log_handler = logging.FileHandler("/bootflash/ndb_deploy.log") + file_log_handler.setLevel(logging.DEBUG) + con_log_handler.setLevel(logging.DEBUG) + formatter = logging.Formatter( + '%(asctime)s - %(name)s - %(levelname)s - %(message)s') + file_log_handler.setFormatter(formatter) + con_log_handler.setFormatter(formatter) + logger.addHandler(file_log_handler) + logger.addHandler(con_log_handler) + + +def guestShell(path): + # Verify command line arguments + forceFlag = 0 + quiteFlag = 0 + if len(sys.argv) == 4: + zipFilePath = sys.argv[-1] + + elif len(sys.argv) == 5 and '--force' in sys.argv[-1]: + zipFilePath = sys.argv[-2] + forceFlag = 1 + + elif len(sys.argv) == 5 and '--quiet' in sys.argv[-1]: + zipFilePath = sys.argv[-2] + quiteFlag = 1 + + elif len(sys.argv) == 6: + zipFilePath = sys.argv[-3] + quiteFlag = 1 + + else: + logger.error("Please provide valid arguments") + sys.exit(0) + + # Verify zip file path + if not os.path.exists(zipFilePath): + logger.error("Please provide valid zip file path") + sys.exit(0) + + # Remove if already xnc exists + if os.path.exists('/volatile/xnc'): + os.system('rm -rf /volatile/xnc') + + # Unzip and verify xnc is exists + zip_ref = zipfile.ZipFile(zipFilePath, 'r') + zip_ref.extractall('/volatile') + zip_ref.close() + xncpath = '/volatile/xnc' + if not os.path.exists(xncpath): + logger.error("Zip file doesn't contain xnc. Provide valid zip file") + sys.exit(0) + + if not os.path.exists('/volatile/xnc/runxnc.sh'): + logger.error("xnc doesn't contain runxnc.sh Provide valid zip file") + sys.exit(0) + + if not os.path.exists('/volatile/xnc/start.sh'): + logger.error("xnc doesn't contain start.sh Provide valid zip file") + sys.exit(0) + + if not os.path.exists('/volatile/xnc/version.properties'): + logger.error( + "xnc doesn't contain version.properties. Provide valid zip file") + sys.exit(0) + + if not os.path.exists('/volatile/xnc/runxnc.cmd'): + logger.error("xnc doesn't contain runxnc.cmd Provide valid zip file") + sys.exit(0) + + if not os.path.isdir('/volatile/xnc/embedded'): + logger.error("xnc doesn't contain embedded. Provide valid zip file") + sys.exit(0) + + if not os.path.isdir('/volatile/xnc/lib'): + logger.error("xnc doesn't contain lib. Provide valid zip file") + sys.exit(0) + + if not os.path.isdir('/volatile/xnc/bin'): + logger.error("xnc doesn't contain bin. Provide valid zip file") + sys.exit(0) + + if not os.path.isdir('/volatile/xnc/configuration'): + logger.error( + "xnc doesn't contain configuration. Provide valid zip file") + sys.exit(0) + + if not os.path.isdir('/volatile/xnc/etc'): + logger.error("xnc doesn't contain etc. Provide valid zip file") + sys.exit(0) + + if not os.path.isdir('/volatile/xnc/plugins'): + logger.error("xnc doesn't contain plugins. Provide valid zip file") + sys.exit(0) + + # Find user, role and priveleges + puser = subprocess.check_output("whoami", shell=True) + try: + whoamicliout = cli( + "show run | i " + + puser.split("\n")[0] + + " | inc role") + whoami = whoamicliout.split(" ")[1] + userRole = whoamicliout.split(" ")[-1].split("\n")[0] + userprivcliout = cli("show privilege") + privFlag = 0 + for line in userprivcliout.split("\n"): + line = line.strip() + if "privilege level" in line: + userpriv = line.split(":")[1] + privFlag = 1 + userRole = userRole.strip() + except: + logger.error("Something went wrong while finding user/role/privelege") + sys.exit(0) + + # Verify user role + if userRole != 'network-admin': + logger.error("User role is not network-admin") + sys.exit(0) + + # Verify user privelege + if privFlag == 1: + if int(userpriv) != 15: + logger.error("User privelege is not 15") + sys.exit(0) + else: + logger.error("User privelege is not 15") + sys.exit(0) + + FirstNxosVersion = 0 + # Find NXOS version + try: + nxosFlag = 0 + nxosVersionOut = cli("show version | inc NXOS | inc version") + for line in nxosVersionOut.split("\n"): + if 'inc' not in line: + if 'I5' in line or 'I6' in line or 'I7' in line: + nxosFlag = 1 + + if 'I5(1)' in line: + FirstNxosVersion = 1 + + if nxosFlag != 1: + logger.error("Device does not contain I5/I6/I7 nxos") + sys.exit(0) + except: + logger.error("Something went wrong while finding NXOS version") + sys.exit(0) + + # Verify guestshell commands are working + if FirstNxosVersion != 1: + try: + with Timeout(10): + test_request() + + except Timeout.Timeout: + logger.error("Please login to the guestshell atleast once") + sys.exit(0) + + try: + memoryCliOuput = cli("show version | inc memory") + for line in memoryCliOuput.split("\n"): + line = line.strip() + if 'inc' not in line: + if 'memory' in line: + nxosMemory = line.split(" ")[-4] + + # Verify memory in the device + try: + if int(nxosMemory) < 8155984: + logger.error("The device does not have sufficient memory.") + sys.exit(0) + except: + logger.info("Error while verifyng NXOS memory") + sys.exit(0) + except: + logger.error("Something went wrong while verifying NXOS memory") + sys.exit(0) + + # Platform Verification + devicePlatformList = [] + cliout = cli('sh ver | inc ignore-case Chassis') + platform_flag = 0 + for line in cliout.split("\n"): + line = line.strip() + if ("Chassis" in line or 'chassis' in line) and 'cisco' in line: + if len(line.split(" ")) >= 4: + platform = line.split(" ")[2] + platform_flag = 1 + else: + platform = line.split(" ")[1] + platform_flag = 1 + if platform_flag == 1: + platform = int(re.search(r'\d+', platform).group()) + if str(platform)[0] == '9': + logger.info("Verified device platform version") + pass + else: + verTempFlag = 0 + for platformVer in devicePlatformList: + if str(platform) in platformVer: + verTempFlag = 1 + + if verTempFlag == 1: + logger.info("Verified device platform version") + pass + else: + logger.error("Device platform version is not N9K") + sys.exit(0) + else: + logger.error("Error while greping platform version") + sys.exit(0) + + # Resizing the guestshell resources + try: + statusFlag = 0 + try: + output = cli("show guestshell detail | inc Activated") + for line in output.split("\n"): + if 'Activated' in line and 'inc' not in line: + statusFlag = 1 + except: + statusFlag = 0 + except: + logger.error("Something went wrong while verifying guestshell details") + sys.exit(0) + + try: + if statusFlag == 0: + for en in range(10): + enableFlag = 0 + try: + enableout = cli("guestshell enable") + for line in enableout.split("\n"): + line = line.strip() + if 'currently activating' in line: + enableFlag = 1 + if enableFlag == 1: + time.sleep(5) + else: + break + except: + time.sleep(5) + + tempflag = 0 + for st in range(200): + if tempflag == 1: + break + try: + output = cli("show guestshell detail | inc Activated") + for line in output.split("\n"): + if 'Activated' in line and 'inc' not in line: + tempflag += 1 + break + except: + time.sleep(1) + + if tempflag == 1: + logger.info("Guestshell is enabled") + else: + logger.error("Error while enabling guestshell") + sys.exit(0) + else: + logger.info("Guestshell is enabled") + + except: + logger.error("Something went wrong while enabling guestshell") + sys.exit(0) + + # Verifying NDB is already installed + systemdPath = '/isan/vdc_1/virtual-instance/guestshell+/rootfs/usr/lib/systemd/system/ndb.service' + if os.path.exists(systemdPath): + if forceFlag == 1: + pass + else: + logger.info("NDB application is already installed.") + sys.exit(0) + else: + pass + + # Verify disk space insdie volatile directory + + try: + diskFreeSpace = cli( + "guestshell run df -m /volatile | awk '{print $4}' | grep '[0-9]'") + diskFreeSpace = int(diskFreeSpace.strip()) + requiredSpace = 600 + if diskFreeSpace <= requiredSpace: + logger.error( + "Please make sure sufficient disk space is available inside the /volatile/ folder.") + sys.exit(0) + except: + logger.error( + "Something went wrong while checking disk dpace inside volatile") + sys.exit(0) + + try: + cli("guestshell resize cpu 5") + except: + logger.error("Please provide valid CPU reservation") + sys.exit(0) + try: + cli("guestshell resize memory 1536") + except: + logger.error("Please provide valid Memory reservation") + sys.exit(0) + try: + cli("guestshell resize rootfs 1536") + except: + logger.error("Please provide valid Disk reservation") + sys.exit(0) + + try: + cli("guestshell reboot") + tempflag = 0 + for st in range(200): + if tempflag == 1: + break + try: + output = cli("show guestshell detail | inc Activated") + for line in output.split("\n"): + if 'Activated' in line and 'inc' not in line: + tempflag += 1 + break + except: + time.sleep(1) + except: + logger.error("Something went wrong while rebooting guestshell") + sys.exit(0) + + if tempflag == 1: + logger.info("Resized the guestshell resources") + + # Place the xnc folder into the guestshell home directory + if FirstNxosVersion != 1: + try: + makePath = '/volatile/xnc/embedded/i5/make-systemctl-env.sh' + for line in fileinput.input(makePath, inplace=1): + print line.replace("guestshell", whoami) + + ndbPath = '/volatile/xnc/embedded/i5/ndb' + for line in fileinput.input(ndbPath, inplace=1): + print line.replace("guestshell", whoami) + + servicePath = '/volatile/xnc/embedded/i5/ndb.service' + for line in fileinput.input(servicePath, inplace=1): + print line.replace("guestshell", whoami) + + runxncPath = '/volatile/xnc/embedded/i5/runxnc.sh' + for line in fileinput.input(runxncPath, inplace=1): + print line.replace("guestshell", whoami) + + except: + logger.error( + "Something went wrong while placing xnc into guestshell home directory") + sys.exit(0) + + if FirstNxosVersion == 1: + guestpath = "/home/guestshell" + else: + guestpath = "/home/" + whoami + + try: + diskFreeSpaceInside = cli( + "guestshell run df -m " + + guestpath + + " | awk '{print $4}' | grep '[0-9]'") + diskFreeSpaceInside = int(diskFreeSpaceInside.strip()) + requiredSpaceInside = 600 + if diskFreeSpaceInside <= requiredSpaceInside: + logger.error( + "Please make sure sufficient disk space is available inside the /home/guestshell/ folder.") + sys.exit(0) + except: + logger.error( + "Something went wrong while checking disk space inside /home/guestshell") + sys.exit(0) + + try: + cli("guestshell run cp -Rf " + xncpath + " " + guestpath + "/") + cli("guestshell run rm -rf " + xncpath) + cli_cmd = "guestshell run chmod -Rf 777 " + guestpath + "/xnc/" + cli(cli_cmd) + logger.info("Placed the xnc folder into the guestshell home directory") + except: + logger.error( + "Something went wrong while place xnc into guestshell home direcotry") + sys.exit(0) + + # Setting the nxapi to listen to network namespace + try: + out = cli("configure terminal ; feature nxapi") + except: + logger.error("Something went wrong while enabling NXAPI") + exit(0) + + try: + cliout = cli("configure terminal ; nxapi use-vrf management ; copy running-config startup-config") + logger.info("Kept the nxapi to listen to network namespace") + except: + if "Warning:" in cliout: + logger.info("Kept the nxapi to listen to network namespace") + else: + logger.error( + "Something went wrong while keeping nxapi to listen to network namespace") + sys.exit(0) + + try: + cli("guestshell run " + guestpath + + "/xnc/embedded/i5/make-systemctl-env.sh") + except: + logger.error( + "Something went wrong while running make-systemctl-env.sh") + sys.exit(0) + + +def main(): + cmd_args = sys.argv + path = cmd_args[-1] + guestShell(path) + +if __name__ == "__main__": + + if len(sys.argv) == 5: + if '--quiet' in sys.argv or '--force' in sys.argv: + pass + else: + logger.error("Please provide valid arguments") + + if len(sys.argv) == 6: + if '--quiet' in sys.argv and '--force' in sys.argv: + pass + else: + logger.error("Please provide valid arguments") + + main() diff --git a/nexusdatabroker/TLSNXAPITool1.0/.OpenSSL.py.swp b/nexusdatabroker/TLSNXAPITool1.0/.OpenSSL.py.swp new file mode 100644 index 0000000000000000000000000000000000000000..c90099858b703bc9ac4a254d844daa6c53fd7424 GIT binary patch literal 20480 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 literal 0 HcmV?d00001 diff --git a/nexusdatabroker/TLSNXAPITool1.0/.TLSScript.py.swp b/nexusdatabroker/TLSNXAPITool1.0/.TLSScript.py.swp new file mode 100644 index 0000000000000000000000000000000000000000..07966f524179527abd59c9b815f04e6de4493630 GIT binary patch literal 20480 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 literal 0 HcmV?d00001 diff --git a/nexusdatabroker/TLSNXAPITool1.0/OpenSSL.py b/nexusdatabroker/TLSNXAPITool1.0/OpenSSL.py new file mode 100755 index 00000000..a9b858c0 --- /dev/null +++ b/nexusdatabroker/TLSNXAPITool1.0/OpenSSL.py @@ -0,0 +1,1078 @@ +from subprocess import call, PIPE, STDOUT +import os +import time +import yaml +import pexpect +import sys +import fileinput +import paramiko +import logging +import pdb + +class Device: + def __init__(self): + self.ip_l = [] + self.cp_keypem_res = "" + self.tem_serpath = "" + self.cp_cert_speloc_res = "" + self.prov_pass = "" + self.sethttps = "" + self.cp_cert_lhser = "" + self.login_mulser = "" + self.tem_seruser = "" + self.pass_pro_res = "" + self.temp_pass = "" + self.copy_keyfile = "" + self.append_forwkey = "" + self.prov_pass_b = "" + self.device_password_list = [] + self.gen_cert_key = "" + self.log_mul_dev = 0 + self.pass_pro = "" + self.cp_cert_lhser_res = "" + self.temp_user = "" + self.temp_ip = "" + self.temp_dport = "" + self.cp_certpem_res = "" + self.copy_file = 1 + self.capem_sw_res = "" + self.server_password_list = [] + self.device_user_list = [] + self.cp_keypem = "" + self.cp_xncpem = "" + self.cp_xncpem_re = "" + self.cp_certpem = "" + self.password = "" + self.cp_ser_speloc = "" + self.default_bits_str = "" + self.gen_cert_key_result = "" + self.tem_serip = "" + self.cp_certfile = "" + self.sw_tlstrust_res = "" + self.cp_cert_speloc = "" + self.run_ndb = "" + self.default_days_str = "" + self.server_path_list = [] + self.gen_key_ca_files_result = "" + self.cp_key_lhser = "" + self.copy_keystore_res = "" + self.sw_tlstrust = "" + self.cp_trust_res = "" + self.path = "" + self.capem_sw = "" + self.server_ip_list = [] + self.cp_key_lhser_res = "" + self.cp_trust = "" + self.copy_keystore = "" + self.gen_key_ca = "" + self.server_user_list = [] + self.temp_serpass = "" + self.xncp_tlskey = "" + self.app_forwkey_e = "" + self.run_n = "" + self.ip = "" + self.user = "" + self.xncp_tlskey_res = "" + self.cp_ser_speloc_res = "" + self.device_ip_list = [] + self.device_user_list = [] + self.device_password_list = [] + self.device_port_list = [] + self.password = "" + self.server_path = "" + self.user = "" + self.path = "" + all_ips_from_yaml = [] + self.replace_ip = 0 + self.organization_name_c = "" + self.organization_name = "" + self.state_name_c = "" + self.state_name = "" + self.country_name_c = "" + self.countryname = "" + self.emailaddress_c = "" + self.email_address = "" + self.localityname_c = "" + self.locality_name = "" + self.organizationalunit_name_c = "" + self.organizational_unit_name = "" + self.commonname_c = "" + self.common_name = "" + self.ip_list = "" + self.ip1_list = "" + self.ip2_list = "" + self.ip3_list = "" + self.ip4_list = "" + self.ip5_list = "" + self.ip6_list = "" + self.ip7_list = "" + self.ip8_list = "" + self.ip9_list = "" + self.ip10_list = "" + self.all_ips_from_yaml = [] + self.ip_l1 = "" + self.ip_l2 = "" + self.ip_l3 = "" + self.ip_l4 = "" + self.ip_l5 = "" + self.ip_l6 = "" + self.ip_l7 = "" + self.ip_l8 = "" + self.ip_l9 = "" + self.ip_l10 = "" + self.append_config = 0 + self.default_md_c = "" + self.cp_xncpem_res = "" + self.organizationalunit_name_list = "" + self.localityname_list = "" + self.default_days = "" + self.default_md = "" + self.organizationname_list = "" + self.default_md_list = [] + self.state_name_list = "" + self.default_bits_c = "" + self.server_port_list = [] + self.default_bits_list = [] + self.country_name_list = "" + self.keystore_password = "" + self.default_days_c = "" + self.emailaddress_list = "" + self.default_bits = "" + self.commonname_list = "" + self.xnc_pwd = "" + self.xnc_usr = "" + def method_one(self): + try: + with open("./Utilities/TlsCerts/ca.conf", 'r') as fil_ptr: + for line in fil_ptr: + if 'default_days' in line: + self.default_days_c = line.split(" ")[-1] + self.default_days_c = self.default_days_c.strip() + if 'default_md' in line and 'digest' in line: + line1 = line.strip() + self.default_md_list = line1.split(" ") + self.default_md_list = filter(None, \ + self.default_md_list) + self.default_md_c = self.default_md_list[2] + if 'default_bits' in line and 'Size of keys' in line: + line2 = line.strip() + self.default_bits_list = line2.split(" ") + self.default_bits_list = filter(None,\ + self.default_bits_list) + self.default_bits_c = self.default_bits_list[2] + if 'commonName_default' in line: + self.commonname_list = line.split(" ")[-1] + self.commonname_c = self.commonname_list.strip() + if 'organizationName_default' in line: + self.organizationname_list = line.split(" ")[-1] + self.organization_name_c = \ + self.organizationname_list.strip() + if 'localityName_default' in line: + self.localityname_list = line.split(" ")[-1] + self.localityname_c = self.localityname_list.strip() + if 'stateOrProvinceName_default' in line: + self.state_name_list = line.split(" ")[-1] + self.state_name_c = \ + self.state_name_list.strip() + if 'countryName_default' in line: + self.country_name_list = line.split(" ")[-1] + self.country_name_c = self.country_name_list.strip() + if 'emailAddress_default' in line: + self.emailaddress_list = line.split(" ")[-1] + self.emailaddress_c = self.emailaddress_list.strip() + if 'organizationalUnitName_default' in line: + self.organizationalunit_name_list = line.split(" ")[-1] + self.organizationalunit_name_c = \ + self.organizationalunit_name_list.strip() + if 'IP.1' and '1.1.1.1' in line: + self.ip_list = line.split(" ")[-1] + self.ip_l1 = self.ip_list.strip() + self.ip_l.append(self.ip_l1) + if 'IP.2' in line: + self.ip2_list = line.split(" ")[-1] + self.ip_l2 = self.ip2_list.strip() + self.ip_l.append(self.ip_l2) + if 'IP.3' in line: + self.ip3_list = line.split(" ")[-1] + self.ip_l3 = self.ip3_list.strip() + self.ip_l.append(self.ip_l3) + if 'IP.4' in line: + self.ip4_list = line.split(" ")[-1] + self.ip_l4 = self.ip4_list.strip() + self.ip_l.append(self.ip_l4) + if 'IP.5' in line: + self.ip5_list = line.split(" ")[-1] + self.ip_l5 = self.ip5_list.strip() + self.ip_l.append(self.ip_l5) + if 'IP.6' in line: + self.ip6_list = line.split(" ")[-1] + self.ip_l6 = self.ip6_list.strip() + self.ip_l.append(self.ip_l6) + if 'IP.7' in line: + self.ip7_list = line.split(" ")[-1] + self.ip_l7 = self.ip7_list.strip() + self.ip_l.append(self.ip_l7) + if 'IP.8' in line: + self.ip8_list = line.split(" ")[-1] + self.ip_l8 = self.ip8_list.strip() + self.ip_l.append(self.ip_l8) + if 'IP.9' in line: + self.ip9_list = line.split(" ")[-1] + self.ip_l9 = self.ip9_list.strip() + self.ip_l.append(self.ip_l9) + if 'IP.10' in line: + self.ip10_list = line.split(" ")[-1] + self.ip_l10 = self.ip10_list.strip() + self.ip_l.append(self.ip_l10) + except OSError: + LOGGER.error("Failed to open configuration file") + sys.exit(0) + try: + with open(INPUTFILE, 'r') as file_ptr: + confi = yaml.load(file_ptr) + self.default_days = confi['default_days'] + self.default_md = confi['default_md'] + self.default_bits = confi['default_bits'] + self.countryname = confi['countryName'] + self.state_name = confi['stateOrProvinceName'] + self.organization_name = confi['organizationName'] + self.organizational_unit_name = confi['organizationalUnitName'] + self.common_name = confi['commonName'] + self.email_address = confi['emailAddress'] + self.locality_name = confi['localityName'] + self.keystore_password = str(confi['keystore']) + except OSError: + LOGGER.error("Failed to open input yaml file") + sys.exit(0) + def replace_method(file1, searchexp, replaceexp): + for line in fileinput.input(file1, inplace=1): + try: + if searchexp in line: + line = line.replace(searchexp, replaceexp) + LOGGER.info("Replace value - "+str(replaceexp)+\ + " in config file is success") + try: + sys.stdout.write(line) + except OSError: + LOGGER.error("Failed to replace value "+\ + +str(replaceexp)+" in config file") + except OSError: + LOGGER.error("Failed to replace values in config file") + replace_method("./Utilities/TlsCerts/ca.conf", \ + self.organization_name_c, str(self.organization_name)) + replace_method("./Utilities/TlsCerts/ca.conf", self.state_name_c, \ + str(self.state_name)) + replace_method("./Utilities/TlsCerts/ca.conf", self.country_name_c, \ + str(self.countryname)) + replace_method("./Utilities/TlsCerts/ca.conf", self.emailaddress_c, \ + str(self.email_address)) + replace_method("./Utilities/TlsCerts/ca.conf", self.localityname_c, \ + str(self.locality_name)) + replace_method("./Utilities/TlsCerts/ca.conf", \ + self.organizationalunit_name_c, str(self.organization_name)) + replace_method("./Utilities/TlsCerts/ca.conf", self.commonname_c, \ + str(self.common_name)) + replace_method("./Utilities/TlsCerts/ca.conf", self.default_md_c, \ + str(self.default_md)) + replace_method("./Utilities/TlsCerts/ca.conf", self.default_bits_c, \ + str(self.default_bits)) + self.all_ips_from_yaml = sorted(confi['IP'].keys()) + for val in self.all_ips_from_yaml: + self.device_ip_list.append(confi['IP'][val]['address']) + self.device_user_list.append(confi['IP'][val]['username']) + self.device_password_list.append(confi['IP'][val]['password']) + self.device_port_list.append(confi['IP'][val]['port']) + self.replace_ip = 0 + while self.replace_ip < len(self.device_ip_list): + replace_method("./Utilities/TlsCerts/ca.conf", \ + self.ip_l[self.replace_ip],\ + str(self.device_ip_list[self.replace_ip])) + self.replace_ip += 1 + self.default_days_str = str(self.default_days) + self.default_bits_str = str(self.default_bits) + def method_two(self): + try: + with open(INPUTFILE, 'r') as file_ptr: + confi = yaml.load(file_ptr) + self.keystore_password = str(confi['keystore']) + except OSError: + LOGGER.error("Failed to open input yaml file") + self.gen_key_ca = str("openssl req -x509 -nodes -days "+\ + self.default_days_str+"0 -newkey rsa:"+ + self.default_bits_str+" -out "+\ + "./Utilities/TlsCerts/"+\ + "mypersonalca/certs/ca.pem \ + -outform PEM -keyout ./Utilities/TlsCerts/"+\ + "mypersonalca/private/ca.key -batch") + try: + self.gen_key_ca_files_result = call(self.gen_key_ca, \ + shell=True, \ + stdout=PIPE, \ + stderr=STDOUT) + if self.gen_key_ca_files_result == 0: + LOGGER.info("Generate ca.pem and ca.key files success") + else: + LOGGER.error("Failed to Generate ca.pem and "+\ + "ca.key files -step5") + sys.exit(0) + except OSError: + LOGGER.error("Failed to Generate ca.pem and ca.key files -step4") + sys.exit(0) + self.gen_cert_key = str("openssl req -new -x509 -days "+\ + self.default_days_str+" -nodes -out "+\ + "./Utilities/TlsCerts/server.crt -keyout "+\ + "./Utilities/TlsCerts/server.key -config "+\ + "./Utilities/TlsCerts/ca.conf -batch") + try: + self.gen_cert_key_result = call(self.gen_cert_key, \ + shell=True, \ + stdout=PIPE, \ + stderr=STDOUT) + if self.gen_cert_key_result == 0: + LOGGER.info("Generate server.crt and server.key files success") + else: + LOGGER.error("Failed to Generate server.crt and server.key"+\ + " files -step5") + sys.exit(0) + except OSError: + LOGGER.error("Failed to Generate ca.pem and ca.key files -step4") + sys.exit(0) + self.ip = confi['ServerIP']['ServerIP1']['ip'] + self.user = confi['ServerIP']['ServerIP1']['user'] + self.password = confi['ServerIP']['ServerIP1']['password'] + self.path = confi['ServerIP']['ServerIP1']['path_ndb_build'] + try: + self.port = confi['ServerIP']['ServerIP1']['port'] + except KeyError: + self.port = 0 + self.server_ip_list = [] + self.server_user_list = [] + self.server_password_list = [] + self.server_path_list = [] + self.server_port_list = [] + server_list = sorted(confi['ServerIP'].keys()) + for value in server_list: + self.server_ip_list.append(confi['ServerIP']\ + [value]['ip']) + self.server_user_list.append(confi['ServerIP']\ + [value]['user']) + self.server_password_list.append(confi['ServerIP']\ + [value]['password']) + self.server_path_list.append(confi['ServerIP']\ + [value]['path_ndb_build']) + str(self.server_password_list) + try: + self.server_port_list.append(confi['ServerIP']\ + [value]['port']) + except KeyError: + self.server_port_list.append(0) + self.append_forwkey = 0 + while self.append_forwkey < len(self.server_path_list): + suffix = "/" + self.server_path = str(self.server_path_list\ + [self.append_forwkey]) + if self.server_path.endswith(suffix) == False: + try: + self.server_path = self.server_path+"/" + self.server_path_list[self.append_forwkey] \ + = str(self.server_path) + except OSError: + LOGGER.error("Failed to append forward slash"+\ + " at end to provided NDB path") + self.append_forwkey += 1 + self.app_forwkey_e = 0 + while self.app_forwkey_e < len(self.server_path_list): + suffix = "/" + self.server_path = str(self.server_path_list\ + [self.app_forwkey_e]) + if self.server_path.startswith(suffix) == False: + try: + self.server_path = "/"+self.server_path + self.server_path_list[self.app_forwkey_e] = \ + str(self.server_path) + except OSError: + LOGGER.error("Failed to append forward slash"+\ + " at start to provided NDB path") + self.app_forwkey_e += 1 + self.append_config = 0 + while self.append_config < len(self.server_path_list): + suffix = "configuration"+"/" + self.server_path = str(self.server_path_list\ + [self.append_config]) + if self.server_path.endswith(suffix) == False: + try: + self.server_path = self.server_path+"configuration"+"/" + self.server_path_list[self.append_config] \ + = str(self.server_path) + except OSError: + LOGGER.error("Failed to append configuration"+\ + " string to provided NDB path") + self.append_config += 1 + self.ip = self.server_ip_list[0] + self.user = self.server_user_list[0] + self.password = self.server_password_list[0] + self.path = self.server_path_list[0] + self.port = self.server_port_list[0] + if self.port != 0: + try: + ssh = paramiko.SSHClient() + server = self.ip + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + ssh.connect(server, port=self.port, username=self.user, password=self.password) + sftp = ssh.open_sftp() + localpath = './Utilities/TlsCerts/server.crt' + remotepath = '/root/xnc/configuration/server.crt' + sftp.put(localpath, remotepath) + local = './Utilities/TlsCerts/server.key' + remote = '/root/xnc/configuration/server.key' + sftp.put(local, remote) + sftp.close() + except: + LOGGER.error("Error while ssh into the server") + sys.exit(0) + else: + try: + ssh = paramiko.SSHClient() + server = self.ip + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + ssh.connect(server, username=self.user, password=self.password) + sftp = ssh.open_sftp() + localpath = './Utilities/TlsCerts/server.crt' + remotepath = self.path+'server.crt' + sftp.put(localpath, remotepath) + local = './Utilities/TlsCerts/server.key' + remote = self.path+'server.key' + sftp.put(local, remote) + sftp.close() + except: + LOGGER.error("Error while ssh into the server") + exit(0) + """ + if self.copy_file == 1: + if self.port != 0: + try: + ssh = paramiko.SSHClient() + server = self.ip + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + ssh.connect(server, port=self.port, username=self.user, password=self.password) + sftp = ssh.open_sftp() + localpath = './Utilities/TlsCerts/server.key' + remotepath = '/root/xnc/server.key' + sftp.put(localpath, remotepath) + sftp.close() + ssh.close() + except paramiko.SSHException: + LOGGER.error("Error while ssh into the device5") + else: + pass + else: + self.cp_ser_speloc = "cp -r ./Utilities/TlsCerts/server.key "+\ + self.path + self.cp_ser_speloc_res = call(str(self.cp_ser_speloc), shell=True) + self.cp_cert_speloc = "cp -r ./Utilities/TlsCerts/server.crt "+\ + self.path + self.cp_cert_speloc_res = call(str(self.cp_cert_speloc), \ + shell=True) + """ + while(self.log_mul_dev < len(self.device_ip_list)): + self.temp_ip = self.device_ip_list[self.log_mul_dev] + self.temp_user = self.device_user_list[self.log_mul_dev] + self.temp_pass = self.device_password_list[self.log_mul_dev] + self.temp_dport = self.device_port_list[self.log_mul_dev] + child = pexpect.spawn('telnet '+ self.temp_ip) + time.sleep(3) + try: + child.expect('login: ') + except pexpect.ExceptionPexpect: + LOGGER.error("Device "+str(self.temp_ip)+\ + " Device is not reachable") + sys.exit(0) + child.sendline(self.temp_user) + time.sleep(3) + try: + child.expect('assword: ') + except pexpect.ExceptionPexpect: + LOGGER.error("Device "+str(self.temp_ip)+\ + " Login incorrect Provided User name is not correct") + sys.exit(0) + child.sendline(self.temp_pass) + time.sleep(3) + try: + child.expect("#") + LOGGER.info("Device "+str(self.temp_ip)+\ + " Login success") + except pexpect.ExceptionPexpect: + LOGGER.error("Device "+str(self.temp_ip)+\ + " Login incorrect Provided Password is not correct") + sys.exit(0) + child.sendline("configure terminal") + try: + child.expect("#") + except pexpect.ExceptionPexpect: + LOGGER.error("Device "+str(self.temp_ip)+\ + " - Unable to configure in device using configuration "+\ + "terminal command") + child.sendline("feature nxapi") + try: + child.expect("#") + except pexpect.ExceptionPexpect: + LOGGER.error("Device "+str(self.temp_ip)+\ + " - Unable to configure feature "+\ + "nxapi command in device") + #pdb.set_trace() + child.sendline("feature sftp-server") + try: + child.expect("#") + except pexpect.ExceptionPexpect: + LOGGER.error("Device "+str(self.temp_ip)+\ + " - Unable to configure feature "+\ + "sftp-server command in device") + self.sethttps = str("nxapi https port "+str(self.temp_dport)) + child.sendline(self.sethttps) + try: + child.expect("#") + except pexpect.ExceptionPexpect: + LOGGER.error("Device "+str(self.temp_ip)+\ + " - Unable to set https port "+\ + "with provided value in device") + try: + child.logfile = open("./Utilities/TlsCerts/temp/temp.log", "w") + except OSError: + LOGGER.error("Failed to open temporary Log file") + child.sendline("dir bootflash:server.key") + try: + with open("./Utilities/TlsCerts/temp/temp.log", "r") as fp: + for line in fp: + if "server.key" in line: + child.sendline("delete bootflash:server.key") + child.expect("[y]") + child.sendline("y") + break + except OSError: + LOGGER.error("Failed to open temporary Log file") + child.sendline("dir bootflash:server.crt") + try: + with open("./Utilities/TlsCerts/temp/temp.log", "r") as fp1: + for line1 in fp1: + if "server.crt" in line1: + child.sendline("delete bootflash:server.crt") + child.expect("[y]") + child.sendline("y") + break + except OSError: + LOGGER.error("Failed to open temporary Log file") + """ + if self.port != 0: + ssh = paramiko.SSHClient() + server = self.temp_ip + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + try: + ssh.connect(server, username=self.temp_user, \ + password=self.temp_pass) + sftp = ssh.open_sftp() + localpath = './Utilities/TlsCerts/server.key' + remotepath = 'server.key' + sftp.put(localpath, remotepath) + except paramiko.SSHException: + LOGGER.error("Error while ssh into the device1") + sys.exit(0) + else: + ssh = paramiko.SSHClient() + server = self.temp_ip + #try: + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + ssh.connect(server, username=self.temp_user, \ + password=self.temp_pass) + sftp = ssh.open_sftp() + localpath = './Utilities/TlsCerts/server.key' + remotepath = 'server.key' + sftp.put(localpath, remotepath) + #except paramiko.SSHException: + # LOGGER.error("Error while ssh into the device2") + # sys.exit(0) + if self.port != 0: + try: + time.sleep(10) + localpath = './Utilities/TlsCerts/server.crt' + remotepath = 'server.crt' + sftp.put(localpath, remotepath) + sftp.close() + ssh.close() + except paramiko.SSHException: + LOGGER.error("Error while ssh into the device") + sys.exit(0) + else: + try: + localpath = './Utilities/TlsCerts/server.crt' + remotepath = 'server.crt' + sftp.put(localpath, remotepath) + sftp.close() + ssh.close() + except paramiko.SSHException: + pass + """ + self.copy_keyfile = str("copy scp://"+self.user+'@'+\ + self.ip+self.path+"server.key "+ + "bootflash:/// vrf management") + child.sendline(self.copy_keyfile) + try: + child.expect ("continue") + child.sendline ("yes") + try: + child.expect('assword: ') + except pexpect.ExceptionPexpect: + LOGGER.error("Device "+str(self.temp_ip)+\ + " Login incorrect Provided User name is not correct") + sys.exit(0) + child.sendline (self.password) + try: + child.expect("#") + LOGGER.info("Device "+str(self.temp_ip)+\ + " copy server.key file success") + except pexpect.ExceptionPexpect: + LOGGER.error("Device "+str(self.temp_ip)+\ + " Login incorrect Provided Password is not correct") + sys.exit(0) + except: + try: + child.expect('assword: ') + except pexpect.ExceptionPexpect: + LOGGER.error("Device "+str(self.temp_ip)+\ + " Login incorrect Provided User name is not correct") + sys.exit(0) + child.sendline (self.password) + try: + child.expect("#") + LOGGER.info("Device "+str(self.temp_ip)+\ + " copy server.key file success") + except pexpect.ExceptionPexpect: + LOGGER.error("Device "+str(self.temp_ip)+\ + " Login incorrect Provided Password is not correct") + sys.exit(0) + time.sleep(10) + self.cp_certfile = str("copy scp://"+self.user+'@'+\ + self.ip+self.path+"server.crt bootflash:/// vrf management") + child.sendline(self.cp_certfile) + try: + child.expect ("continue") + child.sendline ("yes") + try: + child.expect('assword: ') + except pexpect.ExceptionPexpect: + LOGGER.error("Device "+str(self.temp_ip)+\ + " Login incorrect Provided User name is not correct") + sys.exit(0) + child.sendline (self.password) + try: + child.expect("#") + LOGGER.info("Device "+str(self.temp_ip)+\ + " copy server.crt file success") + except pexpect.ExceptionPexpect: + LOGGER.error("Device "+str(self.temp_ip)+\ + " Login incorrect Provided Password is not correct") + sys.exit(0) + except: + try: + child.expect('assword: ') + except pexpect.ExceptionPexpect: + LOGGER.error("Device "+str(self.temp_ip)+\ + " Login incorrect Provided User name is not correct") + sys.exit(0) + child.sendline (self.password) + try: + child.expect("#") + LOGGER.info("Device "+str(self.temp_ip)+\ + " copy server.crt file success") + except pexpect.ExceptionPexpect: + LOGGER.error("Device "+str(self.temp_ip)+\ + " Login incorrect Provided Password is not correct") + sys.exit(0) + time.sleep(10) + child.sendline("configure terminal") + try: + child.expect("#") + except pexpect.ExceptionPexpect: + LOGGER.error("Device "+str(self.temp_ip)+\ + " - Unable to configure in device using configuration "+\ + "terminal command") + time.sleep(5) + child.sendline("nxapi certificate httpskey "+ + "keyfile bootflash:///server.key") + try: + child.expect("#") + except pexpect.ExceptionPexpect: + LOGGER.error("Device "+str(self.temp_ip)+\ + " - Unable to configure certificate keyfile "+\ + "in device using nxapi certificate httpskey keyfile "+\ + "bootflash:///server.key command") + time.sleep(5) + try: + with open("./Utilities/TlsCerts/temp/temp.log", "r") as fp4: + for line4 in fp4: + time.sleep(5) + if "done" and "Upload" and" done" \ + and "cert" and "key" and "match" in line4: + break + else: + child.sendline("nxapi certificate "+ + "httpskey keyfile bootflash:///server.key") + child.expect('#') + break + except OSError: + LOGGER.error("Failed to open temporary Log file") + child.sendline("nxapi certificate httpscrt"+ \ + " certfile bootflash:///server.crt") + try: + child.expect("#") + except pexpect.ExceptionPexpect: + LOGGER.error("Device "+str(self.temp_ip)+\ + " - Unable to configure certificate certfile "+\ + "in device using nxapi certificate httpscrt certfile "+\ + "bootflash:///server.crt command") + time.sleep(5) + try: + with open("./Utilities/TlsCerts/temp/temp.log", "r") as fp5: + for line5 in fp5: + time.sleep(5) + if "done" and "Upload" and" done" and "cert" \ + and "key" and "match" in line4: + break + else: + child.sendline("nxapi certificate "+\ + "httpscrt certfile bootflash:///server.crt") + child.expect('#') + break + except OSError: + LOGGER.error("Failed to open temporary Log file") + child.sendline("nxapi certificate enable") + try: + child.expect("#") + except pexpect.ExceptionPexpect: + LOGGER.error("Device "+str(self.temp_ip)+\ + " - Unable to enable certificate "+\ + "in device using nxapi certificate enable command") + child.expect([pexpect.EOF, pexpect.TIMEOUT]) + self.log_mul_dev += 1 + self.cp_keypem = "cp ./Utilities/TlsCerts/server.key "+\ + "./Utilities/TlsCerts/xnc-privatekey.pem" + try: + self.cp_keypem_res = call(str(self.cp_keypem), \ + shell=True) + if self.cp_keypem_res == 0: + LOGGER.info("Copy server.key file to xnc-privatekey.pem "+\ + "file success") + else: + LOGGER.error("Failed to Copy server.key file to "+\ + "xnc-privatekey.pem file") + sys.exit(0) + except OSError: + LOGGER.error("Failed to Copy server.key file to "+\ + "xnc-privatekey.pem file") + sys.exit(0) + self.cp_certpem = "cp ./Utilities/TlsCerts/server.crt "+\ + "./Utilities/TlsCerts/xnc-cert.pem" + try: + self.cp_certpem_res = call(str(self.cp_certpem), \ + shell=True) + if self.cp_certpem_res == 0: + LOGGER.info("Copy server.crt file to xnc-cert.pem "+\ + "file success") + else: + LOGGER.error("Failed to Copy server.crt file to "+\ + "xnc-cert.pem file") + sys.exit(0) + except OSError: + LOGGER.error("Failed to Copy server.crt file to "+\ + "xnc-cert.pem file") + sys.exit(0) + self.cp_xncpem = "cat ./Utilities/TlsCerts/xnc-privatekey.pem "+\ + "./Utilities/TlsCerts/xnc-cert.pem > ./Utilities/TlsCerts/xnc.pem" + try: + self.cp_xncpem_res = call(str(self.cp_xncpem), \ + shell=True) + if self.cp_xncpem_res == 0: + LOGGER.info("Copy xnc-privatekey.pem and xnc-cert.pem "+\ + "file to xnc.pem file success") + else: + LOGGER.error("Failed to Copy xnc-privatekey.pem and "+\ + "xnc-cert.pem file to xnc.pem file") + sys.exit(0) + except OSError: + LOGGER.error("Failed to Copy xnc-privatekey.pem and "+\ + "xnc-cert.pem file to xnc.pem file") + sys.exit(0) + self.pass_pro = "openssl pkcs12 -export -out "+\ + "./Utilities/TlsCerts/xnc.p12 "+\ + "-in ./Utilities/TlsCerts/xnc.pem -password pass:"+\ + self.keystore_password + try: + self.pass_pro_res = call(str(self.pass_pro), \ + shell=True, \ + stdout=PIPE, \ + stderr=STDOUT) + if self.pass_pro_res == 0: + LOGGER.info("Generate xnc.p12 file success") + else: + LOGGER.error("Failed to Generate xnc.p12 file -step29") + sys.exit(0) + except OSError: + LOGGER.error("Failed to Generate xnc.p12 file -step29") + sys.exit(0) + #pdb.set_trace() + self.xncp_tlskey = "keytool -importkeystore -srckeystore "+\ + "./Utilities/TlsCerts/xnc.p12 -srcstoretype pkcs12 -destkeystore "+\ + "./Utilities/TlsCerts/tlsKeyStore -deststoretype jks -srcstorepass "+\ + self.keystore_password+" -deststorepass "+self.keystore_password + try: + self.xncp_tlskey_res = call(str(self.xncp_tlskey), \ + shell=True, \ + stdout=PIPE, \ + stderr=STDOUT) + if self.xncp_tlskey_res == 0: + LOGGER.info("Convert the xnc.p12 to a Java KeyStore "+\ + "- tlsKeyStore file success") + else: + LOGGER.error("Failed to Convert the xnc.p12 to a Java "+\ + "KeyStore (tlsKeyStore) file -step31") + #sys.exit(0) + except OSError: + LOGGER.error("Failed to Convert the xnc.p12 to a Java "+\ + "KeyStore (tlsKeyStore) file -step31") + #sys.exit(0) + self.capem_sw = "cp ./Utilities/TlsCerts/mypersonalca/certs/ca.pem "+\ + "./Utilities/TlsCerts/sw-cacert.pem" + try: + self.capem_sw_res = call(str(self.capem_sw), shell=True) + if self.capem_sw_res == 0: + LOGGER.info("Copy ca.pem file to sw-cacert.pem file success") + else: + LOGGER.error("Failed to Copy xnc-privatekey.pem and "+\ + "xnc-cert.pem file to xnc.pem file") + sys.exit(0) + except OSError: + LOGGER.error("Failed to Copy xnc-privatekey.pem and "+\ + "xnc-cert.pem file to xnc.pem file") + sys.exit(0) + self.sw_tlstrust = "keytool -import -alias swca1 -file "+\ + "./Utilities/TlsCerts/sw-cacert.pem -keystore ./Utilities/TlsCerts/tlsTrustStore "+\ + "-storepass "+self.keystore_password+" -noprompt" + try: + self.sw_tlstrust_res = call(str(self.sw_tlstrust), \ + shell=True, \ + stdout=PIPE, \ + stderr=STDOUT) + if self.sw_tlstrust_res == 0: + LOGGER.info("Convert the sw-cacert.pem file to a Java "+\ + "TrustStore - tlsTrustStore file success") + else: + LOGGER.error("Failed to Convert the sw-cacert.pem to a "+\ + "Java TrustStore - tlsTrustStore file -step34") + #sys.exit(0) + except OSError: + LOGGER.error("Failed to Convert the sw-cacert.pem to a "+\ + "Java TrustStore - tlsTrustStore file -step34") + #sys.exit(0) + ssh = paramiko.SSHClient() + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + self.login_mulser = 0 + self.tem_serip = "" + self.tem_seruser = "" + self.temp_serpass = "" + self.tem_serpath = "" + try: + with open(INPUTFILE, 'r') as file_ptr: + confi = yaml.load(file_ptr) + self.xnc_pwd = str(confi['xnc_password']) + self.xnc_usr = str(confi['xnc_username']) + except OSError: + LOGGER.error("Failed to open input yaml file") + while (self.login_mulser < len(self.server_ip_list)): + self.tem_serip = self.server_ip_list[self.login_mulser] + self.tem_seruser = self.server_user_list[self.login_mulser] + self.temp_serpass = self.server_password_list[self.login_mulser] + self.tem_serpath = self.server_path_list[self.login_mulser] + self.tem_port = self.server_port_list[self.login_mulser] + xnc_path = self.tem_serpath[:-14] + #pdb.set_trace() + if self.tem_port != 0: + try: + ssh = paramiko.SSHClient() + server = self.tem_serip + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + ssh.connect(server, port=self.tem_port, username=self.tem_seruser, password=self.temp_serpass) + sftp = ssh.open_sftp() + localpath = './Utilities/TlsCerts/tlsTrustStore' + remotepath = '/root/xnc/configuration/tlsTrustStore' + sftp.put(localpath, remotepath) + local = './Utilities/TlsCerts/tlsKeyStore' + remote = '/root/xnc/configuration/tlsKeyStore' + sftp.put(local, remote) + sftp.close() + except paramiko.SSHException: + LOGGER.error("Error while ssh into the server") + sys.exit(0) + else: + try: + ssh = paramiko.SSHClient() + server = self.tem_serip + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + ssh.connect(server, username=self.tem_seruser, password=self.temp_serpass) + sftp = ssh.open_sftp() + localpath = './Utilities/TlsCerts/tlsTrustStore' + remotepath = self.tem_serpath+'tlsTrustStore' + sftp.put(localpath, remotepath) + local = './Utilities/TlsCerts/tlsKeyStore' + remote = self.tem_serpath+'tlsKeyStore' + sftp.put(local, remote) + sftp.close() + except paramiko.SSHException: + LOGGER.error("Error while ssh into the server") + exit(0) + time.sleep(5) + #pdb.set_trace() + self.run_ndb = 'cd '+xnc_path+' ;./runxnc.sh -osgiPasswordSync '+\ + '-tls -tlskeystore ./configuration/tlsKeyStore -tlstruststore '+\ + './configuration/tlsTrustStore' + self.run_n = str(self.run_ndb) + if self.tem_port != 0: + self.run_n += '\n' + try: + chan = ssh.invoke_shell() + chan.send(self.run_n) + except OSError: + LOGGER.error("Server "+self.tem_serip+" Failed Run NDB"+\ + " in TLS mode") + sys.exit(0) + else: + try: + stdin, stdout, stderr = ssh.exec_command(self.run_n) + stdin.write(self.xnc_pwd+"\n") + #print stdout.readlines() + LOGGER.info("Server "+self.tem_serip+" Run NDB in TLS"+\ + " mode success") + except OSError: + LOGGER.error("Server "+self.tem_serip+" Failed Run NDB"+\ + " in TLS mode") + sys.exit(0) + time.sleep(75) + flag = True + timeout = time.time() + 60*5 + while(flag): + if time.time() <= timeout: + if self.tem_port != 0: + try: + ssh = paramiko.SSHClient() + server = self.tem_serip + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + ssh.connect(server, port=self.tem_port, username=self.tem_seruser, password=self.temp_serpass) + sftp = ssh.open_sftp() + localpath = '/root/xnc/logs/xnc.log' + remotepath = './Utilities/TlsCerts/xnc.log' + #pdb.set_trace() + sftp.put(localpath, remotepath) + local = '/root/xnc/logs/xnc.log' + remote = './Utilities/TlsCerts/xnc.log' + sftp.put(local, remote) + sftp.close() + except: + LOGGER.error("Error while ssh into the server") + sys.exit(0) + else: + try: + #pdb.set_trace() + ssh = paramiko.SSHClient() + server = self.tem_serip + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + ssh.connect(server, username=self.tem_seruser, password=self.temp_serpass) + sftp = ssh.open_sftp() + localpath = xnc_path+'logs/xnc.log' + remotepath = './Utilities/TlsCerts/xnc.log' + sftp.get(localpath, remotepath) + local = xnc_path+'logs/xnc.log' + remote = './Utilities/TlsCerts/xnc.log' + sftp.get(local, remote) + sftp.close() + except: + LOGGER.error("Error while ssh into the server11") + exit(0) + try: + with open("./Utilities/TlsCerts/xnc.log", 'r') as fil_ptr: + for line in fil_ptr: + if 'Started \'Cisco Extensible Network Controller (XNC)\' version' in line: + flag = False + break + else: + flag = True + continue + except OSError: + LOGGER.error("Failed to open xnc log file") + sys.exit(0) + else: + LOGGER.error("Failed to start NDB in TLS mode") + sys.exit(0) + time.sleep(15) + #pdb.set_trace() + self.prov_pass = 'cd '+xnc_path+'bin/ ;./xnc '+\ + 'config-keystore-passwords --user '+self.xnc_usr+\ + ' --password '+self.xnc_pwd+' --url https://'+self.tem_serip+\ + ':8443 --verbose --keystore-password '+self.keystore_password+\ + ' --truststore-password '+self.keystore_password + self.prov_pass_b = str(self.prov_pass) + if self.tem_port == 0: + try: + stdin, stdout, stderr = ssh.exec_command(self.prov_pass_b) + LOGGER.info("Server "+self.tem_serip+" Run command of "+\ + "provided TLSKeyStore and TrustStore success") + except OSError: + LOGGER.error("Server "+self.tem_serip+" Failed to Run "+\ + "command of provided TLSKeyStore and TrustStore") + sys.exit(0) + else: + self.prov_pass_b += '\n' + try: + chan = ssh.invoke_shell() + chan.send(self.prov_pass_b) + except OSError: + LOGGER.error("Server "+self.tem_serip+" Failed to Run "+\ + "command of provided TLSKeyStore and TrustStore") + sys.exit(0) + time.sleep(10) + self.login_mulser += 1 + ssh.close() + +if __name__ == "__main__": + DIR = os.path.dirname(__file__) + #sys.stdout = os.devnull + if not os.path.isdir('./Utilities/Log'): + os.mkdir("./Utilities/Log") + #sys.stdout = open(os.devnull, "w") + if '--quiet' in sys.argv: + FILENAME = os.path.join(DIR, './Utilities/Log/Logfile.log') + LOGGER = logging.getLogger(__name__) + LOGGER.setLevel(logging.DEBUG) + FILE_LOG_HANDLER = logging.FileHandler(FILENAME) + FILE_LOG_HANDLER.setLevel(logging.DEBUG) + FORMATTER = logging.Formatter( + '%(asctime)s - %(name)s - %(levelname)s - %(message)s') + FILE_LOG_HANDLER.setFormatter(FORMATTER) + LOGGER.addHandler(FILE_LOG_HANDLER) + else: + FILENAME = os.path.join(DIR, './Utilities/Log/Logfile.log') + LOGGER = logging.getLogger(__name__) + LOGGER.setLevel(logging.DEBUG) + CON_LOG_HANDLER = logging.StreamHandler() + FILE_LOG_HANDLER = logging.FileHandler(FILENAME) + FILE_LOG_HANDLER.setLevel(logging.DEBUG) + CON_LOG_HANDLER.setLevel(logging.DEBUG) + FORMATTER = logging.Formatter( + '%(asctime)s - %(name)s - %(levelname)s - %(message)s') + FILE_LOG_HANDLER.setFormatter(FORMATTER) + CON_LOG_HANDLER.setFormatter(FORMATTER) + LOGGER.addHandler(FILE_LOG_HANDLER) + LOGGER.addHandler(CON_LOG_HANDLER) + INPUTFILE = os.path.join(DIR, './Utilities/Input/inputfile.yaml') + D1 = Device() + D1.method_one() + D1.method_two() + + diff --git a/nexusdatabroker/TLSNXAPITool1.0/TLSNXAPITool.py b/nexusdatabroker/TLSNXAPITool1.0/TLSNXAPITool.py new file mode 100644 index 00000000..00a81167 --- /dev/null +++ b/nexusdatabroker/TLSNXAPITool1.0/TLSNXAPITool.py @@ -0,0 +1,122 @@ +import os +import sys +import yaml +import requests +import subprocess +import logging +import paramiko +# pylint: disable-msg=E0611 +from requests.packages.urllib3.exceptions import InsecureRequestWarning +from requests.packages.urllib3.exceptions import SNIMissingWarning +requests.packages.urllib3.disable_warnings(InsecureRequestWarning) +requests.packages.urllib3.disable_warnings(SNIMissingWarning) + +class Server: + def __init__(self): + self.conn_type = "https" + with open(INPUTFILE) as file_ptr: + confi = yaml.safe_load(file_ptr) + self.server_ip = confi['ServerIP']['ServerIP1']['ip'] + self.username = confi['ServerIP']['ServerIP1']['user'] + self.password = confi['ServerIP']['ServerIP1']['password'] + self.port = '8443' + self.web_url = "" + self.login_url = "" + self.add_device_url = "" + self.device_response = 0 + self.xnc_pwd = str(confi['xnc_password']) + self.xnc_usr = str(confi['xnc_username']) + def ndb_servrer_login(self, device_info): + try: + self.web_url = self.conn_type+"://"+self.server_ip+":"\ + +self.port+"/monitor/" + self.login_url = self.conn_type+"://"+self.server_ip+":"\ + +self.port+"/monitor/j_security_check" + login_payload = {"j_username" : self.xnc_usr, "j_password" : self.xnc_pwd} + with open(INPUTFILE) as file_ptr: + dev_info = yaml.safe_load(file_ptr) + add_device_payload = device_info + add_device_payload['connectiontype'] = 'NXAPI' + add_device_payload['auxnode'] = 'false' + for key in add_device_payload: + add_device_payload[key] = str(add_device_payload[key]) + self.add_device_url = str(self.conn_type+"://"+\ + str(self.server_ip)+":"+str(self.port)+\ + "/controller/web/devices/extended//element/add") + #pylint: disable=maybe-no-member + with requests.session() as ses: + ses.get(self.web_url, verify=False) + ses.post(self.login_url, data=login_payload, verify=False) + ses.post(self.add_device_url, data=add_device_payload, verify=False) + LOGGER.info("Device - "+add_device_payload['address']+\ + " Device added successfully") + except paramiko.SSHException: + LOGGER.error("Device - "+add_device_payload['address']+\ + " Failed to add device in NDB") +if __name__ == "__main__": + FILE1 = '/etc/ssh/ssh_config' + DIR = os.path.dirname(__file__) + #sys.stdout = os.devnull + if not os.path.isdir('./Utilities/Log'): + os.mkdir("./Utilities/Log") + #sys.stdout = open(os.devnull, "w") + if len(sys.argv) == 1: + FILENAME = os.path.join(DIR, './Utilities/Log/Logfile.log') + LOGGER = logging.getLogger(__name__) + LOGGER.setLevel(logging.DEBUG) + CON_LOG_HANDLER = logging.StreamHandler() + FILE_LOG_HANDLER = logging.FileHandler(FILENAME) + FILE_LOG_HANDLER.setLevel(logging.DEBUG) + CON_LOG_HANDLER.setLevel(logging.DEBUG) + FORMATTER = logging.Formatter( + '%(asctime)s - %(name)s - %(levelname)s - %(message)s') + FILE_LOG_HANDLER.setFormatter(FORMATTER) + CON_LOG_HANDLER.setFormatter(FORMATTER) + LOGGER.addHandler(FILE_LOG_HANDLER) + LOGGER.addHandler(CON_LOG_HANDLER) + elif len(sys.argv) == 2: + if '--quiet' in sys.argv: + FILENAME = os.path.join(DIR, './Utilities/Log/Logfile.log') + LOGGER = logging.getLogger(__name__) + LOGGER.setLevel(logging.DEBUG) + FILE_LOG_HANDLER = logging.FileHandler(FILENAME) + FILE_LOG_HANDLER.setLevel(logging.DEBUG) + FORMATTER = logging.Formatter( + '%(asctime)s - %(name)s - %(levelname)s - %(message)s') + FILE_LOG_HANDLER.setFormatter(FORMATTER) + LOGGER.addHandler(FILE_LOG_HANDLER) + else: + FILENAME = os.path.join(DIR, './Utilities/Log/Logfile.log') + LOGGER = logging.getLogger(__name__) + LOGGER.setLevel(logging.DEBUG) + CON_LOG_HANDLER = logging.StreamHandler() + FILE_LOG_HANDLER = logging.FileHandler(FILENAME) + FILE_LOG_HANDLER.setLevel(logging.DEBUG) + CON_LOG_HANDLER.setLevel(logging.DEBUG) + FORMATTER = logging.Formatter( + '%(asctime)s - %(name)s - %(levelname)s - %(message)s') + FILE_LOG_HANDLER.setFormatter(FORMATTER) + CON_LOG_HANDLER.setFormatter(FORMATTER) + LOGGER.addHandler(FILE_LOG_HANDLER) + LOGGER.addHandler(CON_LOG_HANDLER) + LOGGER.error(" Run python script without arguments or along "+\ + "with --quiet argument") + sys.exit(0) + else: + LOGGER.error(" Run python script without arguments or along "+\ + "with --quiet argument") + sys.exit(0) + if '--quiet' in sys.argv: + subprocess.call(" python TLSScript.py --quiet", shell=True) + subprocess.call(" python OpenSSL.py --quiet", shell=True) + else: + subprocess.call(" python TLSScript.py 1", shell=True) + subprocess.call(" python OpenSSL.py 1", shell=True) + INPUTFILE = os.path.join(DIR, './Utilities/Input/inputfile.yaml') + DEV = Server() + with open(INPUTFILE) as f: + DEVICE_INFO = yaml.safe_load(f) + for dic in sorted(DEVICE_INFO['IP'].keys()): + DEV.ndb_servrer_login(DEVICE_INFO['IP'][dic]) + os.system("rm -rf ./Utilities/TlsCerts/temp") + os.system("rm -rf ./Utilities/TlsCerts/xnc.log") \ No newline at end of file diff --git a/nexusdatabroker/TLSNXAPITool1.0/TLSScript.py b/nexusdatabroker/TLSNXAPITool1.0/TLSScript.py new file mode 100755 index 00000000..4c84a54d --- /dev/null +++ b/nexusdatabroker/TLSNXAPITool1.0/TLSScript.py @@ -0,0 +1,296 @@ +import os +import time +import yaml +import pexpect +import sys +import paramiko +import logging + +class Reachable: + def __init__(self): + self.device_ip_list = [] + self.device_user_list = [] + self.device_password_list = [] + self.log_mul_dev = 0 + self.temp_ip = "" + self.temp_user = "" + self.temp_pass = "" + self.tem_serip = "" + self.tem_seruser = "" + self.temp_serpass = "" + self.server_ip_list = [] + self.server_user_list = [] + self.server_password_list = [] + self.login_mulser = 0 + self.all_ips_from_yaml = {} + def reachable_check(self): + try: + with open(INPUTFILE, 'r') as file_ptr: + confi = yaml.safe_load(file_ptr) + self.all_ips_from_yaml = sorted(confi['IP'].keys()) + except OSError: + LOGGER.error("Failed to open input yaml file") + sys.exit(0) + self.log_mul_dev = 0 + for val in self.all_ips_from_yaml: + self.device_ip_list.append(confi['IP'][val]['address']) + self.device_user_list.append(confi['IP'][val]['username']) + self.device_password_list.append(confi['IP'][val]['password']) + while(self.log_mul_dev < len(self.device_ip_list)): + self.temp_ip = self.device_ip_list[self.log_mul_dev] + self.temp_user = self.device_user_list[self.log_mul_dev] + self.temp_pass = self.device_password_list[self.log_mul_dev] + child = pexpect.spawn('telnet '+ self.temp_ip) + time.sleep(3) + try: + child.expect('login: ') + except: + LOGGER.error("Device "+str(self.temp_ip)+\ + " Device is not reachable") + sys.exit(0) + child.sendline(self.temp_user) + time.sleep(3) + try: + child.expect('assword: ') + except: + LOGGER.error("Device "+str(self.temp_ip)+\ + " Login incorrect Provided User name is not correct") + sys.exit(0) + child.sendline(self.temp_pass) + time.sleep(3) + try: + child.expect("#") + LOGGER.info("Device "+str(self.temp_ip)+\ + " Login success") + except: + LOGGER.error("Device "+str(self.temp_ip)+\ + " Login incorrect Provided Password is not correct") + sys.exit(0) + self.log_mul_dev += 1 + self.login_mulser = 0 + server_list = sorted(confi['ServerIP'].keys()) + for value in server_list: + self.server_ip_list.append(confi['ServerIP']\ + [value]['ip']) + self.server_user_list.append(confi['ServerIP']\ + [value]['user']) + self.server_password_list.append(confi['ServerIP']\ + [value]['password']) + while (self.login_mulser < len(self.server_ip_list)): + self.tem_serip = self.server_ip_list[self.login_mulser] + self.tem_seruser = self.server_user_list[self.login_mulser] + self.temp_serpass = self.server_password_list[self.login_mulser] + try: + ssh = paramiko.SSHClient() + server = self.tem_serip + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + ssh.connect(server, username=self.tem_seruser, password=self.temp_serpass) + except: + LOGGER.error("Server "+self.tem_serip+" Unable to "+\ + "connect to Server ") + exit(0) + try: + stdin, stdout, stderr = ssh.exec_command("pwd") + LOGGER.info("Server "+self.tem_serip+" Login Success ") + except: + LOGGER.error("Server "+self.tem_serip+" Failed Run NDB"+\ + " in TLS mode") + sys.exit(0) + self.login_mulser += 1 + ssh.close() +class Nxapi: + def __init__(self): + self.default_days_c = "" + def method_one(self): + try: + if os.path.exists("./Utilities/TlsCerts"): + os.system("rm -rf ./Utilities/TlsCerts") + os.mkdir("./Utilities/TlsCerts") + LOGGER.info("TlsCerts Folder created successfully") + else: + os.mkdir("./Utilities/TlsCerts") + LOGGER.info("TlsCerts Folder created successfully") + except OSError: + LOGGER.error("Failed to Create TlsCerts Folder") + try: + os.mkdir('./Utilities/TlsCerts/mypersonalca/') + LOGGER.info("mypersonalca Folder created successfully "+\ + "under TlsCerts") + except OSError: + LOGGER.error("Failed to Create mypersonalca Folder "+\ + "under TlsCerts") + try: + os.mkdir('./Utilities/TlsCerts/mypersonalca/certs') + LOGGER.info("certs Folder created successfully under "+\ + "TlsCerts/mypersonalca") + except OSError: + LOGGER.error("Failed to Create certs Folder under "+\ + "TlsCerts/mypersonalca") + try: + os.mkdir('./Utilities/TlsCerts/mypersonalca/private') + LOGGER.info("private Folder created successfully "+\ + "under TlsCerts/mypersonalca") + except OSError: + LOGGER.error("Failed to Create private Folder "+\ + "under TlsCerts/mypersonalca") + try: + os.mkdir('./Utilities/TlsCerts/mypersonalca/crl') + LOGGER.info("crl Folder created successfully under "+\ + "TlsCerts/mypersonalca") + except OSError: + LOGGER.error("Failed to Create crl Folder under "+\ + "TlsCerts/mypersonalca") + try: + os.mkdir('./Utilities/TlsCerts/temp/') + LOGGER.info("temp Folder created successfully "+\ + "under TlsCerts") + except OSError: + LOGGER.error("Failed to Create temp Folder "+\ + "under TlsCerts") + try: + serial = open("./Utilities/TlsCerts/mypersonalca/"+\ + "serial", "w+") + LOGGER.info("serial file created successfully under "+\ + "TlsCerts/mypersonalca") + except OSError: + LOGGER.error("Failed to Create serial file under "+\ + "TlsCerts/mypersonalca") + try: + serial.write("01\n") + LOGGER.info("Write to serial file success") + except OSError: + LOGGER.error("Failed to write to serial file") + conf_file_input = """[ ca ] +default_ca = CA_default +[ CA_default ] +dir = . +serial = $dir/serial +database = $dir/index.txt +new_certs_dir = $dir/newcerts +certs = $dir/certs +certificate = $certs/cacert.pem +private_key = $dir/private/cakey.pem +default_days = 365 +default_md = sha256 +preserve = no +email_in_dn = no +nameopt = default_ca +certopt = default_ca +policy = policy_match +copy_extensions = copy +[ policy_match ] +countryName = match +stateOrProvinceName = match +organizationName = match +organizationalUnitName = optional +commonName = supplied +emailAddress = optional +[ req ] +default_bits = 2048 # Size of keys +default_keyfile = example.key # name of generated keys +default_md = sha256 # message digest algorithm +string_mask = nombstr # permitted characters +distinguished_name = req_distinguished_name +req_extensions = v3_req +x509_extensions = v3_req +[ req_distinguished_name ] +0.organizationName = Organization Name (company) +organizationalUnitName = Organizational Unit Name (department, division) +emailAddress = Email Address +emailAddress_max = 40 +localityName = Locality Name (city, district) +stateOrProvinceName = State or Province Name (full name) +countryName = Country Name (2 letter code) +countryName_min = 2 +countryName_max = 2 +commonName = Common Name (hostname, IP, or your name) +commonName_max = 64 +# Default values for the above, for consistency and less typing. +commonName_default = www.cisco.com +organizationName_default = Cisco +localityName_default = SanJose +stateOrProvinceName_default = KAR +countryName_default = US +emailAddress_default = webmaster@cisco.com +organizationalUnitName_default = NDB +[ v3_ca ] +basicConstraints = CA:TRUE +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid:always,issuer:always +[ v3_req ] +# Extensions to add to a certificate request +basicConstraints = CA:FALSE +keyUsage = nonRepudiation, digitalSignature, keyEncipherment +subjectAltName = @alt_names +[alt_names] +IP.1 = 1.1.1.1 +IP.2 = 2.2.2.2 +IP.3 = 3.3.3.3 +IP.4 = 4.4.4.4 +IP.5 = 5.5.5.5 +IP.6 = 6.6.6.6 +IP.7 = 7.7.7.7 +IP.8 = 8.8.8.8 +IP.9 = 9.9.9.9 +IP.10 = 10.10.10.10 +[ server ] +basicConstraints=CA:FALSE +nsCertType = server +nsComment = "OpenSSL Generated Server Certificate" +subjectKeyIdentifier=hash +authorityKeyIdentifier=keyid,issuer:always +[ client ] +basicConstraints=CA:FALSE +nsCertType = client +nsComment = "OpenSSL Generated Client Certificate" +subjectKeyIdentifier=hash +authorityKeyIdentifier=keyid,issuer:always""" + try: + if not os.path.isfile("./Utilities/TlsCerts/ca.conf"): + tls_conf_file = open('./Utilities/TlsCerts/ca.conf', 'w+') + LOGGER.info("CA configuration file created successfully "+\ + "under TlsCerts") + except OSError: + LOGGER.error("Failed to Create CA configuration file "+\ + "under TlsCerts") + try: + tls_conf_file.write(conf_file_input) + LOGGER.info("Write to CA configuration file success") + except OSError: + LOGGER.error("Failed to write to CA configuration file") + +if __name__ == "__main__": + DIR = os.path.dirname(__file__) + #sys.stdout = os.devnull + if not os.path.isdir('./Utilities/Log'): + os.mkdir("./Utilities/Log") + #sys.stdout = open(os.devnull, "w") + if '--quiet' in sys.argv: + FILENAME = os.path.join(DIR, './Utilities/Log/Logfile.log') + LOGGER = logging.getLogger(__name__) + LOGGER.setLevel(logging.DEBUG) + FILE_LOG_HANDLER = logging.FileHandler(FILENAME) + FILE_LOG_HANDLER.setLevel(logging.DEBUG) + FORMATTER = logging.Formatter( + '%(asctime)s - %(name)s - %(levelname)s - %(message)s') + FILE_LOG_HANDLER.setFormatter(FORMATTER) + LOGGER.addHandler(FILE_LOG_HANDLER) + else: + FILENAME = os.path.join(DIR, './Utilities/Log/Logfile.log') + LOGGER = logging.getLogger(__name__) + LOGGER.setLevel(logging.DEBUG) + CON_LOG_HANDLER = logging.StreamHandler() + FILE_LOG_HANDLER = logging.FileHandler(FILENAME) + FILE_LOG_HANDLER.setLevel(logging.DEBUG) + CON_LOG_HANDLER.setLevel(logging.DEBUG) + FORMATTER = logging.Formatter( + '%(asctime)s - %(name)s - %(levelname)s - %(message)s') + FILE_LOG_HANDLER.setFormatter(FORMATTER) + CON_LOG_HANDLER.setFormatter(FORMATTER) + LOGGER.addHandler(FILE_LOG_HANDLER) + LOGGER.addHandler(CON_LOG_HANDLER) + INPUTFILE = os.path.join(DIR, './Utilities/Input/inputfile.yaml') + D = Reachable() + D.reachable_check() + D1 = Nxapi() + D1.method_one() diff --git a/nexusdatabroker/TLSNXAPITool1.0/Utilities/Input/inputfile.yaml b/nexusdatabroker/TLSNXAPITool1.0/Utilities/Input/inputfile.yaml new file mode 100755 index 00000000..63dd94d1 --- /dev/null +++ b/nexusdatabroker/TLSNXAPITool1.0/Utilities/Input/inputfile.yaml @@ -0,0 +1,55 @@ +IP: + IP1: + port: 443 + address: 1.1.1.1 + username: admin + password: cisco123 + IP2: + port: 443 + address: 1.1.1.2 + username: admin + password: cisco123 + +ServerIP: + ServerIP1: + ip: 2.2.2.1 + user: root + password: cisco123 + path_ndb_build: /root/Ndb3.3-Releasebuild/xnc + ServerIP2: + ip: 2.2.2.2 + user: root + password: cisco123 + path_ndb_build: /root/Ndb3.3-Releasebuild/xnc + +default_days: 365 +default_md: 'sha1' +default_bits: 2048 +keystore: 'cisco123' + +xnc_username: 'admin' +xnc_password: 'admin' + +#countryName +countryName: US + +#stateOrProvinceName +stateOrProvinceName: CA + +#organizationName +organizationName: Cisco + +#organizationalUnitName +organizationalUnitName: NDB + +#commonName +commonName: Network + +#emailAddress +emailAddress: web_master@cisco.com + +#localityName +localityName: SanJose + + + diff --git a/nexusdatabroker/TLSNXAPITool1.0/Utilities/Log/Logfile.log b/nexusdatabroker/TLSNXAPITool1.0/Utilities/Log/Logfile.log new file mode 100644 index 00000000..e69de29b