Ejemplo n.º 1
0
def get_rsi(ip_addr):
    dev = call_dev(ip_addr)

    myprint(ip_addr + ' : accessing... <br>')
    try:
        dev.open(gather_facts=False)
    except Exception as err:
        return

    myprint(ip_addr + ' : creating RSI file...<br>')
    ts = datetime.datetime.today().strftime('%Y%m%d%H%M')
    RSI_File = 'RSI_' + ts + '.txt'
    RSI_File2 = config.Temp_Dir + RSI_File
    myprint(RSI_File + '<br>')
    myprint(RSI_File2 + '<br>')
    opcmd = 'op url ' + config.RSI_Slax + ' rsi-file "' + RSI_File2 + '"'
    myprint(opcmd + '<br>')
    dev.timeout = 120
    sw = dev.cli(opcmd, warning=False)

    myprint(ip_addr + ' : uploading RSI file to this server...<br>')
    RSI_File3 = ip_addr + '_' + RSI_File
    cu = FS(dev)
    cu.cp(RSI_File2, config.FileSrv + RSI_File3)

    #    print ip_addr, " : Finished<br>"
    str1 = ip_addr + ' : Complete creating RSI file. Click <a href="' + config.HTTP_RSI_Dir + RSI_File3 + '">here</a> to download.<br>'
    myprint(str1)

    dev.close()
Ejemplo n.º 2
0
def facts_domain(junos, facts):
    """
    The following facts are required:
        facts['hostname']

    The following facts are assigned:
        facts['domain']
        facts['fqdn']
    """

    try:
        domain_filter_xml = E("configuration", E("system", E("domain-name")))
        domain = junos.rpc.get_config(filter_xml=domain_filter_xml,
                                      options=INHERIT)
        domain_name = domain.xpath(".//domain-name")
        if len(domain_name) > 0:
            facts["domain"] = domain_name[0].text
            facts["fqdn"] = facts["hostname"] + "." + facts["domain"]
            return
    except RpcError:
        pass

    fs = FS(junos)
    file_content = fs.cat("/etc/resolv.conf") or fs.cat("/var/etc/resolv.conf")
    words = file_content.split() if file_content is not None else ""
    if "domain" not in words:
        facts["domain"] = None
        facts["fqdn"] = facts["hostname"]
    else:
        idx = words.index("domain") + 1
        facts["domain"] = words[idx]
        facts["fqdn"] = facts["hostname"] + "." + facts["domain"]
Ejemplo n.º 3
0
def facts_domain(junos, facts):
    """
    The following facts are required:
        facts['hostname']

    The following facts are assigned:
        facts['domain']
        facts['fqdn']
    """

    try:
        domain_filter_xml = E('configuration', E('system', E('domain-name')))
        domain = junos.rpc.get_config(filter_xml=domain_filter_xml,
                                      options=INHERIT)
        domain_name = domain.xpath('.//domain-name')
        if len(domain_name) > 0:
            facts['domain'] = domain_name[0].text
            facts['fqdn'] = facts['hostname'] + '.' + facts['domain']
            return
    except RpcError:
        pass

    fs = FS(junos)
    file_content = fs.cat('/etc/resolv.conf') or fs.cat('/var/etc/resolv.conf')
    words = file_content.split() if file_content is not None else ''
    if 'domain' not in words:
        facts['domain'] = None
        facts['fqdn'] = facts['hostname']
    else:
        idx = words.index('domain') + 1
        facts['domain'] = words[idx]
        facts['fqdn'] = facts['hostname'] + '.' + facts['domain']
Ejemplo n.º 4
0
def main ():
    parser = argparse.ArgumentParser(add_help=True)
    parser.add_argument("-i", action="store",
                    help="IP Address")
    parser.add_argument("-u", action="store",
                    help="user")
    parser.add_argument("-p", action="store",
                    help="password")

    args = parser.parse_args()

    ip_address = None
    user = None
    password = None

    if args.i:
        ip_address = args.i
    if args.u:
        user = args.u
    if args.p:
        password= args.p
    
    dev = Device(host = ip_address, user = user, password=password)
    dev.open(gather_facts = False)
    fs = FS(dev)
    myfiles = fs.ls('/var/log').get('files')
    for key in myfiles:
        if key.startswith('mplsstats'):
             with SCP(dev, progress=True) as scp:
                 scp.get("/var/log/%s" % key)
    dev.close()
