Beispiel #1
0
def usage_full():
    nmtalk.message("Usage: nm <command> <options> ...")
    nmtalk.message("")

    nmtalk.message("The following options are understood by all commands:")
    nmformat.opt_table(default_opt_table)

    keys = command_dict.keys()

    if keys:
        command_list = []
        for k in keys:
            description, constructor, aliases, hidden, basic, category  = command_dict[k]
            if not hidden:
                command_list.append([k, aliases, description, category])

        print_command_list(command_list, with_categories=1)

        nmtalk.message("")
        nmtalk.message("For more detailed information about a specific command,")
        nmtalk.message("run 'nm <command name> --help'.")
        nmtalk.message("")

    else:
        nmtalk.error("<< No commands found --- something is wrong! >>")
Beispiel #2
0
    def execute(self, options_dict, non_option_args):
        if len(non_option_args) < 1:
            self.usage()

        manager = self.Manager()
        table_headers = ("Property", "Value")

        for device_iface in non_option_args:
            device = manager.get_device_by_iface(device_iface)
            if not device:
                nmtalk.error("Invalid device %s" % device_iface)
                continue

            config = device.get_ip4_config()
            if not config:
                nmtalk.error("Device has no IP4 config")
                continue

            props = config.get_properties()
            if len(non_option_args) > 1:
                print
                print "Device %s" % device_iface
                print
            nmformat.tabular(table_headers, props)

        return 0
Beispiel #3
0
    def execute(self, options_dict, non_option_args):
        if len(non_option_args) < 1:
            self.usage()

        manager = self.Manager()

        aps = self.find_aps(manager.get_devices(), non_option_args)
            
        found = 0
        table_headers = ("Property", "Value")

        for ssid in non_option_args:
            ap = aps[ssid]
            if not ap:
                nmtalk.error("Can not find AP %s" % ssid)
                continue

            found += 1
            props = ap.get_properties()
            nmformat.tabular(table_headers, props)

        if found == 0:
            return 1

        return 0
Beispiel #4
0
    def execute(self, options_dict, non_option_args):
        if len(non_option_args) < 1:
            self.usage()

        manager = self.Manager()
        table_headers = ("Property", "Value")

        for device_iface in non_option_args:
            device = manager.get_device_by_iface(device_iface)
            if not device:
                nmtalk.error("Invalid device %s" % device_iface)
                continue

            config = device.get_ip4_config()
            if not config:
                nmtalk.error("Device has no IP4 config")
                continue

            props = config.get_properties()
            if len(non_option_args) > 1:
                print
                print "Device %s" % device_iface
                print
            nmformat.tabular(table_headers, props)

        return 0
Beispiel #5
0
    def execute(self, options_dict, non_option_args):
        if not non_option_args:
            self.usage()

        manager = nmsettings.ConnectionManager()

        found = 0
        for name in non_option_args:
            connection = manager.get_connection_by_name(nmsettings.DBUS_SERVICE_USER_SETTINGS, name)
            if not connection:
                nmtalk.error("Can not find connection '%s'" % name)
                continue

            found += 1
            settings = connection.get_settings()
            for setting_type in settings.keys():
                print setting_type
                setting = settings[setting_type]
                for key in setting.keys():
                    print "%s : %s" % (key, setting[key])

                print

        if found == 0:
            return 1

        return 0
Beispiel #6
0
    def execute(self, options_dict, non_option_args):
        manager = self.Manager()
        devices = []

        if len(non_option_args) < 1:
            # Get all wireless devices
            for device in manager.get_devices():
                if isinstance(device, nmwirelessdevicecmds.WirelessDevice):
                    devices.append(device)

        else:
            for device in manager.get_devices():
                for arg in non_option_args:
                    if device.get_interface() == arg:
                        if isinstance(device, nmwirelessdevicecmds.WirelessDevice):
                            devices.append(device)
                        else:
                            nmtalk.error("Wireless device expected, got %s" % str(device))

        got_devices = len(devices)

        if got_devices < 1:
            nmtalk.error("No wireless devices found.")
            return 1

        for device in devices:
            if got_devices > 1:
                nmtalk.message("Access Points for device '%s':" % device.get_interface())

            aps = device.get_access_points()

            if not aps:
                nmtalk.message("No access points found.")
                continue

            rows = []
            active_ap = device.get_active_access_point()
            if active_ap:
                active_ssid = active_ap.get_ssid()
            else:
                active_ssid = None

            for ap in aps:
                if active_ssid == ap.get_ssid():
                    active = "*"
                else:
                    active = ""

                rows.append ((str(ap), active))

            rows.sort(lambda x,y:cmp(x[0].lower(), y[0].lower()))
            nmformat.tabular(("SSID", "Active"), rows)

        return 0
Beispiel #7
0
    def execute(self, options_dict, non_option_args):
        if len(non_option_args) != 1:
            self.usage()

        vpn_manager = nmvpn.VpnManager()
        connection = vpn_manager.get_active_connection_by_name(non_option_args[0])
        if not connection:
            nmtalk.error("VPN connection '%s' not found." % non_option_args[0])
            return 1

        connection.disconnect()

        return 0
Beispiel #8
0
    def execute(self, options_dict, non_option_args):
        if len(non_option_args) != 1:
            self.usage()

        vpn_manager = nmvpn.VpnManager()
        connection = vpn_manager.get_active_connection_by_name(
            non_option_args[0])
        if not connection:
            nmtalk.error("VPN connection '%s' not found." % non_option_args[0])
            return 1

        connection.disconnect()

        return 0
Beispiel #9
0
def usage_basic():
    nmtalk.message("Usage: nm <command> <options> ...")
    nmtalk.message("")

    keys = command_dict.keys()

    if keys:
        keys.sort()
        command_list = []
        for k in keys:
            description, constructor, aliases, hidden, basic, category  = command_dict[k]
            if not hidden and basic:
                command_list.append([k, aliases, description, category])

        nmtalk.message("Some basic commands are:")
        print_command_list(command_list)

        nmtalk.message("")
        nmtalk.message("For a more complete list of commands and important options,")
        nmtalk.message("run \"nm help\".")
        nmtalk.message("")

    else:
        nmtalk.error("<< No commands found --- something is wrong! >>")
Beispiel #10
0
def show_exception(e):
    if nmtalk.show_verbose:
        trace = ""
        exception = ""
        exc_list = traceback.format_exception_only (sys.exc_type, sys.exc_value)
        for entry in exc_list:
            exception += entry
            tb_list = traceback.format_tb(sys.exc_info()[2])
            for entry in tb_list:
                trace += entry

        nmtalk.error(str(e))
        nmtalk.error(trace)
    else:
        nmtalk.error(str(e))
Beispiel #11
0
def show_exception(e):
    if nmtalk.show_verbose:
        trace = ""
        exception = ""
        exc_list = traceback.format_exception_only(sys.exc_type, sys.exc_value)
        for entry in exc_list:
            exception += entry
            tb_list = traceback.format_tb(sys.exc_info()[2])
            for entry in tb_list:
                trace += entry

        nmtalk.error(str(e))
        nmtalk.error(trace)
    else:
        nmtalk.error(str(e))
Beispiel #12
0
def register(constructor):
    obj = constructor()
    name = obj.name()
    aliases = obj.aliases()
    hidden = obj.is_hidden()
    basic = obj.is_basic()
    description = obj.description_short() or "<No Description Available>"
    category = obj.category()

    if command_dict.has_key(name):
        nmtalk.error("Command name collision: '"+name+"'")
    else:
        command_dict[name] = (description, constructor, aliases, hidden, basic, category)

    for a in aliases:
        al = string.lower(a)
        if command_dict.has_key(al):
            nmtalk.error("Command/alias collision: '"+a+"'")
        elif alias_dict.has_key(al):
            nmtalk.error("Alias collision: '"+a+"'")
        else:
            alias_dict[al] = name
Beispiel #13
0
    def execute(self, options_dict, non_option_args):
        if len(non_option_args) != 1:
            self.usage()

        # Find the VPN connection
        manager = nmsettings.ConnectionManager()
        connection_name = non_option_args.pop(0)

        if options_dict.has_key("system"):
            connection = manager.get_connection_by_name(
                nmsettings.DBUS_SERVICE_SYSTEM_SETTINGS, connection_name,
                "vpn")
        elif options_dict.has_key("user"):
            connection = manager.get_connection_by_name(
                nmsettings.DBUS_SERVICE_USER_SETTINGS, connection_name, "vpn")
        else:
            connection = manager.get_connection_by_name(
                nmsettings.DBUS_SERVICE_SYSTEM_SETTINGS, connection_name,
                "vpn")
            if not connection:
                connection = manager.get_connection_by_name(
                    nmsettings.DBUS_SERVICE_USER_SETTINGS, connection_name,
                    "vpn")

        if not connection:
            nmtalk.error("VPN connection '%s' not found." % connection_name)
            return 1

        manager = nm.NetworkManager()

        # Find the first active device
        device = None
        for d in manager.get_devices():
            if d.get_state() == nmdevice.DEVICE_STATE_ACTIVATED:
                device = d
                break

        if not device:
            nmtalk.fatal("Can not activate VPN, no active device found")

        vpn_manager = nmvpn.VpnManager()
        vpn_connection = vpn_manager.connect(connection, device)

        if options_dict.has_key("dont-wait"):
            return 0

        loop = gobject.MainLoop()
        self.exit_status = 0

        def monitor(state, reason):
            msg = "'%s': %s" % (connection_name,
                                nmvpn.vpn_connection_state_to_str(state))
            if reason != nmvpn.VPN_CONNECTION_STATE_REASON_NONE:
                msg += " (%s)" % nmvpn.vpn_connection_state_reason_to_str(
                    reason)

            nmtalk.message(msg)

            if state == nmvpn.VPN_CONNECTION_STATE_ACTIVATED:
                loop.quit()

            elif state == nmvpn.VPN_CONNECTION_STATE_FAILED or state == nmvpn.VPN_CONNECTION_STATE_DISCONNECTED:
                loop.quit()
                self.exit_status = 1

        vpn_connection.proxy.connect_to_signal(
            "StateChanged",
            monitor,
            dbus_interface=nmvpn.DBUS_INTERFACE_VPN_CONNECTION)

        loop.run()

        return self.exit_status
Beispiel #14
0
    def process_argv(self, argv):
        ###
        ### Expand our synthetic args.
        ### Then compile our list of arguments into something that getopt can
        ### understand.  Finally, call getopt on argv and massage the results
        ### in something easy-to-use.
        ###

        argv = get_user_default_args(argv, self.name())

        opt_table = self.opt_table()

        short_opt_getopt = ""
        long_opt_getopt  = []

        short2long_dict = {}

        for o in opt_table:
            
            short_opt = o[0]
            long_opt  = o[1]
            opt_desc  = o[2]

            if short_opt:

                if short2long_dict.has_key(short_opt):
                    nmtalk.error("Short option collision!")
                    nmtalk.error("-" + short_opt + ", --" + long_opt)
                    nmtalk.error("  vs.")
                    nmtalk.error("-" + short_opt + ", --" + short2long_dict[short_opt])
                    sys.exit(1)

                short2long_dict[short_opt] = long_opt
                short_opt_getopt = short_opt_getopt + short_opt
                if opt_desc:
                    short_opt_getopt = short_opt_getopt + ":"

            if opt_desc:
                long_opt_getopt.append(long_opt + "=")
            else:
                long_opt_getopt.append(long_opt)

        try:
            optlist, args = getopt.getopt(argv, short_opt_getopt, long_opt_getopt)
        except getopt.error:
            did_something = 0
            for a in argv:
                if string.find(a,"--") == 0:
                    if not a[2:] in map(lambda x:x[1], opt_table):
                        nmtalk.error("Invalid argument " + a)
                        did_something = 1
                elif string.find(a, "-") == 0:
                    if not a[1:] in map(lambda x:x[0], opt_table):
                        nmtalk.error("Invalid argument " + a)
                        did_something = 1

            # Just in case something strange went wrong and we weren't
            # able to describe quite why the options parsing failed,
            # we print a catch-all error message.
            if not did_something:
                nmtalk.error("Invalid arguments")
                
            self.usage()
            
            sys.exit(1)

        ###
        ### Walk through our list of options and replace short options with the
        ### corresponding long option.
        ###

        i = 0
        while i < len(optlist):
            key = optlist[i][0]
            if key[0:2] != "--":
                optlist[i] = ("--" + short2long_dict[key[1:]], optlist[i][1])
            i = i + 1


        ###
        ### Get the list of "orthogonal" options for this command and, if our
        ### list of options contains orthogonal elements, remove all but the
        ### last such option.
        ### (i.e. if we are handed --quiet --verbose, we drop the --quiet)
        ### 

        optlist.reverse()
        for oo_list in self.orthogonal_opts():
            i = 0
            seen_oo = 0
            while i < len(optlist):
                key = optlist[i][0]
                if key[2:] in oo_list:
                    if seen_oo:
                        del optlist[i]
                        i = i - 1
                    seen_oo = 1
                i = i + 1
        optlist.reverse()

        ###
        ### Store our options in a dictionary
        ###

        opt_dict = {}

        for key, value in optlist:
            opt_dict[key[2:]] = value


        return opt_dict, args
Beispiel #15
0
 def execute(self, options_dict, non_option_args):
     nmtalk.error("Execute not implemented!")
     sys.exit(1)
Beispiel #16
0
    def execute(self, options_dict, non_option_args):
        if len(non_option_args) != 1:
            self.usage()

        # Find the VPN connection
        manager = nmsettings.ConnectionManager()
        connection_name = non_option_args.pop(0)

        if options_dict.has_key("system"):
            connection = manager.get_connection_by_name(nmsettings.DBUS_SERVICE_SYSTEM_SETTINGS,
                                                        connection_name, "vpn")
        elif options_dict.has_key("user"):
            connection = manager.get_connection_by_name(nmsettings.DBUS_SERVICE_USER_SETTINGS,
                                                        connection_name, "vpn")
        else:
            connection = manager.get_connection_by_name(nmsettings.DBUS_SERVICE_SYSTEM_SETTINGS,
                                                        connection_name, "vpn")
            if not connection:
                connection = manager.get_connection_by_name(nmsettings.DBUS_SERVICE_USER_SETTINGS,
                                                            connection_name, "vpn")

        if not connection:
            nmtalk.error("VPN connection '%s' not found." % connection_name)
            return 1

        manager = nm.NetworkManager()

        # Find the first active device
        device = None
        for d in manager.get_devices():
            if d.get_state() == nmdevice.DEVICE_STATE_ACTIVATED:
                device = d
                break

        if not device:
            nmtalk.fatal("Can not activate VPN, no active device found")

        vpn_manager = nmvpn.VpnManager()
        vpn_connection = vpn_manager.connect(connection, device)

        if options_dict.has_key("dont-wait"):
            return 0

        loop = gobject.MainLoop()
        self.exit_status = 0

        def monitor(state, reason):
            msg = "'%s': %s" % (connection_name, nmvpn.vpn_connection_state_to_str(state))
            if reason != nmvpn.VPN_CONNECTION_STATE_REASON_NONE:
                msg += " (%s)" % nmvpn.vpn_connection_state_reason_to_str(reason)

            nmtalk.message(msg)

            if state == nmvpn.VPN_CONNECTION_STATE_ACTIVATED:
                loop.quit()

            elif state == nmvpn.VPN_CONNECTION_STATE_FAILED or state == nmvpn.VPN_CONNECTION_STATE_DISCONNECTED:
                loop.quit()
                self.exit_status = 1

        vpn_connection.proxy.connect_to_signal("StateChanged", monitor,
                                                dbus_interface=nmvpn.DBUS_INTERFACE_VPN_CONNECTION)


        loop.run()

        return self.exit_status
Beispiel #17
0
def main(ver, nm_dir):

    global local
    global nm_version

    nm_version = ver

    if os.environ.has_key("NM_DEBUG"):
        nmtalk.show_debug = 1

    import_commands(nm_dir)

    ###
    ### Grab the option list and extract the first non-option argument that
    ### looks like a command.  This could get weird if someone passes the name
    ### of a command as the argument to an option.
    ###

    argv = sys.argv[1:]

    argv = nmcommand.expand_synthetic_args(argv)

    if "--version" in argv:
        print
        print nm_name + " " + nm_version
        print nm_copyright
        print
        sys.exit(0)

    command = nmcommand.extract_command_from_argv(argv)

    if "-?" in argv or "--help" in argv:
        command.usage()
        sys.exit(0)

    # A hack to suppress extra whitespace when dumping.
    if command.name() == "dump":
        nmtalk.be_terse = 1

    argv = nmcommand.get_user_default_args(argv, command)

    opt_dict, args = command.process_argv(argv)

    ###
    ### Control verbosity
    ###

    if opt_dict.has_key("terse"):
        nmtalk.be_terse = 1

    if opt_dict.has_key("quiet"):
        nmtalk.show_messages = 0
        nmtalk.show_warnings = 0

    if opt_dict.has_key("verbose"):
        nmtalk.show_verbose = 1

    ### Whitespace is nice, so we always print a blank line before
    ### executing the command

    if not nmtalk.be_terse:
        nmtalk.message("")

    try:
        command.execute(opt_dict, args)
    except IOError, e:
        if e.errno == 13:
            nmtalk.error("You must be root to execute this command")
        else:
            show_exception(e)

        sys.exit(1)
Beispiel #18
0
def main(ver, nm_dir):

    global local
    global nm_version

    nm_version = ver

    if os.environ.has_key("NM_DEBUG"):
        nmtalk.show_debug = 1

    import_commands(nm_dir)

    ###
    ### Grab the option list and extract the first non-option argument that
    ### looks like a command.  This could get weird if someone passes the name
    ### of a command as the argument to an option.
    ###

    argv = sys.argv[1:]

    argv = nmcommand.expand_synthetic_args(argv)

    if "--version" in argv:
        print
        print nm_name + " " + nm_version
        print nm_copyright
        print
        sys.exit(0)

    command = nmcommand.extract_command_from_argv(argv)

    if "-?" in argv or "--help" in argv:
        command.usage()
        sys.exit(0)

    # A hack to suppress extra whitespace when dumping.
    if command.name() == "dump":
        nmtalk.be_terse = 1

    argv = nmcommand.get_user_default_args(argv, command)

    opt_dict, args = command.process_argv(argv)

    ###
    ### Control verbosity
    ###

    if opt_dict.has_key("terse"):
        nmtalk.be_terse = 1

    if opt_dict.has_key("quiet"):
        nmtalk.show_messages = 0
        nmtalk.show_warnings = 0

    if opt_dict.has_key("verbose"):
        nmtalk.show_verbose = 1

    ### Whitespace is nice, so we always print a blank line before
    ### executing the command

    if not nmtalk.be_terse:
        nmtalk.message("")

    try:
        command.execute(opt_dict, args)
    except IOError, e:
        if e.errno == 13:
            nmtalk.error("You must be root to execute this command")
        else:
            show_exception(e)

        sys.exit(1)
Beispiel #19
0
def expand_synthetic_args(argv):

    ###
    ### First, walk across our argument list and find any --read-from-file
    ### options.  For each, read the arguments from the file and insert
    ### them directly after the --read-from-file option.
    ###
    
    i = 0
    is_file_to_read_from = 0
    while i < len(argv):
        arg = argv[i]
        file_to_read = None
        if is_file_to_read_from:
            file_to_read = arg
            is_file_to_read_from = 0
        if arg == "--read-from-file":
            is_file_to_read_from = 1
        elif string.find(arg, "--read-from-file=") == 0:
            file_to_read = arg[len("--read-from-file="):]
            is_file_to_read_from = 0

        if file_to_read:
            lines = []
            try:
                f = open(file_to_read, "r")
                lines = map(string.strip, f.readlines())
            except IOError:
                nmtalk.error("Couldn't open file '%s' to read arguments" % file_to_read)
                sys.exit(1)
            argv = argv[:i] + lines + argv[i+1:]
            i = i + len(lines)

        i = i + 1

    ###
    ### Next, look for --read-from-stdin options.  If there is more than
    ### one on the command line, we split our list of options on blank
    ### lines.
    ###

    rfs_count = argv.count("--read-from-stdin")
    if rfs_count > 0:
        lines = map(string.strip, sys.stdin.readlines())

        i = 0  # position in argv
        j = 0  # position in lines
        while i < len(argv):

            if argv[i] == "--read-from-stdin":

                if j < len(lines):
                    if rfs_count > 1 and "" in lines[j:]:
                        j1 = j + lines[j:].index("")
                        argv = argv[:i+1] + lines[j:j1] + argv[i+1:]
                        j = j1+1
                    else:
                        argv = argv[:i+1] + \
                               filter(lambda x:x!="", lines[j:]) + \
                               argv[i+1:]
                        j = len(lines)

                        
                rfs_count = rfs_count - 1

            i = i + 1

    ###
    ### Finally, we filter our all of those --read-from-* arguments
    ### that we left lying around in argv.
    ###

    argv = filter(lambda x: \
                  string.find(x,"--read-from-file") != 0 \
                  and x != "--read-from-stdin",
                  argv)
                        
    return argv