Implemented ActiveConnection, --actcon, --usrcon, --syscon.
[cnetworkmanager.git] / cnetworkmanager
blobf684683b73d0ca2fd6fad939c155149dcb96b6f8
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",
41 help="Info about device DEV (by interface or UDI(TODO))",
42 metavar="DEV")
44 op.add_option("-a", "--ap-list", "--ap",
45 action="store_true", default=False,
46 help="List access points")
48 op.add_option("-u", "--usrcon",
49 action="store_true", default=False,
50 help="List user connection settings")
51 op.add_option("-s", "--syscon",
52 action="store_true", default=False,
53 help="List system connection settings")
55 op.add_option("-c", "--actcon",
56 action="store_true", default=False,
57 help="List active connections")
59 op.add_option("--demo",
60 action="store_true", default=False,
61 help="Run a random demonstration of the API")
62 op.add_option("--activate-connection",
63 help="raw API: activate the KIND(user/system) connection CON on device DEV using AP",
64 metavar="[KIND],CON,DEV,[AP]")
66 (options, args) = op.parse_args()
68 nm = NetworkManager()
70 true_choices = ["1", "on", "yes", "true"]
71 if options.wifi != None:
72 nm["WirelessEnabled"] = options.wifi in true_choices
73 if options.online != None:
74 nm.Sleep(not options.online in true_choices)
75 if options.state:
76 print nm["State"]
77 if options.whe:
78 print nm["WirelessHardwareEnabled"]
79 # style option: pretend that properties are methods (er, python properties)
80 # nm["WirelessEnabled"] -> nm.WirelessEnabled() (er, nm.WirelessEnabled )
82 if options.device_list:
83 devs = nm.GetDevices()
84 for dev in devs:
85 print dev["Interface"], dev["DeviceType"], dev["State"]
87 # --device-info, TODO clean up
88 def get_device(dev_spec, hint):
89 candidates = []
90 # print "Hint:", hint
91 devs = NetworkManager().GetDevices()
92 for dev in devs:
93 # print dev
94 if dev._settings_type() == hint:
95 candidates.append(dev)
96 # print "Candidates:", candidates
97 if len(candidates) == 1:
98 return candidates[0]
99 for dev in devs:
100 if dev["Interface"] == dev_spec:
101 return dev
102 print "Device '%s' not found" % dev_spec
103 return None
105 def dump_prop(obj, prop_name):
106 print "%s: %s" %(prop_name, obj[prop_name])
108 def dump_props(obj, *prop_names):
109 for prop_name in prop_names:
110 dump_prop(obj, prop_name)
112 if options.device_info != None:
113 d = get_device(options.device_info, "no hint")
114 if d == None:
115 print "not found"
116 else:
117 dump_props(d, "Udi", "Interface", "Driver", "Capabilities",
118 "Ip4Address", "State", "Ip4Config", "Dhcp4Config",
119 "Managed", "DeviceType")
120 if d._settings_type() == "802-11-wireless":
121 dump_props(d, "Mode", "WirelessCapabilities")
122 aap = d["ActiveAccessPoint"]
123 for ap in d.GetAccessPoints():
124 print " AP:", ap.object_path
125 if ap.object_path == aap.object_path:
126 print " ACTIVE"
127 dump_props(ap, "Flags", "WpaFlags", "RsnFlags",
128 "Ssid", "Frequency", "HwAddress",
129 "Mode", "MaxBitrate", "Strength")
130 # TODO
131 # print "Ssid(2):", ap.Get("org.freedesktop.NetworkManager.AccessPoint", "Ssid", byte_arrays=True)
133 else:
134 dump_prop(d, "Carrier")
136 if options.ap_list:
137 devs = nm.GetDevices()
138 for dev in filter(lambda d: d._settings_type() == "802-11-wireless", devs):
139 aap = dev["ActiveAccessPoint"]
140 for ap in dev.GetAccessPoints():
141 active = "*" if ap.object_path == aap.object_path else " "
142 print ap["HwAddress"], active, ap["Ssid"]
144 #def is_opath(x):
145 # return is_instance(x, str) and x[0] == "/"
147 # move this to networkmanagersettings
148 def get_connection(svc, conn_spec):
149 # if is_opath(conn_spec):
150 # return conn_spec
151 applet = NetworkManagerSettings(svc)
152 for conn in applet.ListConnections():
153 cs = conn.GetSettings()
154 if cs["connection"]["id"] == conn_spec:
155 return conn
156 print "Connection '%s' not found" % conn_spec
157 return None
159 def get_connection_devtype(conn):
160 cs = conn.GetSettings()
161 return cs["connection"]["type"]
163 def list_conections(svc):
164 acs = nm["ActiveConnections"]
165 acos = map(lambda a: a["Connection"].object_path, acs)
167 applet = NetworkManagerSettings(svc)
168 for conn in applet.ListConnections():
169 cs = conn.GetSettings()
170 active = "*" if conn.object_path in acos else " "
171 print active, cs["connection"]["id"], cs["connection"]["type"]
173 if options.usrcon:
174 list_conections(USER_SERVICE)
175 if options.syscon:
176 list_conections(SYSTEM_SERVICE)
178 # this shows we do need to add __str__ to the objects
179 if options.actcon:
180 acs = nm["ActiveConnections"]
181 for ac in acs:
182 cid = ac["Connection"].GetSettings()["connection"]["id"]
183 try:
184 apmac = ac["SpecificObject"]["HwAddress"]
185 except: # no AP for wired. TODO figure out "/" object
186 apmac = ""
187 devs = ", ".join(map(lambda d: d["Interface"], ac["Devices"]))
188 hdr = "(has default route)" if ac["Default"] else ""
189 print ac["State"], cid, apmac, devs, hdr
191 if options.activate_connection != None:
192 (svc, conpath, devpath, appath) = options.activate_connection.split(',')
193 if svc == "" or svc == "user":
194 svc = USER_SERVICE
195 elif svc == "system":
196 svc = SYSTEM_SERVICE
198 conn = get_connection(svc, conpath)
199 hint = get_connection_devtype(conn)
200 dev = get_device(devpath, hint)
201 if appath == "":
202 appath = "/"
203 # nm.WatchState()
204 # TODO make it accept both objects and opaths
205 nm.ActivateConnection(svc, conn, dev, appath)
206 # TODO (optionally) block only until a stable state is reached
207 LOOP = True
209 ######## demo ##########
211 from networkmanager.dbusclient import DBusMio
212 mio = DBusMio(dbus.SystemBus(), "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager")
213 i = mio.Introspect()
214 d = mio.GetDevices()
216 def print_state_changed(*args):
217 print "State changed:", ",".join(map(str,args))
219 if options.demo:
220 nm = NetworkManager()
222 # TODO: generic signal (adapt cnm monitor), print name and args
224 nm._connect_to_signal("StateChanged", print_state_changed)
225 nm["WirelessEnabled"] = "yes"
227 devs = nm.GetDevices()
229 for d in devs:
230 print "\n DEVICE"
231 # TODO: find API for any object
232 d._connect_to_signal("StateChanged", print_state_changed)
234 LOOP = True
236 # TODO wrap this
237 if LOOP:
238 try:
239 print "Entering mainloop"
240 loop.run()
241 except KeyboardInterrupt:
242 print "Loop exited"