Ejemplo n.º 5
0
 def setUp(self, mock_connect):
     mock_connect.side_effect = self._mock_manager
     self.dev = Device(host='1.1.1.1',
                       user='******',
                       password='******',
                       gather_facts=False)
     self.dev.open()
     self.fs = FS(self.dev)
Ejemplo n.º 6
0
 def setUp(self, mock_connect):
     mock_connect.side_effect = self._mock_manager
     self.dev = Device(host="1.1.1.1",
                       user="******",
                       password="******",
                       gather_facts=False)
     self.dev.open()
     self.fs = FS(self.dev)
Ejemplo n.º 7
0
def check_directory_usage(port):

    with Device(host=host, user=USER, passwd=PASSWD, mode="telnet",
                port=port) as dev:
        fs = FS(dev)
        print("Checking %s: " % port, )
        print(fs.directory_usage(DIRECTORY))
        facts = dev.facts["hostname"] + " " + dev.facts["version"]
        isis = dev.cli("show configuration protocols isis | display set")
        out.write(facts)
        out.write(isis)
Ejemplo n.º 8
0
 def inventory(self):
     """
     Returns dictionary of file listing information for current and rollback
     Junos install packages. This information comes from the /packages
     directory.
     """
     from jnpr.junos.utils.fs import FS
     fs = FS(self.dev)
     pkgs = fs.ls('/packages')
     return dict(current=pkgs['files'].get('junos'),
                 rollback=pkgs['files'].get('junos.old'))
def check_directory_usage(host):  # (3)
    try:
        with Device(host=host, user=USER, password=PASSWD) as dev:
            fs = FS(dev)  # (4)
            print("Checking %s: " % host, end="")
            print(fs.directory_usage(DIRECTORY))  # (5)
    except ConnectRefusedError:  # (6)
        print("%s: Error - Device connection refused!" % host)
    except ConnectTimeoutError:
        print("%s: Error - Device connection timed out!" % host)
    except ConnectAuthError:
        print("%s: Error - Authentication failure!" % host)
Ejemplo n.º 10
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)
Ejemplo n.º 11
0
def check_directory_usage(host):
    try:
        with Device(host=host, user=USER, passwd=PASSWD) as dev:
            fs = FS(dev)
            print("Checking %s:" % host, end="")
            #print("Checking {}:".format{host}, end="")
            print(fs.directory_usage(DIRECTORY))
    except ConnectRefusedError:
        print("{}: Error - Device connection refused!".format(host))
    except ConnectTimeoutError:
        print("%s: Error - Device connection time out!" % host)
    except ConnectAuthError:
        print("%s: Error - Authentication failure!" % host)
Ejemplo n.º 12
0
    def inventory(self):
        """
        Returns dictionary of file listing information for current and rollback
        Junos install packages. This information comes from the /packages
        directory.

        .. warning:: Experimental method; may not work on all platforms.  If
                     you find this not working, please report issue.
        """
        from jnpr.junos.utils.fs import FS
        fs = FS(self.dev)
        pkgs = fs.ls('/packages')
        return dict(current=pkgs['files'].get('junos'),
                    rollback=pkgs['files'].get('junos.old'))
Ejemplo n.º 13
0
def get_logs(equipment):
    try:
        print("Compressing /var/log...")
        fileSystem = FS(equipment)
        fileSystem.tgz("/var/log/*",
                       "/var/tmp/" + current_date + "_py_varlog.tgz")
        print(
            "Copying log files down and removing the .tgz that was created...")
        with SCP(equipment, progress=True) as scp:
            scp.get(f"/var/tmp/" + current_date + "_py_varlog.tgz",
                    full_file + "_" + current_date + "_varlog.tgz")
        print("\nRemoving that var/log file\n")
        fileSystem.rm("/var/tmp/*_py_varlog.tgz")
    except Exception as err:
        missedEquipment[equipment] = "Error getting logs - " + str(err)
