7 from networkmanager
import NetworkManager
8 from networkmanager
.monitor
import Monitor
9 from networkmanager
.applet
import NetworkManagerSettings
, SYSTEM_SERVICE
, USER_SERVICE
10 from networkmanager
.applet
.service
import NetworkManagerUserSettings
11 import networkmanager
.applet
.settings
as settings
13 # must be set before we ask for signals
14 from dbus
.mainloop
.glib
import DBusGMainLoop
15 DBusGMainLoop(set_as_default
=True)
18 loop
= gobject
.MainLoop()
21 from optparse
import OptionParser
23 op
= OptionParser(version
="%prog " + VERSION
)
25 # TODO http://docs.python.org/lib/optparse-adding-new-types.html
26 op
.add_option("-w", "--wifi",
27 choices
=["0","1","off","on","no","yes","false","true"],
29 help="Enable or disable wireless")
30 op
.add_option("-o", "--online",
31 choices
=["0","1","off","on","no","yes","false","true"],
33 help="Enable or disable network at all")
34 op
.add_option("--state",
35 action
="store_true", default
=False,
36 help="Print the NM state")
37 op
.add_option("--whe", "--wireless-hardware-enabled",
38 action
="store_true", default
=False,
39 help="Print whether the WiFi is enabled")
41 op
.add_option("-d", "--device-list", "--dev",
42 action
="store_true", default
=False,
44 op
.add_option("--device-info", "--di",
45 help="Info about device DEV (by interface or UDI(TODO))",
48 op
.add_option("-a", "--ap-list", "--ap", "-n", "--nets",# -n is a stopgap
49 action
="store_true", default
=False,
50 help="List access points")
51 op
.add_option("--ap-info", "--ai",
52 help="Info about access point AP (by hw address or UDI(TODO))",
55 op
.add_option("-u", "--usrcon",
56 action
="store_true", default
=False,
57 help="List user connection settings")
58 op
.add_option("-s", "--syscon",
59 action
="store_true", default
=False,
60 help="List system connection settings")
62 op
.add_option("-c", "--actcon",
63 action
="store_true", default
=False,
64 help="List active connections")
66 op
.add_option("--demo",
67 action
="store_true", default
=False,
68 help="Run a random demonstration of the API")
69 op
.add_option("--activate-connection",
70 help="activate the KIND(user/system) connection ID on device DEV using APMAC.",
71 metavar
="[KIND],ID,[DEV],[APMAC]")
72 op
.add_option("-m", "--monitor",
73 action
="store_true", default
=False,
74 help="loop to show dbus signals")
76 op
.add_option("-C", "--connect",
77 help="Connect to a wireless network SSID (creating the configuration using the key options below)",
79 op
.add_option("--unprotected",
80 action
="store_true", default
=False,
81 help="network does not require a key")
82 op
.add_option("--wep-hex",
84 help="use this WEP key of 26 hex digits")
85 op
.add_option("--wep-pass",
87 help="use this WEP passphrase")
88 op
.add_option("--wpa-psk-hex",
90 help="use this WPA key of 64 hex digits")
91 op
.add_option("--wpa-pass",
93 help="use this WPA passphrase")
95 (options
, args
) = op
.parse_args()
99 true_choices
= ["1", "on", "yes", "true"]
100 if options
.wifi
!= None:
101 nm
["WirelessEnabled"] = options
.wifi
in true_choices
102 if options
.online
!= None:
103 nm
.Sleep(not options
.online
in true_choices
)
107 print nm
["WirelessHardwareEnabled"]
108 # style option: pretend that properties are methods (er, python properties)
109 # nm["WirelessEnabled"] -> nm.WirelessEnabled() (er, nm.WirelessEnabled )
111 if options
.device_list
:
112 devs
= nm
.GetDevices()
114 print dev
["Interface"], dev
["DeviceType"], dev
["State"]
116 # --device-info, TODO clean up
117 def get_device(dev_spec
, hint
):
119 # print "Hint:", hint
120 devs
= NetworkManager().GetDevices()
123 if dev
._settings
_type
() == hint
:
124 candidates
.append(dev
)
125 # print "Candidates:", candidates
126 if len(candidates
) == 1:
129 if dev
["Interface"] == dev_spec
:
131 print "Device '%s' not found" % dev_spec
134 def dump_prop(obj
, prop_name
):
135 print "%s: %s" %(prop_name
, obj
[prop_name
])
137 def dump_props(obj
, *prop_names
):
138 for prop_name
in prop_names
:
139 dump_prop(obj
, prop_name
)
142 dump_props(ap
, "Flags", "WpaFlags", "RsnFlags",
143 "Ssid", "Frequency", "HwAddress",
144 "Mode", "MaxBitrate", "Strength")
146 if options
.device_info
!= None:
147 d
= get_device(options
.device_info
, "no hint")
151 dump_props(d
, "Udi", "Interface", "Driver", "Capabilities",
152 "Ip4Address", "State", "Ip4Config", "Dhcp4Config",
153 "Managed", "DeviceType")
154 if d
._settings
_type
() == "802-11-wireless":
155 dump_props(d
, "Mode", "WirelessCapabilities")
156 aap
= d
["ActiveAccessPoint"]
157 for ap
in d
.GetAccessPoints():
158 print " AP:", ap
.object_path
159 if ap
.object_path
== aap
.object_path
:
163 dump_prop(d
, "Carrier")
165 if options
.ap_list
or options
.ap_info
!= None:
166 devs
= nm
.GetDevices()
167 for dev
in filter(lambda d
: d
._settings
_type
() == "802-11-wireless", devs
):
168 aap
= dev
["ActiveAccessPoint"]
169 for ap
in dev
.GetAccessPoints():
170 is_active
= ap
.object_path
== aap
.object_path
172 active
= "*" if is_active
else " "
173 print ap
["HwAddress"], active
, ap
["Ssid"]
174 elif ap
["HwAddress"] == options
.ap_info
:
175 print "Active:", is_active
179 # return is_instance(x, str) and x[0] == "/"
181 # move this to networkmanagersettings
182 def get_connection(svc
, conn_spec
):
183 # if is_opath(conn_spec):
185 applet
= NetworkManagerSettings(svc
)
186 for conn
in applet
.ListConnections():
187 cs
= conn
.GetSettings()
188 if cs
["connection"]["id"] == conn_spec
:
190 print "Connection '%s' not found" % conn_spec
193 def get_connection_devtype(conn
):
194 cs
= conn
.GetSettings()
195 return cs
["connection"]["type"]
197 def list_conections(svc
):
198 acs
= nm
["ActiveConnections"]
199 acos
= map(lambda a
: a
["Connection"].object_path
, acs
)
201 applet
= NetworkManagerSettings(svc
)
202 for conn
in applet
.ListConnections():
203 cs
= conn
.GetSettings()
204 active
= "*" if conn
.object_path
in acos
else " "
205 print active
, cs
["connection"]["id"], cs
["connection"]["type"]
208 list_conections(USER_SERVICE
)
210 list_conections(SYSTEM_SERVICE
)
212 # this shows we do need to add __str__ to the objects
214 acs
= nm
["ActiveConnections"]
216 cid
= ac
["Connection"].GetSettings()["connection"]["id"]
218 apmac
= ac
["SpecificObject"]["HwAddress"]
219 except: # no AP for wired. TODO figure out "/" object
221 devs
= ", ".join(map(lambda d
: d
["Interface"], ac
["Devices"]))
222 hdr
= "(has default route)" if ac
["Default"] else ""
223 print ac
["State"], cid
, apmac
, devs
, hdr
229 def print_state_changed(*args
):
230 print time
.strftime("(%X)"),
231 print "State:", ", ".join(map(str,args
))
233 if options
.connect
!= None:
234 ssid
= options
.connect
236 us
= NetworkManagerUserSettings([]) # request_name may fail
237 except dbus
.exceptions
.NameExistsException
, e
:
238 print "Another applet is running:", e
242 if options
.unprotected
:
243 c
= settings
.WiFi(ssid
)
244 if options
.wep_hex
!= None:
245 c
= settings
.Wep(ssid
, "", options
.wep_hex
)
246 if options
.wep_pass
!= None:
247 c
= settings
.Wep(ssid
, options
.wep_pass
)
248 if options
.wpa_psk_hex
!= None:
249 c
= settings
.WpaPsk(ssid
, "", options
.wpa_psk_hex
)
250 if options
.wpa_pass
!= None:
251 c
= settings
.WpaPsk(ssid
, options
.wpa_pass
)
253 print "Error, connection settings not specified"
257 svc_conn
= us
.addCon(c
.conmap
)
258 hint
= svc_conn
.settings
["connection"]["type"]
259 dev
= get_device("", hint
)
261 nm
._connect
_to
_signal
("StateChanged", print_state_changed
)
262 # must be async because ourselves are providing the service
263 dummy_handler
= lambda *args
: None
264 nm
.ActivateConnection(svc
, svc_conn
, dev
, appath
,
265 reply_handler
=dummy_handler
,
266 error_handler
=dummy_handler
)
269 if options
.activate_connection
!= None:
270 (svc
, conpath
, devpath
, appath
) = options
.activate_connection
.split(',')
271 if svc
== "" or svc
== "user":
273 elif svc
== "system":
276 conn
= get_connection(svc
, conpath
)
277 hint
= get_connection_devtype(conn
)
278 dev
= get_device(devpath
, hint
)
281 nm
._connect
_to
_signal
("StateChanged", print_state_changed
)
282 # TODO make it accept both objects and opaths
283 nm
.ActivateConnection(svc
, conn
, dev
, appath
)
284 # TODO (optionally) block only until a stable state is reached
288 ######## demo ##########
290 from dbusclient
import DBusMio
291 mio
= DBusMio(dbus
.SystemBus(), "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager")
296 nm
= NetworkManager()
298 # TODO: generic signal (adapt cnm monitor), print name and args
300 nm
["WirelessEnabled"] = "yes"
302 devs
= nm
.GetDevices()
306 # TODO: find API for any object
307 d
._connect
_to
_signal
("StateChanged", print_state_changed
)
310 ######## demo end ##########
315 print "Entering mainloop"
317 except KeyboardInterrupt: