Provisionally implement -n as -a.
[cnetworkmanager.git] / cnetworkmanager
bloba5be77452b0bbdd9cb0bb3a5040731370d97815f
1 #!/usr/bin/python
2 VERSION = "0.20"
4 import sys
5 import dbus
6 from networkmanager.networkmanager import NetworkManager, SYSTEM_SERVICE, USER_SERVICE
7 from networkmanager.settings.settings import NetworkManagerSettings
9 # must be set before we ask for signals
10 from dbus.mainloop.glib import DBusGMainLoop
11 DBusGMainLoop(set_as_default=True)
12 # for calling quit
13 import gobject
14 loop = gobject.MainLoop()
15 LOOP = False
17 from optparse import OptionParser
19 op = OptionParser(version="%prog " + VERSION)
21 # TODO http://docs.python.org/lib/optparse-adding-new-types.html
22 op.add_option("-w", "--wifi",
23 choices=["0","1","off","on","no","yes","false","true"],
24 metavar="BOOL",
25 help="Enable or disable wireless")
26 op.add_option("-o", "--online",
27 choices=["0","1","off","on","no","yes","false","true"],
28 metavar="BOOL",
29 help="Enable or disable network at all")
30 op.add_option("--state",
31 action="store_true", default=False,
32 help="Print the NM state")
33 op.add_option("--whe", "--wireless-hardware-enabled",
34 action="store_true", default=False,
35 help="Print whether the WiFi is enabled")
37 op.add_option("-d", "--device-list", "--dev",
38 action="store_true", default=False,
39 help="List devices")
40 op.add_option("--device-info", "--di",
41 help="Info about device DEV (by interface or UDI(TODO))",
42 metavar="DEV")
44 op.add_option("-a", "--ap-list", "--ap", "-n", "--nets",# -n is a stopgap
45 action="store_true", default=False,
46 help="List access points")
47 op.add_option("--ap-info", "--ai",
48 help="Info about access point AP (by hw address or UDI(TODO))",
49 metavar="AP")
51 op.add_option("-u", "--usrcon",
52 action="store_true", default=False,
53 help="List user connection settings")
54 op.add_option("-s", "--syscon",
55 action="store_true", default=False,
56 help="List system connection settings")
58 op.add_option("-c", "--actcon",
59 action="store_true", default=False,
60 help="List active connections")
62 op.add_option("--demo",
63 action="store_true", default=False,
64 help="Run a random demonstration of the API")
65 op.add_option("--activate-connection",
66 help="raw API: activate the KIND(user/system) connection CON on device DEV using AP",
67 metavar="[KIND],CON,DEV,[AP]")
69 (options, args) = op.parse_args()
71 nm = NetworkManager()
73 true_choices = ["1", "on", "yes", "true"]
74 if options.wifi != None:
75 nm["WirelessEnabled"] = options.wifi in true_choices
76 if options.online != None:
77 nm.Sleep(not options.online in true_choices)
78 if options.state:
79 print nm["State"]
80 if options.whe:
81 print nm["WirelessHardwareEnabled"]
82 # style option: pretend that properties are methods (er, python properties)
83 # nm["WirelessEnabled"] -> nm.WirelessEnabled() (er, nm.WirelessEnabled )
85 if options.device_list:
86 devs = nm.GetDevices()
87 for dev in devs:
88 print dev["Interface"], dev["DeviceType"], dev["State"]
90 # --device-info, TODO clean up
91 def get_device(dev_spec, hint):
92 candidates = []
93 # print "Hint:", hint
94 devs = NetworkManager().GetDevices()
95 for dev in devs:
96 # print dev
97 if dev._settings_type() == hint:
98 candidates.append(dev)
99 # print "Candidates:", candidates
100 if len(candidates) == 1:
101 return candidates[0]
102 for dev in devs:
103 if dev["Interface"] == dev_spec:
104 return dev
105 print "Device '%s' not found" % dev_spec
106 return None
108 def dump_prop(obj, prop_name):
109 print "%s: %s" %(prop_name, obj[prop_name])
111 def dump_props(obj, *prop_names):
112 for prop_name in prop_names:
113 dump_prop(obj, prop_name)
115 def dump_ap(ap):
116 dump_props(ap, "Flags", "WpaFlags", "RsnFlags",
117 "Ssid", "Frequency", "HwAddress",
118 "Mode", "MaxBitrate", "Strength")
120 if options.device_info != None:
121 d = get_device(options.device_info, "no hint")
122 if d == None:
123 print "not found"
124 else:
125 dump_props(d, "Udi", "Interface", "Driver", "Capabilities",
126 "Ip4Address", "State", "Ip4Config", "Dhcp4Config",
127 "Managed", "DeviceType")
128 if d._settings_type() == "802-11-wireless":
129 dump_props(d, "Mode", "WirelessCapabilities")
130 aap = d["ActiveAccessPoint"]
131 for ap in d.GetAccessPoints():
132 print " AP:", ap.object_path
133 if ap.object_path == aap.object_path:
134 print " ACTIVE"
135 dump_ap(ap)
136 else:
137 dump_prop(d, "Carrier")
139 if options.ap_list or options.ap_info != None:
140 devs = nm.GetDevices()
141 for dev in filter(lambda d: d._settings_type() == "802-11-wireless", devs):
142 aap = dev["ActiveAccessPoint"]
143 for ap in dev.GetAccessPoints():
144 is_active = ap.object_path == aap.object_path
145 if options.ap_list:
146 active = "*" if is_active else " "
147 print ap["HwAddress"], active, ap["Ssid"]
148 elif ap["HwAddress"] == options.ap_info:
149 print "Active:", is_active
150 dump_ap(ap)
152 #def is_opath(x):
153 # return is_instance(x, str) and x[0] == "/"
155 # move this to networkmanagersettings
156 def get_connection(svc, conn_spec):
157 # if is_opath(conn_spec):
158 # return conn_spec
159 applet = NetworkManagerSettings(svc)
160 for conn in applet.ListConnections():
161 cs = conn.GetSettings()
162 if cs["connection"]["id"] == conn_spec:
163 return conn
164 print "Connection '%s' not found" % conn_spec
165 return None
167 def get_connection_devtype(conn):
168 cs = conn.GetSettings()
169 return cs["connection"]["type"]
171 def list_conections(svc):
172 acs = nm["ActiveConnections"]
173 acos = map(lambda a: a["Connection"].object_path, acs)
175 applet = NetworkManagerSettings(svc)
176 for conn in applet.ListConnections():
177 cs = conn.GetSettings()
178 active = "*" if conn.object_path in acos else " "
179 print active, cs["connection"]["id"], cs["connection"]["type"]
181 if options.usrcon:
182 list_conections(USER_SERVICE)
183 if options.syscon:
184 list_conections(SYSTEM_SERVICE)
186 # this shows we do need to add __str__ to the objects
187 if options.actcon:
188 acs = nm["ActiveConnections"]
189 for ac in acs:
190 cid = ac["Connection"].GetSettings()["connection"]["id"]
191 try:
192 apmac = ac["SpecificObject"]["HwAddress"]
193 except: # no AP for wired. TODO figure out "/" object
194 apmac = ""
195 devs = ", ".join(map(lambda d: d["Interface"], ac["Devices"]))
196 hdr = "(has default route)" if ac["Default"] else ""
197 print ac["State"], cid, apmac, devs, hdr
199 if options.activate_connection != None:
200 (svc, conpath, devpath, appath) = options.activate_connection.split(',')
201 if svc == "" or svc == "user":
202 svc = USER_SERVICE
203 elif svc == "system":
204 svc = SYSTEM_SERVICE
206 conn = get_connection(svc, conpath)
207 hint = get_connection_devtype(conn)
208 dev = get_device(devpath, hint)
209 if appath == "":
210 appath = "/"
211 # nm.WatchState()
212 # TODO make it accept both objects and opaths
213 nm.ActivateConnection(svc, conn, dev, appath)
214 # TODO (optionally) block only until a stable state is reached
215 LOOP = True
217 ######## demo ##########
219 from networkmanager.dbusclient import DBusMio
220 mio = DBusMio(dbus.SystemBus(), "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager")
221 i = mio.Introspect()
222 d = mio.GetDevices()
224 def print_state_changed(*args):
225 print "State changed:", ",".join(map(str,args))
227 if options.demo:
228 nm = NetworkManager()
230 # TODO: generic signal (adapt cnm monitor), print name and args
232 nm._connect_to_signal("StateChanged", print_state_changed)
233 nm["WirelessEnabled"] = "yes"
235 devs = nm.GetDevices()
237 for d in devs:
238 print "\n DEVICE"
239 # TODO: find API for any object
240 d._connect_to_signal("StateChanged", print_state_changed)
242 LOOP = True
244 # TODO wrap this
245 if LOOP:
246 try:
247 print "Entering mainloop"
248 loop.run()
249 except KeyboardInterrupt:
250 print "Loop exited"