Ejemplo n.º 14
0
def get_facts(device):
    """
    Gathers domain facts from the configuration or /etc/resolv.conf.
    """
    domain_config = """
        <configuration>
            <system>
                <domain-name/>
             </system>
        </configuration>
    """
    domain = None
    fqdn = None
    # Try to read the domain-name from the config.
    # This might fail due to lack of permissions.
    try:
        rsp = device.rpc.get_config(filter_xml=etree.XML(domain_config),
                                    options={
                                        'database': 'committed',
                                        'inherit': 'inherit',
                                        'commit-scripts': 'apply',
                                    })
        domain = rsp.findtext('.//domain-name')
    # Ignore if user can't view the configuration.
    except PermissionError:
        pass

    # Try to read the domain from the resolv.conf file. This only requires
    # view permissions.
    if domain is None:
        fs = FS(device)
        file_content = (fs.cat('/etc/resolv.conf')
                        or fs.cat('/var/etc/resolv.conf'))
        words = file_content.split() if file_content is not None else []
        if 'domain' in words:
            idx = words.index('domain') + 1
            domain = words[idx]

    # Set the fqdn
    fqdn = device.facts['hostname']
    if fqdn is not None and domain is not None:
        fqdn = fqdn + '.' + domain

    return {
        'domain': domain,
        'fqdn': fqdn,
    }
Ejemplo n.º 15
0
def facts_domain(junos, facts):
    """
    The following facts are required:
        facts['hostname']

    The following facts are assigned:
        facts['domain']
        facts['fqdn']
    """
    fs = FS(junos)
    words = fs.cat('/etc/resolv.conf').split()
    if 'domain' not in words:
        facts['domain'] = None
        facts['fqdn'] = facts['hostname']
    else:
        idx = words.index('domain') + 1
        facts['domain'] = words[idx]
        facts['fqdn'] = facts['hostname'] + '.' + facts['domain']
Ejemplo n.º 16
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()
Ejemplo n.º 17
0
def get_rsi(equipment):
    try:
        print(
            "Gathering RSI...(This takes a bit - give it time. Timeout is 10 minutes.)"
        )
        ss = StartShell(equipment)
        ss.open()
        ss.run('cli request support information \\| save /var/tmp/' +
               current_date + '_py_rsi.txt',
               this="%",
               timeout=600)
        print("RSI Done, copying it and deleting it...\n")
        ss.close()
        with SCP(equipment, progress=True) as scp:
            scp.get('/var/tmp/' + current_date + "_py_rsi.txt",
                    full_file + "_" + current_date + "_rsi.txt")
        fileSystem = FS(equipment)
        fileSystem.rm('/var/tmp/*_py_rsi.txt')
    except Exception as err:
        missedEquipment[equipment] = "Error getting RSI - " + str(err)
Ejemplo n.º 18
0
with open(filename_snap) as f:
    for line in f:
        if re.search('Input/output error', line):
            print "-> (e) Device has Input/output error.Aborting snapshot!"
            log("-> (e) Device has Input/output error.Aborting snapshot!")
            close()
            sys.exit(1)

text_file_snap.close()

# request system storage cleanup #

print "-> Performing system storage cleanup, please be patient"

fs = FS(j_device)
fs.storage_cleanup()

# Disables traceoptions + syslog #

print "-> Disabling syslog + traceoptions (when enabled)"
my_commit(disable_cmds, j_device)

# Take a snapshot #

print "-> Snapshoting the device.."

try:
    rsp = j_device.rpc.request_snapshot(slice='alternate', dev_timeout=600)
except Exception as err:
    print "--> (e) Error when snapshoting the device!", err
