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)
14 loop
= gobject
.MainLoop()
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"],
25 help="Enable or disable wireless")
26 op
.add_option("-o", "--online",
27 choices
=["0","1","off","on","no","yes","false","true"],
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,
40 op
.add_option("--device-info", "--di",
41 help="Info about device DEV (by interface or UDI(TODO))",
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))",
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()
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
)
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()
88 print dev
["Interface"], dev
["DeviceType"], dev
["State"]
90 # --device-info, TODO clean up
91 def get_device(dev_spec
, hint
):
94 devs
= NetworkManager().GetDevices()
97 if dev
._settings
_type
() == hint
:
98 candidates
.append(dev
)
99 # print "Candidates:", candidates
100 if len(candidates
) == 1:
103 if dev
["Interface"] == dev_spec
:
105 print "Device '%s' not found" % dev_spec
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
)
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")
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
:
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
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
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):
159 applet
= NetworkManagerSettings(svc
)
160 for conn
in applet
.ListConnections():
161 cs
= conn
.GetSettings()
162 if cs
["connection"]["id"] == conn_spec
:
164 print "Connection '%s' not found" % conn_spec
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"]
182 list_conections(USER_SERVICE
)
184 list_conections(SYSTEM_SERVICE
)
186 # this shows we do need to add __str__ to the objects
188 acs
= nm
["ActiveConnections"]
190 cid
= ac
["Connection"].GetSettings()["connection"]["id"]
192 apmac
= ac
["SpecificObject"]["HwAddress"]
193 except: # no AP for wired. TODO figure out "/" object
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":
203 elif svc
== "system":
206 conn
= get_connection(svc
, conpath
)
207 hint
= get_connection_devtype(conn
)
208 dev
= get_device(devpath
, hint
)
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
217 ######## demo ##########
219 from networkmanager
.dbusclient
import DBusMio
220 mio
= DBusMio(dbus
.SystemBus(), "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager")
224 def print_state_changed(*args
):
225 print "State changed:", ",".join(map(str,args
))
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()
239 # TODO: find API for any object
240 d
._connect
_to
_signal
("StateChanged", print_state_changed
)
247 print "Entering mainloop"
249 except KeyboardInterrupt: