Automation

Expand all | Collapse all

Python script to automount usb on Juniper EX Swicthes

Jump to Best Answer
  • 1.  Python script to automount usb on Juniper EX Swicthes

    Posted 01-27-2020 15:39

    Hello, i am trying to write a script that will mount a usb stick on the Juniper EX 2300/3400's. When I runst the script I gett he below error. Any help would be appreciated.

     

    root> op usb
    Traceback (most recent call last):
    File "/var/db/scripts/op/automountusb1.py", line 11, in <module>
    with StartShell(dev) as ss:
    File "../../../../../../../../src/dist/python-add-ons/junos-eznc/lib/jnpr/junos/utils/start_shell.py", line 170, in __enter__
    File "../../../../../../../../src/dist/python-add-ons/junos-eznc/lib/jnpr/junos/utils/start_shell.py", line 102, in open
    RuntimeError
    :
    StartShell requires user credentials
    error: op script failed: /var/db/scripts/op/automountusb1.py

     

    My python script.

     

    #!/usr/bin/env python2

    from jnpr.junos import Device
    from jnpr.junos.utils.start_shell import StartShell
    import commands

     

    MOUNT_DIR = "/var/tmp/usb"

     

    with Device() as dev: #= Device(host='localhost', user='root', password='H!ghM@rk!ng')
        with StartShell(dev) as ss:
            dev.open()
            print (ss.run('cli -c "start shell user root"'))
            print (ss.run('cli -c "camcontrol inquiry da1 -S"'))

     



  • 2.  RE: Python script to automount usb on Juniper EX Swicthes

     
    Posted 01-28-2020 00:45

    To execute the python script make sure we have the following in the system configuration

     

    set system scripts language python

     

    Also make sure we have the correct permission for the script file. 

     

    Hope this helps.

     

     



  • 3.  RE: Python script to automount usb on Juniper EX Swicthes
    Best Answer

     
    Posted 01-28-2020 01:10

    I believe this is what you are facing

     

    https://github.com/Juniper/py-junos-eznc/issues/908

     

    The start shell takes user credentials to make the connection. You might have to use the subprocess to achieve this.

     

     



  • 4.  RE: Python script to automount usb on Juniper EX Swicthes

    Posted 01-28-2020 08:00

    hank-you, that got me on the right path.



  • 5.  RE: Python script to automount usb on Juniper EX Swicthes

    Posted 01-28-2020 12:37

    Below is my working script, running into one last issue. When I run op usb m yes the usb gets mounted but i get the below error, any thoughts?

     

    ### Error ###

    root> op usb m yes
    ### Mounting USB ###


    ### USB Mounted ###
    Traceback (most recent call last):
    File "/var/db/scripts/op/automountusb1.py", line 115, in <module>
    main()
    File "/var/db/scripts/op/automountusb1.py", line 64, in main
    mount_msdosfs: /dev/da2s1:
    _p01 = Popen(["grep", _dev],stdin=_p0.stdout, stdout=None)
    File "../../../../../../../src/dist/python/Lib/subprocess.py", line 702, in __init__
    File "../../../../../../../src/dist/python/Lib/subprocess.py", line 1117, in _get_handles
    ValueError
    :
    I/O operation on closed file
    error: op script failed: /var/db/scripts/op/automountusb1.py

    {master:0}

     

    ### Python Script ###

     

    #!/usr/bin/env python2
    """
    Mounts or UnMounts USB stick

     

    Script takes a command line argument of m(mount) or u(un mount) and then attempts to
    locate the current USB stick and either mount or un mount the USB stick

     

    Args:
        (m): mounts the USB stick
        (u): unmounts the USB stick

     

    Returns:
        (NA)

     

    Exceptions:
        (NA):

     

    Created By:
        (Jason Mann)
    """

     

    ################################################
    from subprocess import Popen, PIPE
    import re #Regular Expressions
    import argparse
    ################################################


    def main():
        _arguments = {'m': 'Enter yes to mount the usb stick', 'u': 'Enter yes to unmount the usb stick'}
        _parser = argparse.ArgumentParser(description='Script will mount or unmount USB stick.')

       

        #Define the arguments accepted by parser
        # which use the key names defined in the arguments dictionary
        for _key in _arguments:
            _parser.add_argument(('-' + _key), required=False, help=_arguments[_key])

        _args = _parser.parse_args()

     

        # Dont want user to enter yes for both arguments since neither is mandatory
        if _args.m == "yes" and _args.u == "yes":
            print ("")
            print ("### Can not have both arguments set to yes ###")
            print ("")

     

        # Mount the USB
        if _args.m == "yes" and _args.u == "no" or _args.m == "yes" and _args.u is None:
            print ("")
            print ("")
            print ("### Mounting USB ###")

     

            # FreeBSD shell command that will list attached devices
            _p0 = Popen(["camcontrol", "devlist"], stdout=PIPE)

     

            # List will be used to find the FreeBSD dev device
            _listofnum = ["1","2","3","4","5"]
            _found = False

     

            # Loop through the list to find the dev device, usually will be 1 but added up to 5
            # just in case
            for _num in _listofnum:

                # FreeBSD shell command that greps the output from the _po command ran
                # have to run them this way to do the pipe command
                _dev = "da" + _num
                _p01 = Popen(["grep", _dev],stdin=_p0.stdout, stdout=None)
                _p01_1 = _p01.communicate()[0]
                _p0.stdout.close()

          

                if _p01_1 != "": # device found
                    # FreeBSD shell command that will retrieve the sn of the device
                    # Doing this to verify that the dev used was correct
                    _p1 = Popen(["camcontrol", "inquiry", _dev, "-S"], stdout=None)
                    _p2 = _p1.communicate()[0]

     

                    # FreeBSD shell command that will mount the USB stick
                    _devmnt = "/dev/da" + _num + "s1"
                    _p3 = Popen(["mount_msdosfs", _devmnt, "/var/tmp/usb"],stdout=None)

     

                    print ("")
                    print ("")
                    print ("### USB Mounted ###")
                    _found = True

            if _found == False:
                print ("")
                print ("")
                print ("### USB not Found ###")
                print ("")

        else:

            print ("")
            print ("")
            print ("### Invalid arguments or argument values ###")
            print ("")
            print ("")

     

         

        # UnMount the USB
        if _args.u == "yes" and _args.m == "no" or _args.u == "yes" and _args.m is None:
            print ("")
            print ("")
            print ("### Unmounting USB ###")

             

            # We use /var/tmp/usb as the standard mount point for usb sticks

            _p2 = Popen(["umount", "/var/tmp/usb"],stdout=None)

           

            print ("")
            print ("### USB Unmounted ###")

        else:
            print ("")
            print ("")
            print ("### Invalid arguments or argument values ###")
            print ("")
            print ("")

     

    if __name__ == "__main__":
        main()



  • 6.  RE: Python script to automount usb on Juniper EX Swicthes

     
    Posted 01-28-2020 20:19

    I believe the error is I/O operation and with subprocess module itself. You may try with subprocess32 on python3 as we are running the python on BSD platform.