Ejemplo n.º 19
0
def save_data(dev, step, **options):
    from jnpr.junos.utils.fs import FS
    from jnpr.junos.utils.start_shell import StartShell
    if not dev.connected:
        reconnect = reconnect_dev(dev, 2)
        if not reconnect:
            logging.info("Connection Failed to {}\n".format(dev.hostname))
            return
    if options.has_key('script_name'):
        script_name = options['script_name']
    else:
        script_name = False
    if options.has_key('rsi'):
        rsi = True
        if options['rsi'] == 'brief':
            brief = True
        else:
            brief = False
    else:
        rsi = False
    if options.has_key('folder'):
        dst_dir = options['folder']
    else:
        dst_dir = '/var/tmp'
    if options.has_key('save_config'):
        save_config = options['save_config']
    else:
        save_config = False
    # Start Shell
    dev_shell = StartShell(dev)
    dev_shell.open()
    # Get RSI
    if rsi:
        logging.info(
            'Running "request support information", this may take a while')
        if brief:
            rsi_cli = dev_shell.run(
                'cli -c "request support information brief | save {}/{}_rsi.txt"'
                .format(dst_dir, step))
        else:
            rsi_cli = dev_shell.run(
                'cli -c "request support information | save {}/{}_rsi.txt"'.
                format(dst_dir, step))
    # Run OP Script
    if script_name:
        logging.info("Running op script: '{}' ... ".format(script_name))
        op_script = dev_shell.run('cli -c "op {} | save {}/{}_{}.txt"'.format(
            script_name, dst_dir, step, script_name))
    # Save Configuration
    if save_config:
        logging.info("Saving Configuration backup")
        cfg = dev_shell.run(
            'cli -c "show configuration | save {}/{}_backup_config.txt"'.
            format(dst_dir, step))
    dev_shell.close()
    logging.info('Verifying stored files')
    dev_fs = FS(dev)
    tmp_list = dev_fs.ls(dst_dir)
    if rsi:
        if tmp_list['files'].has_key('{}_rsi.txt'.format(step)):
            logging.info("Compressing RSI")
            dev_fs.tgz(
                '{}/{}_rsi.txt'.format(dst_dir, step),
                '{}/{}_Upgrade-MOP-support-information.tgz'.format(
                    dst_dir, step))
            dev_fs.rm('{}/{}_rsi.txt'.format(dst_dir, step))
            if tmp_list['files'].has_key(
                    '{}_Upgrade-MOP-support-information.tgz'.format(step)):
                logging.info("RSI file saved in {}".format(dst_dir))
                rsi_complete = True
        else:
            logging.info("RSI collection did not complete in time\n")
    if save_config:
        if tmp_list['files'].has_key('{}_backup_config.txt'.format(step)):
            config_saved = True
            logging.info(
                "Backup configuration saved to {}/{}_backup_config.txt".format(
                    dst_dir, step))
        else:
            logging.info("Failed to save backup config")
    if script_name:
        if tmp_list['files'].has_key('{}_{}.txt'.format(step, script_name)):
            op_complete = True
            logging.info("OP {} script output saved in {}".format(
                script_name, dst_dir))
        else:
            logging.info("OP {} script did not complete Successfully".format(
                script_name))
Ejemplo n.º 20
0
from jnpr.junos import Device
from jnpr.junos.utils.config import Config
from jnpr.junos.utils.fs import FS
from pprint import pprint
import sys

dev = Device('host', user='******', password='******')

dev.open()

fs = FS(dev)

pprint(fs.ls(path="/var/tmp/", brief=True))

print fs.pwd()
Ejemplo n.º 21
0
             user="******",
             password="******",
             gather_facts=False)
dev.open()
print("Connection successfully...")

print("\n------ FILE CREATION")
print("Starting shell for creating RSI...")
ss = StartShell(dev)
ss.open()
ss.run('cli -c "request support information | save /var/tmp/pyez_rsi.txt"')
print("RSI done...")
ss.close()

# Compress /var/log/ to /var/tmp/pyez_varlog.tgz
fileSystem = FS(dev)
fileSystem.tgz("/var/log/*", "/var/tmp/pyez_varlog.tgz")
print("/var/log-compressed...")

# Get file system information
statRsi = fileSystem.stat("/var/tmp/pyez_rsi.txt")
statLogs = fileSystem.stat("/var/tmp/pyez_varlog.tgz")

# Transfering files via SCP
print("\n------ Transfering files")

# Get RSI
if statRsi['size'] is not None:
    print("File: /var/tmp/pyez_rsi.txt - Size: " +
          (str(sizeof_fmt(statRsi['size']))))
    askForTransferRsi = input("Do you want to transfer the RSI? (Yes, No)")