VirtualBox

Changeset 29051 in vbox for trunk/src/VBox/Frontends


Ignore:
Timestamp:
May 5, 2010 2:37:25 AM (15 years ago)
Author:
vboxsync
svn:sync-xref-src-repo-rev:
61100
Message:

VBoxShell: NAT manipulations.

File:
1 edited

Legend:

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

    r28889 r29051  
    21732173
    21742174    return 0
     2175
     2176def natAlias(ctx, mach, nicnum, nat, args=[]):
     2177    """This command shows/alters NAT's alias settings.
     2178    usage: nat <vm> <nicnum> alias [default|[log] [proxyonly] [sameports]]
     2179    default - set settings to default values
     2180    log - switch on alias loging
     2181    proxyonly - switch proxyonly mode on
     2182    sameports - enforces NAT using the same ports
     2183    """
     2184    alias = {
     2185        'log': 0x1,
     2186        'proxyonly': 0x2,
     2187        'sameports': 0x4
     2188    }
     2189    if len(args) == 1:
     2190        first = 0
     2191        msg = ''
     2192        for aliasmode, aliaskey in alias.iteritems():
     2193            if first == 0:
     2194                first = 1
     2195            else:
     2196                msg += ', '
     2197            if int(nat.aliasMode) & aliaskey:
     2198                msg += '{0}: {1}'.format(aliasmode, 'on')
     2199            else:
     2200                msg += '{0}: {1}'.format(aliasmode, 'off')
     2201        msg += ')'
     2202        return (0, [msg])
     2203    else:
     2204        nat.aliasMode = 0
     2205        if 'default' not in args:
     2206            for a in range(1, len(args)):
     2207                if not alias.has_key(args[a]):
     2208                    print 'Invalid alias mode: ' + args[a]
     2209                    print natAlias.__doc__
     2210                    return (1, '')
     2211                nat.aliasMode = int(nat.aliasMode) | alias[args[a]];
     2212    return (0, '')
     2213
     2214def natSettings(ctx, mach, nicnum, nat, args):
     2215    """This command shows/alters NAT settings.
     2216    usage: nat <vm> <nicnum> settings [<mtu> [[<socsndbuf> <sockrcvbuf> [<tcpsndwnd> <tcprcvwnd>]]]]
     2217    mtu - set mtu <= 16000
     2218    socksndbuf/sockrcvbuf - sets amount of kb for socket sending/receiving buffer
     2219    tcpsndwnd/tcprcvwnd - sets size of initial tcp sending/receiving window
     2220    """
     2221    if len(args) == 1:
     2222        (mtu, socksndbuf, sockrcvbuf, tcpsndwnd, tcprcvwnd) = nat.getNetworkSettings();
     2223        if mtu == 0: mtu = 1500
     2224        if socksndbuf == 0: socksndbuf = 64
     2225        if sockrcvbuf == 0: sockrcvbuf = 64
     2226        if tcpsndwnd == 0: tcpsndwnd = 64
     2227        if tcprcvwnd == 0: tcprcvwnd = 64
     2228        msg = 'mtu:{0} socket(snd:{1}, rcv:{2}) tcpwnd(snd:{3}, rcv:{4})'.format(mtu, socksndbuf, sockrcvbuf, tcpsndwnd, tcprcvwnd);
     2229        return (0, [msg])
     2230    else:
     2231        if args[1] < 16000:
     2232            print 'invalid mtu value ({0} no in range [65 - 16000])'.format(args[1])
     2233            return (1, '')
     2234        for i in range(2, len(args)):
     2235            if not args[i].isdigit() or int(args[i]) < 8 or int(args[i]) > 1024:
     2236                print 'invalid {0} parameter ({1} not in range [8-1024])'.format(i, args[i])
     2237                return (1,'')
     2238        a = [args[1]]
     2239        if len(args) < 6:
     2240            for i in range(2, len(args)): a.append(args[i])
     2241            for i in range(len(args), 6): a.append(0)
     2242        else:
     2243            for i in range(2, len(args)): a.append(args[i])
     2244        #print a
     2245        nat.setNetworkSettings(int(a[0]), int(a[1]), int(a[2]), int(a[3]), int(a[4]))
     2246    return (0,'')
     2247
     2248def natDns(ctx, mach, nicnum, nat, args):
     2249    """This command shows/alters DNS's NAT settings
     2250    usage: nat <vm> <nicnum> dns [passdomain] [proxy] [usehostresolver]
     2251    passdomain - enforces builtin DHCP server to pass domain
     2252    proxy - switch on builtin NAT DNS proxying mechanism
     2253    usehostresolver - proxies all DNS requests to Host Resolver interface
     2254    """
     2255    yesno = {0: 'off', 1: 'on'}
     2256    if len(args) == 1:
     2257        msg = 'passdomain:{0}, proxy:{1}, usehostresolver:{2}'.format(yesno[int(nat.dnsPassDomain)], yesno[int(nat.dnsProxy)], yesno[int(nat.dnsUseHostResolver)])
     2258        return (0, [msg])
     2259    else:
     2260        nat.dnsPassDomain = 'passdomain' in args
     2261        nat.dnsProxy =  'proxy' in args
     2262        nat.dnsUseHostResolver =  'usehostresolver' in args
     2263    return (0, '')
     2264
     2265def natTftp(ctx, mach, nicnum, nat, args):
     2266    """This command shows/alters TFTP settings
     2267    usage nat <vm> <nicnum> tftp [prefix <prefix>| bootfile <bootfile>| server <server>]
     2268    prefix - alters prefix TFTP settings
     2269    bootfile - alters bootfile TFTP settings
     2270    server - sets booting server
     2271    """
     2272    if len(args) == 1:
     2273        server = nat.tftpNextServer
     2274        if server is None:
     2275            server = nat.network
     2276            if server is None:
     2277                server = '10.0.{0}/24'.format(int(nicnum) + 2)
     2278            (server,mask) = server.split('/')
     2279            while server.count('.') != 3:
     2280                server += '.0'
     2281            (a,b,c,d) = server.split('.')
     2282            server = '{0}.{1}.{2}.4'.format(a,b,c)
     2283        prefix = nat.tftpPrefix
     2284        if prefix is None:
     2285            prefix = '{0}/TFTP/'.format(ctx['vb'].homeFolder)
     2286        bootfile = nat.tftpBootFile
     2287        if bootfile is None:
     2288            bootfile = '{0}.pxe'.format(mach.name)
     2289        msg = 'server:{0}, prefix:{1}, bootfile:{2}'.format(server, prefix, bootfile)
     2290        return (0, [msg])
     2291    else:
     2292
     2293        cmd = args[1]
     2294        if len(args) != 3:
     2295            print 'invalid args:', args
     2296            print natTftp.__doc__
     2297            return (1,'')
     2298        if cmd == 'prefix': nat.tftpPrefix = args[2]
     2299        elif cmd == 'bootfile': nat.tftpBootFile = args[2]
     2300        elif cmd == 'server': nat.tftpNextServer = args[2]
     2301        else:
     2302            print "invalid cmd:", cmd
     2303            return (1, '')
     2304    return (0,'')
     2305
     2306def natPortForwarding(ctx, mach, nicnum, nat, args):
     2307    """This command shows/manages port-forwarding settings
     2308    usage:
     2309        nat <vm> <nicnum> <pf> [ simple tcp|udp <hostport> <guestport>]
     2310            |[no_name tcp|udp <hostip> <hostport> <guestip> <guestport>]
     2311            |[ex tcp|udp <pf-name> <hostip> <hostport> <guestip> <guestport>]
     2312            |[delete <pf-name>]
     2313    """
     2314    if len(args) == 1:
     2315        # note: keys/values are swapped in defining part of the function
     2316        proto = {0: 'udp', 1: 'tcp'}
     2317        msg = []
     2318        pfs = ctx['global'].getArray(nat, 'redirects')
     2319        for pf in pfs:
     2320            (pfnme, pfp, pfhip, pfhp, pfgip, pfgp) = str(pf).split(',')
     2321            msg.append('{0}: {1} {2}:{3} => {4}:{5}'.format(pfnme, proto[int(pfp)], pfhip, pfhp, pfgip, pfgp))
     2322        return (0, msg) # msg is array
     2323    else:
     2324        proto = {'udp': 0, 'tcp': 1}
     2325        pfcmd = {
     2326            'simple': {
     2327                'validate': lambda: args[1] in pfcmd.keys() and args[2] in proto.keys() and len(args) == 5,
     2328                'func':lambda: nat.addRedirect('', proto[args[2]], '', int(args[3]), '', int(args[4]))
     2329            },
     2330            'no_name': {
     2331                'validate': lambda: args[1] in pfcmd.keys() and args[2] in proto.keys() and len(args) == 7,
     2332                'func': lambda: nat.addRedirect('', proto[args[2]], args[3], int(args[4]), args[5], int(args[6]))
     2333            },
     2334            'ex': {
     2335                'validate': lambda: args[1] in pfcmd.keys() and args[2] in proto.keys() and len(args) == 8,
     2336                'func': lambda: nat.addRedirect(args[3], proto[args[2]], args[4], int(args[5]), args[6], int(args[7]))
     2337            },
     2338            'delete': {
     2339                'validate': lambda: len(args) == 3,
     2340                'func': lambda: nat.removeRedirect(args[2])
     2341            }
     2342        }
     2343
     2344        if not pfcmd[args[1]]['validate']():
     2345            print 'invalid port-forwarding or args of sub command ', args[1]
     2346            print natPortForwarding.__doc__
     2347            return (1, '')
     2348
     2349        a = pfcmd[args[1]]['func']()
     2350    return (0,'')
     2351
     2352def natNetwork(ctx, mach, nicnum, nat, args):
     2353    """This command shows/alters NAT network settings
     2354    usage: nat <vm> <nicnum> network [<network>]
     2355    """
     2356    if len(args) == 1:
     2357        if nat.network is not None and len(str(nat.network)) != 0:
     2358            msg = '\'%s\'' % (nat.network)
     2359        else:
     2360            msg = '10.0.{0}.0/24'.format(int(nicnum) + 2)
     2361        return (0, [msg])
     2362    else:
     2363        (addr, mask) = args[1].split('/')
     2364        if addr.count('.') > 3 or int(mask) < 0 or int(mask) > 32:
     2365            print 'Invalid arguments'
     2366            return (1,'')
     2367        nat.network = args[1]
     2368    return (0, '')
     2369def natCmd(ctx, args):
     2370    """This command is entry point to NAT settins management
     2371    usage: nat <vm> <nicnum> <cmd> <cmd-args>
     2372    cmd - [alias|settings|tftp|dns|pf|network]
     2373    for more information about commands:
     2374    nat help <cmd>
     2375    """
     2376
     2377    natcommands = {
     2378        'alias' : natAlias,
     2379        'settings' : natSettings,
     2380        'tftp': natTftp,
     2381        'dns': natDns,
     2382        'pf': natPortForwarding,
     2383        'network': natNetwork
     2384    }
     2385
     2386    if args[1] == 'help':
     2387        if len(args) > 2:
     2388            print natcommands[args[2]].__doc__
     2389        else:
     2390            print natCmd.__doc__
     2391        return 0
     2392    if len(args) == 1 or len(args) < 4 or args[3] not in natcommands:
     2393        print natCmd.__doc__
     2394        return 0
     2395    mach = ctx['argsToMach'](args)
     2396    if mach == None:
     2397        print "please specify vm"
     2398        return 0
     2399    if len(args) < 3 or not args[2].isdigit() or int(args[2]) not in range(0, ctx['vb'].systemProperties.networkAdapterCount):
     2400        print 'please specify adapter num {0} isn\'t in range [0-{1}]'.format(args[2], ctx['vb'].systemProperties.networkAdapterCount)
     2401        return 0
     2402    nicnum = int(args[2])
     2403    cmdargs = []
     2404    for i in range(3, len(args)):
     2405        cmdargs.append(args[i])
     2406       
     2407    # @todo vvl if nicnum is missed but command is entered
     2408    # use NAT func for every adapter on machine.
     2409    func = args[3]
     2410    rosession = 1
     2411    session = None
     2412    if len(cmdargs) > 1:
     2413        rosession = 0
     2414        session = ctx['global'].openMachineSession(mach.id);
     2415        mach = session.machine;
     2416
     2417    adapter = mach.getNetworkAdapter(nicnum)
     2418    natEngine = adapter.natDriver
     2419    (rc, report) = natcommands[func](ctx, mach, nicnum, natEngine, cmdargs)
     2420    if rosession == 0:
     2421        if rc == 0:
     2422            mach.saveSettings()
     2423        session.close()
     2424    else:
     2425        for r in report:
     2426            msg ='{0} nic{1} {2}: {3}'.format(mach.name, nicnum, func, r)
     2427            print msg
     2428    return 0
     2429
    21752430
    21762431aliases = {'s':'start',
     
    22482503            'colors':['Toggle colors', colorsCmd, 0],
    22492504            'snapshot':['VM snapshot manipulation, snapshot help for more info', snapshotCmd, 0],
     2505            'nat':['NAT manipulation, nat help for more info', natCmd, 0],
    22502506            }
    22512507
Note: See TracChangeset for help on using the changeset viewer.

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