VirtualBox

Changeset 28716 in vbox


Ignore:
Timestamp:
Apr 25, 2010 8:11:35 PM (15 years ago)
Author:
vboxsync
Message:

VBoxShell: colors, shared folders, finding in logs

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/VBox/Frontends/VBoxShell/vboxshell.py

    r28679 r28716  
    136136       print "onGuestPropertyChange: %s: %s=%s" %(id, name, newValue)
    137137
    138 g_hasreadline = 1
     138g_hasreadline = True
    139139try:
    140140    import readline
    141141    import rlcompleter
    142142except:
    143     g_hasreadline = 0
    144 
     143    g_hasreadline = False
     144
     145
     146g_hascolors = True
     147term_colors = {
     148    'red':'\033[31m',
     149    'blue':'\033[94m',
     150    'green':'\033[92m',
     151    'yellow':'\033[93m',
     152    'magenta':'\033[35m'
     153    }
     154def colored(str,color):
     155    if not g_hascolors:
     156        return str
     157    global term_colors
     158    col = term_colors.get(color,None)
     159    if col:
     160        return col+str+'\033[0m'
     161    else:
     162        return str
    145163
    146164if g_hasreadline:
     
    189207                    matches.append(word)
    190208        except Exception,e:
    191             traceback.print_exc()
    192             print e
     209            printErr(e)
     210            if g_verbose:
     211                traceback.print_exc()
    193212
    194213        return matches
     
    207226  readline.set_completer_delims(re.sub("[\\.]", "", delims)) # remove some of the delimiters
    208227  # OSX need it
     228  readline.parse_and_bind("set editing-mode emacs")
    209229  if platform.system() == 'Darwin':
     230      # see http://www.certif.com/spec_help/readline.html
    210231      readline.parse_and_bind ("bind ^I rl_complete")
     232      readline.parse_and_bind ("bind ^W ed-delete-prev-word")
     233      # Doesn't work well
     234      # readline.parse_and_bind ("bind ^R em-inc-search-prev")
    211235  readline.parse_and_bind("tab: complete")
    212236
    213 g_verbose = True
     237
     238g_verbose = False
    214239
    215240def split_no_quotes(s):
     
    219244    try:
    220245        while not p.completed:
    221             print "%d %%\r" %(p.percent),
     246            print "%s %%\r" %(colored(str(p.percent),'red')),
    222247            sys.stdout.flush()
    223248            p.waitForCompletion(wait)
     
    231256        return 0
    232257
     258def printErr(ctx,e):
     259     print colored(str(e), 'red')
     260
    233261def reportError(ctx,progress):
    234262    ei = progress.errorInfo
    235263    if ei:
    236         print "Error in %s: %s" %(ei.component, ei.text)
     264        print colored("Error in %s: %s" %(ei.component, ei.text), 'red')
     265
     266def colCat(ctx,str):
     267    return colored(str, 'magenta')
     268
     269def colVm(ctx,vm):
     270    return colored(vm, 'blue')
    237271
    238272def createVm(ctx,name,kind,base):
     
    272306            perf.setup(['*'], [mach], 10, 15)
    273307          except Exception,e:
    274             print e
     308            printErr(ctx, e)
    275309            if g_verbose:
    276310                traceback.print_exc()
     
    306340def asState(var):
    307341    if var:
    308         return 'on'
    309     else:
    310         return 'off'
     342        return colored('on', 'green')
     343    else:
     344        return colored('off', 'green')
    311345
    312346def asFlag(var):
     
    457491
    458492def printHostUsbDev(ctx,ud):
    459     print "  %s: %s (vendorId=%d productId=%d serial=%s) %s" %(ud.id, ud.product, ud.vendorId, ud.productId, ud.serialNumber,getUSBStateString(ud.state))
     493    print "  %s: %s (vendorId=%d productId=%d serial=%s) %s" %(ud.id, colored(ud.product,'blue'), ud.vendorId, ud.productId, ud.serialNumber,asEnumElem(ctx, 'USBDeviceState', ud.state))
    460494
    461495def printUsbDev(ctx,ud):
    462     print "  %s: %s (vendorId=%d productId=%d serial=%s)" %(ud.id, ud.product, ud.vendorId, ud.productId, ud.serialNumber)
     496    print "  %s: %s (vendorId=%d productId=%d serial=%s)" %(ud.id,  colored(ud.product,'blue'), ud.vendorId, ud.productId, ud.serialNumber)
    463497
    464498def printSf(ctx,sf):
    465     print "name=%s host=%s %s %s" %(sf.name, sf.hostPath, cond(sf.accessible, "accessible", "not accessible"), cond(sf.writable, "writable", "read-only"))
     499    print "    name=%s host=%s %s %s" %(sf.name, sf.hostPath, cond(sf.accessible, "accessible", "not accessible"), cond(sf.writable, "writable", "read-only"))
    466500
    467501def ginfo(ctx,console, args):
     
    497531        progress = vb.openExistingSession(session, uuid)
    498532    except Exception,e:
    499         print "Session to '%s' not open: %s" %(mach.name,e)
     533        printErr(ctx, "Session to '%s' not open: %s" %(mach.name,str(e)))
    500534        if g_verbose:
    501535            traceback.print_exc()
     
    530564        ops[cmd]()
    531565    except Exception, e:
    532         print 'failed: ',e
     566        printErr(ctx,e)
    533567        if g_verbose:
    534568            traceback.print_exc()
     
    543577         cmd(ctx, mach, args)
    544578    except Exception, e:
    545         print 'failed: ',e
     579        printErr(ctx,e)
    546580        if g_verbose:
    547581            traceback.print_exc()
     
    579613    else:
    580614        spec = ""
    581     print "    %s: %s%s" %(cmd,h,spec)
     615    print "    %s: %s%s" %(colored(cmd,'blue'),h,spec)
    582616
    583617def helpCmd(ctx, args):
     
    601635    for e in all.keys():
    602636        if str(elem) == str(all[e]):
    603             return e
    604     return "<unknown>"
     637            return colored(e, 'green')
     638    return colored("<unknown>", 'green')
    605639
    606640def enumFromString(ctx,enum,str):
     
    614648        else:
    615649            tele = "    "
    616         print "%sMachine '%s' [%s], state=%s" %(tele,m.name,m.id,asEnumElem(ctx,"SessionState", m.sessionState))
     650        print "%sMachine '%s' [%s], state=%s" %(tele,colVm(ctx,m.name),m.id,asEnumElem(ctx,"SessionState", m.sessionState))
    617651    return 0
    618652
     
    626660    os = ctx['vb'].getGuestOSType(mach.OSTypeId)
    627661    print " One can use setvar <mach> <var> <value> to change variable, using name in []."
    628     print "  Name [name]: %s" %(mach.name)
     662    print "  Name [name]: %s" %(colVm(ctx,mach.name))
    629663    print "  Description [description]: %s" %(mach.description)
    630664    print "  ID [n/a]: %s" %(mach.id)
     
    671705    if controllers:
    672706        print
    673         print "  Controllers:"
     707        print colCat(ctx,"  Controllers:")
    674708    for controller in controllers:
    675709        print "    '%s': bus %s type %s" % (controller.name, asEnumElem(ctx,"StorageBus", controller.bus), asEnumElem(ctx,"StorageControllerType", controller.controllerType))
     
    678712    if attaches:
    679713        print
    680         print "  Mediums:"
     714        print colCat(ctx,"  Mediums:")
    681715    for a in attaches:
    682716        print "   Controller: '%s' port/device: %d:%d type: %s (%s):" % (a.controller, a.port, a.device, asEnumElem(ctx,"DeviceType", a.type), a.type)
     
    712746                    print "    Virtual image at %s" %(m.location)
    713747                    print "    Size: %s" %(m.size)
     748
     749    print colCat(ctx,"   Shared folders:")
     750    for sf in ctx['global'].getArray(mach, 'sharedFolders'):
     751        printSf(ctx,sf)
    714752
    715753    return 0
     
    10591097    return 0
    10601098
    1061 def getUSBStateString(state):
    1062     if state == 0:
    1063         return "NotSupported"
    1064     elif state == 1:
    1065         return "Unavailable"
    1066     elif state == 2:
    1067         return "Busy"
    1068     elif state == 3:
    1069         return "Available"
    1070     elif state == 4:
    1071         return "Held"
    1072     elif state == 5:
    1073         return "Captured"
    1074     else:
    1075         return "Unknown"
     1099def colorsCmd(ctx, args):
     1100    global g_hascolors
     1101    g_hascolors = not g_hascolors
     1102    return 0
    10761103
    10771104def hostCmd(ctx, args):
    1078    host = ctx['vb'].host
     1105   vb = ctx['vb']
     1106   print "VirtualBox version %s" %(vb.version)
     1107   #print "Global shared folders:"
     1108   #for ud in ctx['global'].getArray(vb, 'sharedFolders'):
     1109   #    printSf(ctx,sf)
     1110   host = vb.host
    10791111   cnt = host.processorCount
    1080    print "Processors available/online: %d/%d " %(cnt,host.processorOnlineCount)
     1112   print colCat(ctx,"Processors:")
     1113   print "  available/online: %d/%d " %(cnt,host.processorOnlineCount)
    10811114   for i in range(0,cnt):
    1082       print "Processor #%d speed: %dMHz %s" %(i,host.getProcessorSpeed(i), host.getProcessorDescription(i))
    1083 
    1084    print "RAM: %dM (free %dM)" %(host.memorySize, host.memoryAvailable)
    1085    print "OS: %s (%s)" %(host.operatingSystem, host.OSVersion)
     1115       print "  processor #%d speed: %dMHz %s" %(i,host.getProcessorSpeed(i), host.getProcessorDescription(i))
     1116
     1117   print colCat(ctx, "RAM:")
     1118   print "  %dM (free %dM)" %(host.memorySize, host.memoryAvailable)
     1119   print colCat(ctx,"OS:");
     1120   print "  %s (%s)" %(host.operatingSystem, host.OSVersion)
    10861121   if host.Acceleration3DAvailable:
    1087        print "3D acceleration available"
     1122       print colCat(ctx,"3D acceleration available")
    10881123   else:
    1089        print "3D acceleration NOT available"
    1090 
    1091    print "Network interfaces:"
     1124       print colCat(ctx,"3D acceleration NOT available")
     1125
     1126   print colCat(ctx,"Network interfaces:")
    10921127   for ni in ctx['global'].getArray(host, 'networkInterfaces'):
    10931128       print "  %s (%s)" %(ni.name, ni.IPAddress)
    10941129
    1095    print "DVD drives:"
     1130   print colCat(ctx,"DVD drives:")
    10961131   for dd in ctx['global'].getArray(host, 'DVDDrives'):
    10971132       print "  %s - %s" %(dd.name, dd.description)
    10981133
    1099    print "Floppy drives:"
     1134   print colCat(ctx,"Floppy drives:")
    11001135   for dd in ctx['global'].getArray(host, 'floppyDrives'):
    11011136       print "  %s - %s" %(dd.name, dd.description)
    11021137
    1103    print "USB devices:"
     1138   print colCat(ctx,"USB devices:")
    11041139   for ud in ctx['global'].getArray(host, 'USBDevices'):
    11051140       printHostUsbDev(ctx,ud)
     
    11831218def showLogCmd(ctx, args):
    11841219    if (len(args) < 2):
    1185         print "usage: showLog <vm> <num>"
    1186         return 0
    1187     mach = argsToMach(ctx,args)
    1188     if mach == None:
    1189         return 0
    1190 
    1191     log = 0;
     1220        print "usage: showLog vm <num>"
     1221        return 0
     1222    mach = argsToMach(ctx,args)
     1223    if mach == None:
     1224        return 0
     1225
     1226    log = 0
    11921227    if (len(args) > 2):
    1193        log  = args[2];
    1194 
    1195     uOffset = 0;
     1228       log  = args[2]
     1229
     1230    uOffset = 0
    11961231    while True:
    1197         data = mach.readLog(log, uOffset, 1024*1024)
     1232        data = mach.readLog(log, uOffset, 4096)
    11981233        if (len(data) == 0):
    11991234            break
     
    12041239    return 0
    12051240
     1241def findLogCmd(ctx, args):
     1242    if (len(args) < 3):
     1243        print "usage: findLog vm pattern <num>"
     1244        return 0
     1245    mach = argsToMach(ctx,args)
     1246    if mach == None:
     1247        return 0
     1248
     1249    log = 0
     1250    if (len(args) > 3):
     1251       log  = args[3]
     1252
     1253    pattern = args[2]
     1254    uOffset = 0
     1255    while True:
     1256        # to reduce line splits on buffer boundary
     1257        data = mach.readLog(log, uOffset, 512*1024)
     1258        if (len(data) == 0):
     1259            break
     1260        d = str(data).split("\n")
     1261        for s in d:
     1262            m = re.findall(pattern, s)
     1263            if len(m) > 0:
     1264                for mt in m:
     1265                    s = s.replace(mt, colored(mt,'red'))
     1266                print s
     1267        uOffset += len(data)
     1268
     1269    return 0
     1270
    12061271def evalCmd(ctx, args):
    12071272   expr = ' '.join(args[1:])
     
    12091274        exec expr
    12101275   except Exception, e:
    1211         print 'failed: ',e
     1276        printErr(ctx,e)
    12121277        if g_verbose:
    12131278            traceback.print_exc()
     
    12361301            if done != 0: break
    12371302    except Exception,e:
    1238         print "error:",e
     1303        printErr(ctx,e)
    12391304        if g_verbose:
    1240                 traceback.print_exc()
     1305            traceback.print_exc()
    12411306    lf.close()
    12421307    return 0
     
    19652030   return 0
    19662031
     2032def shareFolderCmd(ctx,args):
     2033    if (len(args) < 4):
     2034        print "usage: shareFolder vm path name <writable> <persistent>"
     2035        return 0
     2036
     2037    mach = argsToMach(ctx,args)
     2038    if mach is None:
     2039        return 0
     2040    path = args[2]
     2041    name = args[3]
     2042    writable = False
     2043    persistent = False
     2044    if len(args) > 4:
     2045        for a in args[4:]:
     2046            if a == 'writable':
     2047                writable = True
     2048            if a == 'persistent':
     2049                persistent = True
     2050    if persistent:
     2051        cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.createSharedFolder(name, path, writable), [])
     2052    else:
     2053        cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx,mach,console,args: console.createSharedFolder(name, path, writable)])
     2054    return 0
     2055
     2056def unshareFolderCmd(ctx,args):
     2057    if (len(args) < 3):
     2058        print "usage: unshareFolder vm name"
     2059        return 0
     2060
     2061    mach = argsToMach(ctx,args)
     2062    if mach is None:
     2063        return 0
     2064    name = args[2]
     2065    found = False
     2066    for sf in ctx['global'].getArray(mach, 'sharedFolders'):
     2067        if sf.name == name:
     2068            cmdClosedVm(ctx, mach, lambda ctx,mach,args: mach.removeSharedFolder(name), [])
     2069            found = True
     2070            break
     2071    if not found:
     2072        cmdExistingVm(ctx, mach, 'guestlambda', [lambda ctx,mach,console,args: console.removeSharedFolder(name)])
     2073    return 0
     2074
    19672075aliases = {'s':'start',
    19682076           'i':'info',
     
    19992107            'portForward':['Setup permanent port forwarding for a VM, takes adapter number host port and guest port: portForward Win32 0 8080 80', portForwardCmd, 0],
    20002108            'showLog':['Show log file of the VM, : showLog Win32', showLogCmd, 0],
     2109            'findLog':['Show entries matching pattern in log file of the VM, : findLog Win32 PDM|CPUM', findLogCmd, 0],
    20012110            'reloadExt':['Reload custom extensions: reloadExt', reloadExtCmd, 0],
    20022111            'runScript':['Run VBox script: runScript script.vbox', runScriptCmd, 0],
     
    20302139            'detachCtr': ['Detach HDD from the VM: detachCtr win Ctr0', detachCtrCmd, 0],
    20312140            'attachUsb': ['Attach USB device to the VM (use listUsb to show available devices): attachUsb win uuid', attachUsbCmd, 0],
    2032             'detachUsb': ['Detach USB device from the VM: detachUsb win uui', detachUsbCmd, 0],
     2141            'detachUsb': ['Detach USB device from the VM: detachUsb win uuid', detachUsbCmd, 0],
    20332142            'listMediums': ['List mediums known to this VBox instance', listMediumsCmd, 0],
    20342143            'listUsb': ['List known USB devices', listUsbCmd, 0],
    2035             'gui': ['Start GUI frontend', guiCmd, 0]
     2144            'shareFolder': ['Make host\'s folder visible to guest: shareFolder win /share share writable', shareFolderCmd, 0],
     2145            'unshareFolder': ['Remove folder sharing', unshareFolderCmd, 0],
     2146            'gui': ['Start GUI frontend', guiCmd, 0],
     2147            'colors':['Toggle colors', colorsCmd, 0],
    20362148            }
    20372149
     
    21352247    while True:
    21362248        try:
    2137             cmd = raw_input("vbox> ")
     2249            cmd = raw_input(colored("vbox> ", 'blue'))
    21382250            done = runCommand(ctx, cmd)
    21392251            if done != 0: break
    21402252        except KeyboardInterrupt:
    21412253            print '====== You can type quit or q to leave'
     2254        except EOFError:
    21422255            break
    2143         except EOFError:
    2144             break;
    21452256        except Exception,e:
    2146             print e
     2257            printErr(ctx,e)
    21472258            if g_verbose:
    21482259                traceback.print_exc()
Note: See TracChangeset for help on using the changeset viewer.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette