Esempio n. 1
0
 def test_sw_put_ftp(self, mock_ftp_put):
     dev = Device(host='1.1.1.1', user='******', password='******',
                  mode='telnet', port=23, gather_facts=False)
     sw = SW(dev)
     sw.put(package='test.tgz')
     self.assertTrue(
         call(
             'test.tgz',
             '/var/tmp') in mock_ftp_put.mock_calls)
Esempio n. 2
0
def JunosSwUpgrade():

    # initialize logging
    logging.basicConfig(filename=logfile,
                        level=logging.INFO,
                        format='%(asctime)s:%(name)s: %(message)s')
    logging.getLogger().name = hostName
    logging.getLogger().addHandler(logging.StreamHandler())
    logging.info('Information logged in {0}'.format(logfile))

    if no_copy == False:
        # verify package exists
        if not (os.path.isfile(package)):
            msg = 'Software package does not exist: {0}. '.format(package)
            logging.error(msg)
            print("Package not Exists error and exit with system exit")
            sys.exit()

    dev = Device(host=hostName, user=uName, password=uPass)

    try:
        dev.open()
    except ConnectError as err:
        logging.error('Cannot connect to device: {0}\n'.format(err))
        print("Connection issue with the Target device")
        return

    # Create an instance of SW
    sw = SW(dev)

    try:
        logging.info('Starting the software upgrade process: {0}' \
                     .format(package))
        print("Starting software upgrade process")
        ok = sw.install(package=package,
                        remote_path=remote_path,
                        progress=update_progress,
                        validate=validate,
                        no_copy=True,
                        all_re=True)
    except Exception as err:
        msg = 'Unable to install software, {0}'.format(err)
        logging.error(msg)
        ok = False

    if ok is True:
        logging.info('Software installation complete. Rebooting')
        rsp = sw.reboot()
        logging.info('Upgrade pending reboot cycle, please be patient.')
        logging.info(rsp)
    else:
        msg = 'Unable to install software, {0}'.format(ok)
        logging.error(msg)

    # End the NETCONF session and close the connection
    dev.close()
Esempio n. 3
0
 def reboot(self):
     try:
         from jnpr.junos.utils.sw import SW
         sw = SW(self.device)
         print("Rebooting...")
         print(sw.reboot())
         print("The system reboot successfully")
     except RpcError as err:
         print("Unable to reboot the system: {0}".format(err))
         sys.exit(1)
Esempio n. 4
0
def reboot_device(ip_addr):
    dev = call_dev(ip_addr)

    try:
        dev.open(gather_facts=False)
    except Exception as err:
        return
    else:
        sw = SW(dev)
        rsp = sw.reboot()
        dev.close()
def main():

    # initialize logging
    logging.basicConfig(filename=logfile,
                        level=logging.INFO,
                        format='%(asctime)s:%(name)s: %(message)s')
    logging.getLogger().name = host
    logging.getLogger().addHandler(logging.StreamHandler())
    logging.info('Information logged in {0}'.format(logfile))

    # verify package exists
    if not (os.path.isfile(package)):
        msg = 'Software package does not exist: {0}. '.format(package)
        logging.error(msg)
        sys.exit()

    dev = Device(host=host, user=junos_username, passwd=junos_password)
    try:
        dev.open()
    except ConnectError as err:
        logging.error('Cannot connect to device: {0}\n'.format(err))
        return

    # Create an instance of SW
    sw = SW(dev)

    try:
        logging.info(
            'Starting the software upgrade process: {0}'.format(package))
        #ok = sw.install(package=package,progress=update_progress)
    except Exception as err:
        msg = 'Unable to install software, {0}'.format(err)
        logging.error(msg)
        ok = False
    #UPGRADED SUCCESSFULLY
    logging.info("!!!!!!!!!!!!!")
    #logging.info(dev.cli("request system firmware upgrade pic pic-slot 0 fpc-slot 1"))
    print dev.cli("show system firmware")

    logging.info("!!!!!!!!!!!!!")

    if ok is True:
        logging.info('Software installation complete. Rebooting')
        #rsp = sw.reboot()
        logging.info('Upgrade pending reboot cycle, please be patient.')
        logging.info(rsp)
    else:
        msg = 'Unable to install software, {0}'.format(ok)
        logging.error(msg)

    # End the NETCONF session and close the connection
    dev.close()
Esempio n. 6
0
def main():
    dev = Device(host="192.168.65.61", user="******", passwd="lab123", normalize=True)
    dev.open()

    if dev.facts['junos_info']['re0']['text'] == TARGET_VERSION:
        print("Device OS version is already the target version")
        exit(1) 

    fs = FS(dev)
    bytes_free = fs.storage_usage()['/dev/gpt/junos']['avail_block']*512

    file_size = os.stat(IMAGE_FILE).st_size
    
    print("We have %d bytes free, image size is %d" % (bytes_free, file_size))    
    if bytes_free < file_size:
        print("Error: not enough space on device")
        exit(1)

    print("Copying image to the device...")
    with SCP(dev, progress=True) as scp:
        scp.put(IMAGE_FILE, remote_path=REMOTE_PATH)

    print("Installing package...")
    sw = SW(dev)
    install_result = sw.install(package=REMOTE_PATH+IMAGE_FILE, no_copy=True, validate=False,
             progress=True)
    if not install_result:
        print("Installation error, exiting")
        exit(1)

    print("Rebooting...")
    sw.reboot()

    for _ in range(20):
        print("Waiting for device reboot...")
        sleep(50)
        try:
            dev.open(auto_probe=10)
            ver = dev.facts['junos_info']['re0']['text']
        except (ProbeError, ConnectError):
            continue
        dev.close()
        break
    else:
        print("The device did not complete reboot in time, please check.")
        exit(1)          

    if ver == TARGET_VERSION:
        print("Reboot complete. Installation successful.")
    else:
        print("Reboot complete but something went wrong!")
        exit(1)
Esempio n. 7
0
 def test_sw_put_ftp(self, mock_ftp_put):
     dev = Device(
         host="1.1.1.1",
         user="******",
         password="******",
         mode="telnet",
         port=23,
         gather_facts=False,
     )
     dev.facts = facts
     sw = SW(dev)
     sw.put(package="test.tgz")
     self.assertTrue(call("test.tgz", "/var/tmp") in mock_ftp_put.mock_calls)
Esempio n. 8
0
def install_package(module, device):
    junos = SW(device)
    package = module.params['src']
    no_copy = module.params['no_copy']

    progress_log = lambda x, y: module.log(y)

    module.log('installing package')
    result = junos.install(package, progress=progress_log, no_copy=no_copy)

    if not result:
        module.fail_json(msg='Unable to install package on device')

    if module.params['reboot']:
        module.log('rebooting system')
        junos.reboot()
Esempio n. 9
0
def main():
    # initialize logging
    logging.basicConfig(filename="results.log", level=logging.DEBUG,
                        format='%(asctime)s:%(levelname)s: %(message)s')
  
    dev = Device(host=hostname, user=junos_username, passwd=junos_password)
    
    # hard set parameters. 
    # dev = Device(host="192.168.100.1", user="******", passwd="juniper123")
    try:
        dev.open()
    except ConnectError as err:
        sys.exit("Unfortunately the target device is unreachable. Check connection parameters.")

    type = (dev.facts["version"])
  
    sw = SW(dev)

    if type == "18.4R3-S2":
        logging.info("Already on latest firmware.")
        print("Looks like your device is already on the latest firmware!.")

    elif type != "18.4R3-S2":
        print("Not on latest Junos version. Copying/installing latest Junos image to device. Please be patient.")
        try:
            logging.info('Starting the software upgrade process: {0}'.format(package_srx))
            ok = sw.install(package=package_srx,remote_path=srx_local,validate=False,progress=update_progress)
                
        except Exception as err:
            msg = 'Unable to install software, {0}'.format(err)
            logging.error(msg)
            ok = False
            print("Unable to install software.")

        if ok == True:
            print("Software installation complete. Rebooting!")
            logging.info("Software installation complete. Rebooting!")
            rsp = sw.reboot()
            logging.info("Upgrade pending reboot cycle, please be patient.")
            logging.info(rsp)
    else:   
        msg = 'Unable to install software, {0}'.format(ok)
        logging.error(msg)
        print("Unable to install software.")

    dev.close()
Esempio n. 10
0
def main():
    # initialize logging
    logging.basicConfig(filename=logfile,
                        level=logging.INFO,
                        format='%(asctime)s:%(name)s: %(message)s')
    logging.getLogger().name = host
    logging.getLogger().addHandler(logging.StreamHandler())
    logging.info('Information logged in {0}'.format(logfile))
    # verify package exists
    if not (os.path.isfile(package)):
        msg = 'Software package does not exist: {0}. '.format(package)
        logging.error(msg)
        sys.exit()

    try:
        dev = Device(host=host)
        dev.open()
    except ConnectError as err:
        logging.error('Cannot connect to device: {0}\n'.format(err))
        return

    # Create an instance of SW
    sw = SW(dev)
    try:
        logging.info(
            'Starting the software upgrade process: {0}'.format(package))
        ok = sw.install(package=package,
                        remote_path=remote_path,
                        progress=update_progress,
                        validate=validate)
    except Exception as err:
        msg = 'Unable to install software, {0}'.format(err)
        logging.error(msg)
        ok = False

    if ok is True:
        logging.info('Software installation complete. Rebooting')
        #        rsp = sw.reboot()
        logging.info('Upgrade pending reboot cycle, please be patient.')
        logging.info(rsp)
    else:
        msg = 'Unable to install software, {0}'.format(ok)
        logging.error(msg)

    # End the NETCONF session and close the connection
    dev.close()
Esempio n. 11
0
def install_package(module, device):
    junos = SW(device)
    package = module.params['src']
    no_copy = module.params['no_copy']
    validate = module.params['validate']

    def progress_log(dev, report):
        module.log(report)

    module.log('installing package')
    result = junos.install(package, progress=progress_log, no_copy=no_copy,
                           validate=validate)

    if not result:
        module.fail_json(msg='Unable to install package on device')

    if module.params['reboot']:
        module.log('rebooting system')
        junos.reboot()
Esempio n. 12
0
def install_junos(ip_addr, image_file):
    # calucurate MD5
    md5 = commands.getoutput('md5sum -b %s' % cofig.OS_Dir + '/' +
                             image_file).split()
    local_md5 = md5[0]
    print 'local md5 =  ', local_md5, '<br>'

    dev = call_dev(ip_addr)

    try:
        dev.open(gather_facts=False)
        dev.timeout = 1800

        # copy the image
        print 'Copying os image. please wait...<br>'
        junos_image_file = config.Temp_Dir + image_file
        cu = FS(dev)
        result = cu.cp(config.OSImage_Dir + image_file, junos_image_file)

        # calcurate MD5 on device
        remote_md5 = cu.checksum(junos_image_file)

        print 'remote md5 = ', remote_md5, '<br>'

        if local_md5 == remote_md5:
            print 'Complete file copy successfully.<br>'

            # install the image
            print 'Start junos update. please wait...<br>'
            sw = SW(dev)
            result = sw.pkgadd(junos_image_file)

            if result is True:
                print 'OS installation process finished successfully.<br>'
            else:
                print 'OS installation process finished with failure.<br>'
        else:
            print 'Complete file copy with failure.<br>'

    except Exception as err:
        print err
    else:
        dev.close()
Esempio n. 13
0
def reboot_router(hostname):
    '''
    Reboot the routers
    '''

    username = '******'
    password = '******'

    print(f"Rebooting hostname {hostname}")

    try:
        with Device(host=hostname,
                    user=username,
                    password=password,
                    normalize=True) as dev:
            sw = SW(dev)
            print(sw.reboot())
    except ConnectError as err:
        print(err)
        return False
Esempio n. 14
0
    def scrub(cls, set_data):
        """
        Setups new routers.
        """
        utils.colour_print(f'Generating JunOS setconf for router:')
        file_name = f'scrub.j2'
        setconf = jinja_env.get_template(file_name).render(**set_data)

        if cls.deploy(setconf=setconf, router_ip=set_data['router']['router_ip']):
            utils.colour_print('(colour_success)Successfully scrubbed router.(colour_clear)')
            utils.colour_print('Reboot required so rebooting the router..')

            with Device(host=set_data['router']['router_ip'], user='******') as router:
                sw = SW(router)
                sw.reboot(in_min=2)
            utils.colour_print('Rebooting the router...')

        else:
            utils.error('Failed to build router, please try again.')
            traceback.print_exc()
def main():
    module = AnsibleModule(argument_spec=dict(host=dict(type='str',
                                                        required=True),
                                              port=dict(type='int',
                                                        default=830),
                                              user=dict(type='str',
                                                        default='root'),
                                              password=dict(type='str',
                                                            default=None,
                                                            no_log=True),
                                              license=dict(type='str',
                                                           required=True),
                                              shutdown=dict(type='bool',
                                                            default=False)),
                           supports_check_mode=True)

    args = module.params

    if not isfile(args['license']):
        module.fail_json(msg="license not found: {0}".format(args['license']))
        return

    dev = Device(args['host'],
                 user=args['user'],
                 password=args['password'],
                 port=args['port']).open()

    with MyStartShell(dev) as sh:
        license = open(args['license']).read().splitlines()
        for line in license:
            sh.run('echo %s >> /var/tmp/license.lic' % line)
        sh.run('cli -c "request system license add /var/tmp/license.lic"')

    if args['shutdown']:
        try:
            SW(dev).poweroff()
        except RpcError:
            pass

    module.exit_json(failed=False, changed=True)
Esempio n. 16
0
    def junos_auto_install(self, host_ip, path, device):
        """
        Use PyEz to secure install new junos version
        to remote host
        """

        sw = SW(device)
        path = os.path.join(os.getcwd(), path)
        print path, type(path)
        try:
            ok = sw.install(package=path, progress=install_progress)
        except Exception as err:
            print("Install error")
            raise err
        if ok is True:
            print("\nSoftware installation succeeded")
        else:
            print(ok)
            time.sleep(30)
        try:
            rsp = sw.reboot()
            print(rsp)
        except exception.ConnectClosedError:
            print("About to loose connection ..")
        finally:
            print("Please wait for the box to wake-up!")
            time.sleep(120)
            dev = self.device_connect(host_ip)
            feeds = dev.probe(10)
            while not feeds:
                feeds = dev.probe(20)
                #print("probing in 20 seconds interval")
            print("\n\nConnecting to box now ...")
            dev.open()
            print("Connected")
            print("New version:")
            self.print_base_info(dev)
            return dev
Esempio n. 17
0
 def test_sw_constructor_multi_vc(self, mock_execute):
     mock_execute.side_effect = self._mock_manager
     self.sw = SW(self.dev)
     self.assertFalse(self.sw._multi_VC)
Esempio n. 18
0
 def get_sw(self, mock_execute):
     mock_execute.side_effect = self._mock_manager
     return SW(self.dev)
Esempio n. 19
0
def shutdown(**kwargs):
    '''
    Shut down (power off) or reboot a device running Junos OS. This includes
    all Routing Engines in a Virtual Chassis or a dual Routing Engine system.

      .. note::
          One of ``shutdown`` or ``reboot`` must be set to ``True`` or no
          action will be taken.

    shutdown : False
      Set this to ``True`` if you want to shutdown the machine. This is a
      safety mechanism so that the user does not accidentally shutdown the
      junos device.

    reboot : False
      If ``True``, reboot instead of shutting down

    at
      Used when rebooting, to specify the date and time the reboot should take
      place. The value of this option must match the JunOS CLI reboot syntax.

    in_min
        Used when shutting down. Specify the delay (in minutes) before the
        device will be shut down.

    CLI Examples:

    .. code-block:: bash

        salt 'device_name' junos.shutdown reboot=True
        salt 'device_name' junos.shutdown shutdown=True in_min=10
        salt 'device_name' junos.shutdown shutdown=True
    '''
    conn = __proxy__['junos.conn']()
    ret = dict()
    sw = SW(conn)

    op = dict()
    if '__pub_arg' in kwargs:
        if kwargs['__pub_arg']:
            if isinstance(kwargs['__pub_arg'][-1], dict):
                op.update(kwargs['__pub_arg'][-1])
    else:
        op.update(kwargs)
    if 'shutdown' not in op and 'reboot' not in op:
        ret['message'] = \
            'Provide either one of the arguments: shutdown or reboot.'
        ret['out'] = False
        return ret

    try:
        if 'reboot' in op and op['reboot']:
            shut = sw.reboot
        elif 'shutdown' in op and op['shutdown']:
            shut = sw.poweroff
        else:
            ret['message'] = 'Nothing to be done.'
            ret['out'] = False
            return ret

        if 'in_min' in op:
            shut(in_min=op['in_min'])
        elif 'at' in op:
            shut(at=op['at'])
        else:
            shut()
        ret['message'] = 'Successfully powered off/rebooted.'
        ret['out'] = True
    except Exception as exception:
        ret['message'] = \
            'Could not poweroff/reboot beacause "{0}"'.format(exception)
        ret['out'] = False
    return ret
Esempio n. 20
0
from jnpr.junos import Device
from jnpr.junos.utils.sw import SW
import sys

dev = Device('host', user='******', password='******')
try:
    dev.open()
except Exception as err:
    print "Unable to connect to host:", err
    sys.exit(1)

sft = SW(dev)
print sft.reboot()
#print sft.reboot(in_min=5)
#print ("Before Shutdown\n")
#print sft.poweroff()
#print ("After Shutdown\n")
Esempio n. 21
0
    def upgrade_device(self, ip, hostname, tar_code, reboot="askReboot"):
        # Upgrade single device
        # Status dictionary for post-upgrade reporting
        statusDict = {}
        if Menu.upgrade_list == '':
            statusDict['Upgrade_List'] = 'Juniper-Upgrade_' + Menu.username
        else:
            statusDict['Upgrade_List'] = Menu.upgrade_list
        statusDict['Upgrade_Start'] = ''
        statusDict['Upgrade_Finish'] = ''
        statusDict['IP'] = ip
        statusDict['Connected'] = 'N'
        statusDict['OS_installed'] = 'N'
        statusDict['Rebooted'] = 'N'
        statusDict['IST_Confirm_Loaded'] = ''
        statusDict['IST_Confirm_Rebooted'] = ''
        statusDict['Comments'] = ''

        # Start Logging
        now = datetime.datetime.now()
        date_time = now.strftime("%Y-%m-%d-%H%M")
        install_log = Menu.log_dir + "juniper-install-LOG_" + date_time + "_" + Menu.username + ".log"
        logging.basicConfig(filename=install_log,
                            level=logging.INFO,
                            format='%(asctime)s:%(name)s: %(message)s')
        logging.getLogger().name = ip
        print('Information logged in {0}'.format(install_log))

        # Upgrade Information
        self.do_log("Device: {0} ({1})".format(hostname, ip))
        self.do_log("JunOS: {0}".format(tar_code))

        # Verify package exists before starting upgrade process
        fullpathfile = Menu.image_dir + tar_code
        if os.path.isfile(fullpathfile):
            dev = Device(ip, user=Menu.username, password=Menu.password)
            self.do_log('\n')
            self.do_log(
                '------------------------- Opening connection to: {0} -------------------------\n'
                .format(ip))
            self.do_log('User: {0}'.format(Menu.username))
            # Try to open a connection to the device
            try:
                dev.open()
            # If there is an error when opening the connection, display error and exit upgrade process
            except Exception as err:
                sys.stderr.write('Cannot connect to device {0} : {1}'.format(
                    ip, err))
            # If
            else:
                # Record connection achieved
                statusDict['Connected'] = 'Y'
                # Increase the default RPC timeout to accommodate install operations
                dev.timeout = 600
                # Create an instance of SW
                sw = SW(dev)
                try:
                    # Logging...
                    self.do_log(
                        'Starting the software upgrade process: {0}'.format(
                            tar_code))
                    now = datetime.datetime.now()
                    statusDict['Upgrade_Start'] = now.strftime(
                        "%Y-%m-%d %H:%M")
                    self.do_log('Timestamp: {0}'.format(
                        statusDict['Upgrade_Start']))

                    # Actual Upgrade Function
                    ok = sw.install(package=fullpathfile,
                                    remote_path=Menu.remote_path,
                                    progress=True,
                                    validate=True)
                    # Failed install method...
                    # ok = sw.install(package=fullPathFile, remote_path=Menu.remote_path, progress=self.update_progress, validate=True)
                except Exception as err:
                    msg = 'Unable to install software, {0}'.format(err)
                    self.do_log(msg, level='error')
                else:
                    if ok is True:
                        # Logging...
                        statusDict['OS_installed'] = 'Y'
                        self.do_log('Software installation complete.')
                        now = datetime.datetime.now()
                        statusDict['Upgrade_Finish'] = now.strftime(
                            "%Y-%m-%d %H:%M")
                        self.do_log('Timestamp: {0}'.format(
                            statusDict['Upgrade_Finish']))
                        # Check rebooting status...
                        if reboot == "askReboot":
                            answer = getYNAnswer('Would you like to reboot')
                            if answer == 'y':
                                reboot = "doReboot"
                            else:
                                reboot = "noReboot"
                        if reboot == "doReboot":
                            rsp = sw.reboot()
                            statusDict['Rebooted'] = 'Y'
                            self.do_log(
                                'Upgrade pending reboot cycle, please be patient.'
                            )
                            self.do_log(rsp)
                            # Open a command terminal to monitor device connectivity
                            # os.system("start cmd /c ping -t " + ip)
                        elif reboot == "noReboot":
                            self.do_log(
                                'Reboot NOT performed. System must be rebooted to complete upgrade.'
                            )

                # End the NETCONF session and close the connection
                dev.close()
                self.do_log('\n')
                self.do_log(
                    '------------------------- Closed connection to: {0} -------------------------\n'
                    .format(ip))
        else:
            msg = 'Software package does not exist: {0}. '.format(fullpathfile)
            sys.exit(msg + '\nExiting program')

        return statusDict
Esempio n. 22
0
def update_process(type,host,package,threadIns):
    
    # verify package exists
    if type=='OS' or type=='Firmware':
        if not (os.path.isfile(package)):
            msg = 'Software package does not exist: {0}. '.format(package)
            logging.error(msg)
            print msg
            sys.exit()
    time.sleep(20)
    dev=None
    dev = Device(host=host,user=junos_username, passwd=junos_password)
    rebootTime=10
    rebootOK=False
    while not rebootOK:
        try:
            time.sleep(10)
            rebootOK=True
            dev.open()
        except Exception as err:
            print threadIns.hostIP+threadIns.serialNumber+':wait device time='+str(rebootTime)+"Sec  "+str(err)
            logging.info(threadIns.hostIP+threadIns.serialNumber+':wait device time='+str(rebootTime)+"Sec  "+str(err))
            rebootTime+=10
            rebootOK=False

        if rebootTime>=rebootTimeout:
            logging.error('Cannot connect to device\n')
            print 'Cannot connect to device\n'
            return
    
        



    
        
    if type=='createLogFile':
        threadIns.status="createLog"
        dev.timeout = 100
        create_log(dev)
        dev.close()
        return
        
    if type=='checkSerialNumber':
        threadIns.status="checkSN"
        threadIns.serialNumber=dev.facts['serialnumber']
        dev.close()
        return
    
    if type=='Snapshot':
        threadIns.status="Snapshot"
        dev.timeout = 600
        dev.rpc.request_snapshot(slice='alternate')
        dev.close()
        return
    
    if type=='setFixIP':
        threadIns.status="setFixIP"
        cu = Config(dev)
        cu.load('delete interfaces ge-0/0/0', format='set')
        cu.load('set interfaces ge-0/0/0 unit 0 family inet address '+threadIns.hostIP+'/'+str(dhcpNetmask), format='set')
        cu.pdiff()
        cu.commit()
        return
    
    
    
    
    # Create an instance of SW
    sw = SW(dev)
    
    threadIns.status="install"+type
    try:
        logging.info('Starting the software upgrade process: {0}'.format(package))
        okOS = sw.install(package=package, remote_path=remote_path,progress=update_progress, validate=validate)
        #okOS=True
    except Exception as err:
        msg = 'Unable to install software, {0}'.format(err)
        logging.error(msg)
        okOS = False
    
    
    if type=="Firmware":
        #UPGRADED SUCCESSFULLY
        logging.info("!!!!!!!!!!!!!")
        logging.info(dev.cli("request system firmware upgrade pic pic-slot 0 fpc-slot 1"))
        threadIns.status="checkFirmware"
        
        okFirmware=False
        #okFirmware=True
        firmwareTime=0
        
        while not okFirmware and okOS:
            xmlStr=etree.tostring(dev.rpc.get_system_firmware_information(), encoding='unicode')
            xmlRoot = ET.fromstring(xmlStr)
            for firmware_status in xmlRoot.iter('firmware-status'):
                #UPGRADED SUCCESSFULLY
                if firmware_status.text=='UPGRADED SUCCESSFULLY':okFirmware=True
                if firmware_status.text!='OK':print firmware_status.text
            print threadIns.hostIP+threadIns.serialNumber+":wate firmware upgrade "+str(firmwareTime)+" Sec"
            time.sleep(1)
            firmwareTime=firmwareTime+1
            #print okFirmware
    elif type=="OS":okFirmware=True
    
    
    
    threadIns.status="reboot after install"+type
    if okOS is True and okFirmware is True:
        logging.info('Software installation complete. Rebooting')
        rsp = sw.reboot()
        logging.info('Upgrade pending reboot cycle, please be patient.')
        logging.info(rsp)
    else:
        msg = 'Unable to install software, {0}'.format(okOS)
        logging.error(msg)
    
    # End the NETCONF session and close the connection
    dev.close()
Esempio n. 23
0
def shutdown(**kwargs):
    '''
    Shut down (power off) or reboot a device running Junos OS.
    This includes all Routing Engines in a Virtual Chassis or a dual Routing \
    Engine system.

    Usage:

    .. code-block:: bash

        salt 'device_name' junos.shutdown reboot=True

        salt 'device_name' junos.shutdown shutdown=True in_min=10

        salt 'device_name' junos.shutdown shutdown=True


    Parameters:
      Optional
        * kwargs:
            * shutdown:
              Set this to true if you want to shutdown the machine.
              (default=False, this is a safety mechanism so that the user does
              not accidentally shutdown the junos device.)
            * reboot:
              Whether to reboot instead of shutdown. (default=False)
              Note that either one of the above arguments has to be specified
              (shutdown or reboot) for this function to work.
            * at:
              Date and time the reboot should take place. The
              string must match the junos cli reboot syntax
              (To be used only if reboot=True)
            * in_min:
              Specify delay in minutes for shutdown

    '''
    conn = __proxy__['junos.conn']()
    ret = dict()
    sw = SW(conn)

    op = dict()
    if '__pub_arg' in kwargs:
        if kwargs['__pub_arg']:
            if isinstance(kwargs['__pub_arg'][-1], dict):
                op.update(kwargs['__pub_arg'][-1])
    else:
        op.update(kwargs)
    if 'shutdown' not in op and 'reboot' not in op:
        ret['message'] = \
            'Provide either one of the arguments: shutdown or reboot.'
        ret['out'] = False
        return ret

    try:
        if 'reboot' in op and op['reboot']:
            shut = sw.reboot
        elif 'shutdown' in op and op['shutdown']:
            shut = sw.poweroff
        else:
            ret['message'] = 'Nothing to be done.'
            ret['out'] = False
            return ret

        if 'in_min' in op:
            shut(in_min=op['in_min'])
        elif 'at' in op:
            shut(at=op['at'])
        else:
            shut()
        ret['message'] = 'Successfully powered off/rebooted.'
        ret['out'] = True
    except Exception as exception:
        ret['message'] = \
            'Could not poweroff/reboot beacause "{0}"'.format(exception)
        ret['out'] = False
    return ret
Esempio n. 24
0
    def reboot_device(self, ip, hostname):
        # Reboots a device
        # Status dictionary for post-upgrade reporting
        statusDict = {}
        if Menu.upgrade_list == '':
            statusDict['Upgrade_List'] = 'Juniper-Upgrade_' + Menu.username
        else:
            statusDict['Upgrade_List'] = Menu.upgrade_list
        statusDict['Upgrade_Start'] = ''
        statusDict['Upgrade_Finish'] = '-'
        statusDict['IP'] = ip
        statusDict['Connected'] = 'N'
        statusDict['OS_installed'] = '-'
        statusDict['Rebooted'] = 'N'
        statusDict['IST_Confirm_Loaded'] = '-'
        statusDict['IST_Confirm_Rebooted'] = ''
        statusDict['Comments'] = ''

        # Start the logging
        now = datetime.datetime.now()
        date_time = now.strftime("%Y-%m-%d-%H%M")
        reboot_log = Menu.log_dir + "juniper-reboot-LOG_" + date_time + "_" + Menu.username + ".log"
        logging.basicConfig(filename=reboot_log,
                            level=logging.INFO,
                            format='%(asctime)s:%(name)s: %(message)s')
        logging.getLogger().name = ip
        print('Information logged in {0}'.format(reboot_log))

        # Display basic information
        self.do_log("Device: {0} ({1})".format(hostname, ip))
        now = datetime.datetime.now()
        formattime = now.strftime("%Y-%m-%d %H:%M")
        self.do_log("Timestamp: {0}".format(formattime))

        # Verify package exists before starting upgrade process
        dev = Device(ip, user=Menu.username, password=Menu.password)
        # Try to open a connection to the device
        try:
            self.do_log('\n')
            self.do_log(
                '------------------------- Opening connection to: {0} -------------------------\n'
                .format(ip))
            self.do_log('User: {0}'.format(Menu.username))
            dev.open()
        # If there is an error when opening the connection, display error and exit upgrade process
        except Exception as err:
            sys.stderr.write('Cannot connect to device: {0}\n'.format(err))
        else:
            # Record connection achieved
            statusDict['Connected'] = 'Y'

            # Increase the default RPC timeout to accommodate install operations
            dev.timeout = 600
            # Create an instance of SW
            sw = SW(dev)

            # Logging
            now = datetime.datetime.now()
            statusDict['Upgrade_Start'] = now.strftime("%Y-%m-%d %H:%M")
            self.do_log('Timestamp: {0}'.format(statusDict['Upgrade_Start']))
            self.do_log('Beginning reboot cycle, please be patient.')

            # Attempt to reboot
            try:
                rsp = sw.reboot()
                self.do_log(rsp)
            except Exception as err:
                msg = 'Unable to reboot system, {0}'.format(err)
                self.do_log(msg, level='error')
            else:
                # Record reboot
                statusDict['Rebooted'] = 'Y'

            # End the NETCONF session and close the connection
            dev.close()
            self.do_log('\n')
            self.do_log(
                '------------------------- Closed connection to: {0} -------------------------\n'
                .format(ip))

        return statusDict
Esempio n. 25
0
from jnpr.junos import Device
from jnpr.junos.utils.sw import SW

USER = "******"
PASSWD = "lab123"
DEVICE_IP = "10.254.0.41"


def update_progress(dev, report):
    print(report)


dev = Device(host=DEVICE_IP, user=USER, password=PASSWD)
dev.open()

sw = SW(dev)

ok = sw.install(package="/var/tmp/junos-vmx-x86-64-17.1R2.7.tgz",
                no_copy=True,
                progress=update_progress,
                validate=False)

print(ok)

sw.reboot()
Esempio n. 26
0
def do_junos_upgrade(router, cleanfsflag, device_address, device_username,
                     device_password, junos_version_for_upgrade,
                     current_re_only, copy_only):
    router.open()
    facts = dict((router.facts))
    router.close()
    current_re_model = None

    if str(facts['version']) == str(junos_version_for_upgrade):
        print(device_address, "already is running on junos version",
              junos_version_for_upgrade)
        return 0

    if 're0' in list(facts['current_re']):
        if dict(facts['RE0'])['model']:
            current_re_model = dict(facts['RE0'])['model']
        else:
            print("Script could not fetch Model of RE0 from", device_address,
                  "which is the current RE. Script will not upgrade",
                  device_address, "\n")
            return 1
        if not current_re_only:
            if facts['RE1']:
                if (str(facts['RE1']['model']) != str(current_re_model)):
                    current_re_only = True
                    print(
                        "Script is logged in to RE0 of", device_address,
                        "Either the script could not fetch the RE type of RE1 or the RE type of RE0 does not match RE1. Script will only upgrade RE0 on",
                        device_address, "\n")
                if (not current_re_only) and (str(facts['RE1']['status']) !=
                                              'OK'):
                    current_re_only = True
                    print(
                        "Script is logged in to RE0 of", device_address,
                        "Status of RE1 is not \'OK\'. Script will only upgrade RE0 on",
                        device_address, "\n")
                if (not current_re_only) and facts['version_RE1']:
                    if str(facts['version_RE1']) == junos_version_for_upgrade:
                        current_re_only = True
                        print("Script is logged in to RE0 of", device_address,
                              "RE1 is already running junos version",
                              junos_version_for_upgrade,
                              "Script will only upgrade RE0 on",
                              device_address, "\n")
                else:
                    current_re_only = True
                    print(
                        "Script is logged in to RE0 of", device_address,
                        "Script could not fetch version info from RE1. Script will only upgrade RE0 on",
                        device_address, "\n")

            else:
                current_re_only = True
                print(
                    "Script is logged in to RE0 of", device_address,
                    "Script could not fetch RE1 info. Script will only upgrade RE0 on",
                    device_address, "\n")

    elif 're1' in list(facts['current_re']):
        if dict(facts['RE1'])['model']:
            current_re_model = dict(facts['RE1'])['model']
        else:
            print("Script could not fetch Model of RE1 from", device_address,
                  "which is the current RE. Script will not upgrade",
                  device_address, "\n")
            return 1
        if not current_re_only:
            if facts['RE0']:
                if (str(facts['RE0']['model']) != str(current_re_model)):
                    current_re_only = True
                    print(
                        "Script is logged in to RE1 of", device_address,
                        "Either the script could not fetch the RE type of RE0 or the RE type of RE0 does not match RE1. Script will only upgrade RE1 on",
                        device_address, "\n")
                if (not current_re_only) and (str(facts['RE0']['status']) !=
                                              'OK'):
                    current_re_only = True
                    print(
                        "Script is logged in to RE1 of", device_address,
                        "Status of RE0 is not \'OK\'. Script will only upgrade RE1 on",
                        device_address, "\n")
                if (not current_re_only) and facts['version_RE0']:
                    if str(facts['version_RE0']) == junos_version_for_upgrade:
                        current_re_only = True
                        print("Script is logged in to RE1 of", device_address,
                              "RE0 is already running junos version",
                              junos_version_for_upgrade,
                              "Script will only upgrade RE1 on",
                              device_address, "\n")
                else:
                    if (not current_re_only):
                        current_re_only = True
                        print(
                            "Script is logged in to RE1 of", device_address,
                            "Script could not fetch version info from RE0. Script will only upgrade RE1 on",
                            device_address, "\n")

            else:
                current_re_only = True
                print(
                    "Script is logged in to RE1 of", device_address,
                    "Script could not fetch RE0 info. Script will only upgrade RE1 on",
                    device_address, "\n")

    else:
        print(
            "Script could not identify current RE Model. Script will not upgrade",
            device_address, "\n")
        return 1

    if not current_re_model:
        print(
            "Script could not identify current RE Model. Script will not upgrade",
            device_address, "\n")
        return 1

    version_year = re.search('^(\d*)\..*$', junos_version_for_upgrade).group(1)
    major_version = re.search('^(\d*\.\d).*$',
                              junos_version_for_upgrade).group(1)
    junos_name_format_type = None
    junos_name_format = None
    junos_image_name = None
    junos_image_location_format = None
    junos_image_path = None
    found_valid_image = False

    for format_map_key in junos_image_name_format_selector.keys():
        if (junos_image_name_format_selector[format_map_key]['from'] <=
                int(version_year) <=
                junos_image_name_format_selector[format_map_key]['to']):
            junos_name_format_type = format_map_key

    if junos_name_format_type is None:
        print("Couldn't fetch Junos name format type. Script will not upgrade",
              device_address)
        return 1

    put_version_in_format = re.compile('^(.*)(VERSION_NUMBER)(.*)$')
    put_version_in_image_location = re.compile(
        '^(.*)(MAJOR_VERSION_NUMBER)(.*)(VERSION_NUMBER)(.*)$')
    daily_image_format = re.compile('^(\d*\.\d)I\-(\d{8})\.(\d)\.(\d{4})$')
    junos_version_in_directory_path = junos_version_for_upgrade

    if daily_image_format.match(junos_version_for_upgrade):  # for daily image
        junos_version_in_directory_path = daily_image_format.search(
            junos_version_for_upgrade).group(2) + daily_image_format.search(
                junos_version_for_upgrade).group(
                    4) + '.' + daily_image_format.search(
                        junos_version_for_upgrade).group(3)

    print("Model of current RE in", device_address, "is:", current_re_model)

    try:
        junos_name_format = str(
            junos_image_name_format_map[junos_name_format_type]
            [current_re_model])
        junos_image_name = put_version_in_format.sub(
            r"\g<1>" + str(junos_version_for_upgrade) + r"\g<3>",
            junos_name_format)
        junos_image_location_format = junos_image_location_map[
            current_re_model]
        try:
            for image_path in list(junos_image_location_format):
                junos_image_path = put_version_in_image_location.sub(
                    r"\g<1>" + str(major_version) + r"\g<3>" +
                    str(junos_version_in_directory_path) + r"\g<5>",
                    image_path) + str(junos_image_name)
                if (Path(junos_image_path).is_file()):
                    print("Junos image for upgrading current RE in",
                          device_address, "is at: ", junos_image_path)
                    found_valid_image = True
                    break
        except:
            print(
                "Error in fetching image file location for,", device_address,
                "from image location format configuration. Please check if correct image location format is available in script configuration file for RE Type: ",
                current_re_model)
            return 1
    except:
        print(
            "Error in fetching image name for", device_address,
            "based on image name format configuration. Please check if correct image name format is available in script configuration file for RE Type: ",
            current_re_model)
        return 1

    if not found_valid_image or not junos_image_path:
        print("Error in finding suitable junos image to upgrade",
              device_address, "Script will not upgrade", device_address)
        return 1

    router.open()
    sw = SW(router)
    file_copy_status = 1
    is_vmhost_image = False
    local_checksum_string = None
    remote_checksum_string = None
    checksum_matches = False

    if ('vmhost' in junos_image_path):
        is_vmhost_image = True

    print("Checking whether the device", device_address,
          "already have the junos image file", junos_image_name,
          "in /var/tmp/ directory")

    if Path(junos_image_path + '.md5').is_file():
        remote_checksum_string = sw.remote_checksum('/var/tmp/' +
                                                    junos_image_name,
                                                    algorithm='md5')
        if remote_checksum_string:
            with open(junos_image_path + '.md5') as checksum_data:
                local_checksum_string = str(
                    checksum_data.readline()).split()[0].rstrip()
            if remote_checksum_string == local_checksum_string:
                checksum_matches = True
    elif Path(junos_image_path + '.sha1').is_file():
        remote_checksum_string = sw.remote_checksum('/var/tmp/' +
                                                    junos_image_name,
                                                    algorithm='sha1')
        if remote_checksum_string:
            with open(junos_image_path + '.sha1') as checksum_data:
                local_checksum_string = str(
                    checksum_data.readline()).split()[0].rstrip()
            if remote_checksum_string == local_checksum_string:
                checksum_matches = True
    elif Path(junos_image_path + '.sha256').is_file():
        remote_checksum_string = sw.remote_checksum('/var/tmp/' +
                                                    junos_image_name,
                                                    algorithm='sha256')
        if remote_checksum_string:
            with open(junos_image_path + '.sha256') as checksum_data:
                local_checksum_string = str(
                    checksum_data.readline()).split()[0].rstrip()
            if remote_checksum_string == local_checksum_string:
                checksum_matches = True
    else:
        remote_checksum_string = sw.remote_checksum('/var/tmp/' +
                                                    junos_image_name)
        if remote_checksum_string:
            local_checksum_string = sw.local_checksum(junos_image_path)
            if remote_checksum_string == local_checksum_string:
                checksum_matches = True

    if checksum_matches:
        print("Device already have the junos image file", junos_image_name,
              "in /var/tmp/ directory of", device_address,
              "Script will use this file to perform the upgrade.")
        file_copy_status = 0
    else:
        print(
            "The device", device_address, "do not have the junos image file",
            junos_image_name,
            "in /var/tmp/ directory. Script will copy the required junos image."
        )
        if Path(str(split_copy_path)).is_file():
            print("Script will now attempt to use splitcopy.py script to copy",
                  junos_image_path, "to", device_address)
            print("running command:", str(split_copy_path), junos_image_path,
                  device_username + "@" + device_address + ":/var/tmp/",
                  "--pwd", device_password)

            try:
                file_copy_status = subprocess.call([
                    str(split_copy_path), junos_image_path,
                    device_username + "@" + device_address + ":/var/tmp/",
                    "--pwd", device_password
                ],
                                                   stdout=sys.stdout,
                                                   stderr=subprocess.DEVNULL,
                                                   timeout=900)
            except Exception as e:
                file_copy_status = 1
                print("Attempt to copy the image to", device_address,
                      "using splitcopy utility failed.")
                print(str(e))

            if file_copy_status != 0:
                print(
                    "splitcopy couldn't copy the image to", device_address,
                    "\nScript will use junos pyEZ jnpr.junos.utls.sw.put() to copy image to device. This process will be slower."
                )
                try:
                    sw.put(junos_image_path, progress=True)
                    file_copy_status = 0
                except Exception as e:
                    print(str(e))
        else:
            print(
                "Scipt couldnt locate splitcopy utility. Script will use junos pyEZ jnpr.junos.utls.sw.put() to copy image to device. This process will be slower."
            )
            try:
                sw.put(junos_image_path, progress=True)
                file_copy_status = 0
            except Exception as e:
                print(str(e))

    if file_copy_status != 0:
        print(
            "Script could not copy the required junos image file to current RE of",
            device_address, "Upgrade will not be performed on", device_address)
        router.close()
        return 1

    if copy_only:
        print("Script successfully copied", junos_image_name,
              "to /var/tmp/ directory of", device_address)
        router.close()
        return 0

    try:
        installation_status = sw.install(package="/var/tmp/" +
                                         junos_image_name,
                                         no_copy=True,
                                         progress=True,
                                         vmhost=is_vmhost_image,
                                         cleanfs=cleanfsflag,
                                         all_re=not (current_re_only))

        if installation_status:
            print("Rebooting", device_address, "after junos upgrade")
            try:
                sw.reboot(all_re=not (current_re_only), vmhost=is_vmhost_image)
            except:
                pass  ## Pyez throws an exception after rebooting vmhost devices. This can be removed after it is fixed.
            router.close()
            wait_for_router_online(router, 300, device_address)
            router.open()
            if str(dict(router.facts)['version']) == str(
                    junos_version_for_upgrade):
                print(device_address, "was successfully upgraded to",
                      junos_version_for_upgrade)
                return 0
            else:
                print(
                    "Script attempted upgrading", device_address, "to",
                    junos_version_for_upgrade,
                    "and rebooted the device. But current version is still not the target version."
                )
                return 1
        else:
            print(
                "Script could not complete installation of new junos image in ",
                device_address)
            router.close()
            return 1

    except Exception as e:
        print("Script could not complete installation of new junos image in ",
              device_address)
        print(str(e))
        router.close()
        return 1
def main():
    dev = Device(host=hostname, user=junos_username, passwd=junos_password)
    # open a connection with the device and start a NETCONF session
    try:
        dev.open()
    except ConnectError as err:
        sys.exit("Unfortunately the target device is unreachable. Check connection parameters.")
    ######################################################################################
    #######################CONFIG LOAD STARTS HERE########################################
    ######################################################################################
    dev.bind(cu=Config)
    # Lock the configuration, load configuration changes, and commit
    print ("Locking the configuration")

    try:
        dev.cu.lock()
    except LockError as err:
        print ("Unable to lock configuration: {0}".format(err))
        dev.close()
        return

    print ("Loading configuration changes")
    try:
        dev.cu.load(path=conf_file, merge=True)
    except (ConfigLoadError, Exception) as err:
        print ("Unable to load configuration changes: {0}".format(err))
        print ("Unlocking the configuration")
        try:
                dev.cu.unlock()
        except UnlockError:
            print ("Unable to unlock configuration: {0}".format(err))
        dev.close()
        return

    print ("Committing the configuration")
    try:
        dev.cu.commit(comment='Loaded by example.')
    except CommitError as err:
        print ("Unable to commit configuration: {0}".format(err))
        print ("Unlocking the configuration")
        try:
            dev.cu.unlock()
        except UnlockError as err:
            print ("Unable to unlock configuration: {0}".format(err))
        dev.close()
        return

    print ("Unlocking the configuration")
    try:
        dev.cu.unlock()
    except UnlockError as err:
        print ("Unable to unlock configuration: {0}".format(err))
  ######################################################################################
  #######################UPGRADE PROCESS STARTS HERE####################################
  ######################################################################################
    type = (dev.facts["version"])
    sw = SW(dev)

    if type == "18.4R3-S2":
        print("Looks like your device is already on the latest firmware!.")

    elif type != "18.4R3-S2":
        print("Not on latest Junos version. Copying/installing latest Junos image to device. Please be patient.")
        try:
            ok = sw.install(package=package_srx,remote_path=srx_local,validate=False,progress=update_progress)
                
        except Exception as err:
            ok = False
            print("Unable to install software.")

        if ok == True:
            print("Software installation complete. Rebooting!")
            rsp = sw.reboot()
    else:   
        print("Unable to install software.")

    dev.close()
Esempio n. 28
0
def shutdown(**kwargs):
    """
    Shut down (power off) or reboot a device running Junos OS. This includes
    all Routing Engines in a Virtual Chassis or a dual Routing Engine system.

      .. note::
          One of ``shutdown`` or ``reboot`` must be set to ``True`` or no
          action will be taken.

    shutdown : False
      Set this to ``True`` if you want to shutdown the machine. This is a
      safety mechanism so that the user does not accidentally shutdown the
      junos device.

    reboot : False
      If ``True``, reboot instead of shutting down

    at
      Used when rebooting, to specify the date and time the reboot should take
      place. The value of this option must match the JunOS CLI reboot syntax.

    in_min
        Used when shutting down. Specify the delay (in minutes) before the
        device will be shut down.

    CLI Examples:

    .. code-block:: bash

        salt 'device_name' junos.shutdown reboot=True
        salt 'device_name' junos.shutdown shutdown=True in_min=10
        salt 'device_name' junos.shutdown shutdown=True
    """
    conn = __proxy__["junos.conn"]()
    ret = {}
    sw = SW(conn)

    op = {}
    if "__pub_arg" in kwargs:
        if kwargs["__pub_arg"]:
            if isinstance(kwargs["__pub_arg"][-1], dict):
                op.update(kwargs["__pub_arg"][-1])
    else:
        op.update(kwargs)
    if "shutdown" not in op and "reboot" not in op:
        ret["message"] = "Provide either one of the arguments: shutdown or reboot."
        ret["out"] = False
        return ret

    try:
        if "reboot" in op and op["reboot"]:
            shut = sw.reboot
        elif "shutdown" in op and op["shutdown"]:
            shut = sw.poweroff
        else:
            ret["message"] = "Nothing to be done."
            ret["out"] = False
            return ret

        if "in_min" in op:
            shut(in_min=op["in_min"])
        elif "at" in op:
            shut(at=op["at"])
        else:
            shut()
        ret["message"] = "Successfully powered off/rebooted."
        ret["out"] = True
    except Exception as exception:  # pylint: disable=broad-except
        ret["message"] = 'Could not poweroff/reboot beacause "{0}"'.format(
            exception)
        ret["out"] = False
    return ret
from yaml import load
from jnpr.junos.utils.sw import SW
from jnpr.junos import Device

f = open('inventory.yml', 'r')
devices_list = load(f.read())['devices_list']
f.close()

pkgs_list = [
    'network-agent-x86-32-18.2R1-S3.2-C1.tgz',
    'junos-openconfig-x86-32-0.0.0.10-1.tgz'
]

for pkg in pkgs_list:
    for item in devices_list:
        print 'adding the package ' + pkg + ' to the device ' + item[
            'device-id']
        device = Device(
            host=item['host'],
            user=item['authentication']['password']['username'],
            password=item['authentication']['password']['password'])
        device.open()
        sw = SW(device)
        sw.install(package=pkg,
                   validate=False,
                   no_copy=False,
                   progress=True,
                   remote_path="/var/home/jcluser")
        device.close()
Esempio n. 30
0
def main():

    # initialize logging
    logging.basicConfig(filename=logfile,
                        level=logging.INFO,
                        format='%(asctime)s:%(name)s: %(message)s')
    logging.getLogger().name = host
    logging.getLogger().addHandler(logging.StreamHandler())
    logging.info('Information logged in {0}'.format(logfile))

    # verify package1 exists
    if not (os.path.isfile(package1)):
        msg = 'Software package1 does not exist: {0}. '.format(package1)
        logging.error(msg)
        sys.exit()

    dev = Device(host=host, user=user, passwd=passwd)
    try:
        dev.open()
    except ConnectError as err:
        logging.error('Cannot connect to device: {0}\n'.format(err))
        return

    # Create an instance of SW
    sw = SW(dev)

    try:
        logging.info(
            'Starting the software upgrade process: {0}'.format(package1))
        ok = True
        #ok = sw.install(package=package1, remote_path=remote_path,progress=update_progress, validate=validate)

    except Exception as err:
        msg = 'Unable to install software, {0}'.format(err)
        logging.error(msg)
        ok = False

    if ok is True:
        logging.info('Software installation complete. Rebooting')
        rsp = sw.reboot()
        logging.info('Upgrade pending reboot cycle, please be patient.')
        logging.info(rsp)

    else:
        msg = 'Unable to install software, {0}'.format(ok)
        logging.error(msg)

#dev=None
#dev = Device(host=host, user=user, passwd=passwd)
# End the NETCONF session and close the connection
    time.sleep(20)
    rebootOK = False
    while not rebootOK:
        try:
            print("try open")
            time.sleep(15)
            rebootOK = True
            dev.open()

        except ConnectError as err:
            print("Not open")
            rebootOK = False

#"--------------firmware--------------"
# verify package2 exists
    if not (os.path.isfile(package2)):
        msg = 'Software package2 does not exist: {0}. '.format(package2)
        logging.error(msg)
        sys.exit()

    # Create an instance of SW
    sw = SW(dev)

    try:
        logging.info(
            'Starting the software upgrade process: {0}'.format(package2))
        #ok = True
        ok = sw.install(package=package2,
                        remote_path=remote_path,
                        progress=update_progress,
                        validate=validate)
    except Exception as err:
        msg = 'Unable to install software, {0}'.format(err)
        logging.error(msg)
        ok = False

    if ok is True:
        logging.info('Software installation complete.')
        dev.cli("request system firmware upgrade pic pic-slot 0 fpc-slot 1")

    else:
        msg = 'Unable to install software, {0}'.format(ok)
        logging.error(msg)

    time.sleep(20)
    rsp = sw.reboot()
    print("last reboot")

    time.sleep(20)
    rebootOK = False
    while not rebootOK:
        try:
            print("try open")
            time.sleep(15)
            rebootOK = True
            dev.open()

        except ConnectError as err:
            print("Not open")
            rebootOK = False

    #dev.timeout = 600

#dev.rpc.request_snapshot(slice='alternate')
#dev.cli("request system snapshot slice alternate")

    print "close device"
    dev.close()