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
12 from networkmanager
.util
import Table
14 # must be set before we ask for signals
15 from dbus
.mainloop
.glib
import DBusGMainLoop
16 DBusGMainLoop(set_as_default
=True)
19 loop
= gobject
.MainLoop()
22 from optparse
import OptionParser
24 op
= OptionParser(version
="%prog " + VERSION
)
26 op
.add_option("-t", "--terse",
27 action
="store_true", default
=False,
28 help="No table headings and padding, suitable for parsing")
30 # TODO http://docs.python.org/lib/optparse-adding-new-types.html
31 op
.add_option("-w", "--wifi",
32 choices
=["0","1","off","on","no","yes","false","true"],
34 help="Enable or disable wireless")
35 op
.add_option("-o", "--online",
36 choices
=["0","1","off","on","no","yes","false","true"],
38 help="Enable or disable network at all")
39 op
.add_option("--state",
40 action
="store_true", default
=False,
41 help="Print the NM state")
42 op
.add_option("--we", "--wireless-enabled",
43 action
="store_true", default
=False,
44 help="Print whether the WiFi is enabled")
45 op
.add_option("--whe", "--wireless-hardware-enabled",
46 action
="store_true", default
=False,
47 help="Print whether the WiFi hardware is enabled")
49 op
.add_option("-d", "--device-list", "--dev",
50 action
="store_true", default
=False,
52 op
.add_option("--device-info", "--di",
53 help="Info about device DEV (by interface or UDI(TODO))",
56 op
.add_option("-a", "--ap-list", "--ap", "-n", "--nets",# -n is a stopgap
57 action
="store_true", default
=False,
58 help="List access points")
59 op
.add_option("--ap-info", "--ai",
60 help="Info about access point AP (by hw address or UDI(TODO))",
63 op
.add_option("-u", "--usrcon",
64 action
="store_true", default
=False,
65 help="List user connection settings")
66 op
.add_option("-s", "--syscon",
67 action
="store_true", default
=False,
68 help="List system connection settings")
69 op
.add_option("--con-info", "--ci",
70 help="Info about connection settings ID (of the *user*/system KIND)",
73 op
.add_option("-c", "--actcon",
74 action
="store_true", default
=False,
75 help="List active connections")
77 op
.add_option("--demo",
78 action
="store_true", default
=False,
79 help="Run a random demonstration of the API")
80 op
.add_option("--activate-connection",
81 help="activate the KIND(user/system) connection ID on device DEV using APMAC.",
82 metavar
="[KIND],ID,[DEV],[APMAC]")
83 op
.add_option("-m", "--monitor",
84 action
="store_true", default
=False,
85 help="loop to show dbus signals")
87 op
.add_option("-C", "--connect",
88 help="Connect to a wireless network SSID (creating the configuration using the key options below)",
90 op
.add_option("--unprotected",
91 action
="store_true", default
=False,
92 help="network does not require a key")
93 op
.add_option("--wep-hex",
95 help="use this WEP key of 26 hex digits")
96 op
.add_option("--wep-pass",
98 help="use this WEP passphrase")
99 op
.add_option("--wpa-psk-hex",
101 help="use this WPA key of 64 hex digits")
102 op
.add_option("--wpa-pass",
104 help="use this WPA passphrase")
106 (options
, args
) = op
.parse_args()
108 Table
.terse
= options
.terse
110 nm
= NetworkManager()
112 true_choices
= ["1", "on", "yes", "true"]
113 if options
.wifi
!= None:
114 nm
["WirelessEnabled"] = options
.wifi
in true_choices
116 print nm
["WirelessEnabled"]
117 if options
.online
!= None:
119 nm
.Sleep(not options
.online
in true_choices
)
120 except dbus
.exceptions
.DBusException
, e
:
121 if e
.get_dbus_name() != "org.freedesktop.NetworkManager.AlreadyAsleepOrAwake":
127 print nm
["WirelessHardwareEnabled"]
128 # style option: pretend that properties are methods (er, python properties)
129 # nm["WirelessEnabled"] -> nm.WirelessEnabled() (er, nm.WirelessEnabled )
131 if options
.device_list
:
132 devs
= nm
.GetDevices()
133 t
= Table("Interface", "Type", "State")
135 t
.row(dev
["Interface"], dev
["DeviceType"], dev
["State"])
138 # --device-info, TODO clean up
139 def get_device(dev_spec
, hint
):
141 # print "Hint:", hint
142 devs
= NetworkManager().GetDevices()
145 if dev
._settings
_type
() == hint
:
146 candidates
.append(dev
)
147 # print "Candidates:", candidates
148 if len(candidates
) == 1:
151 if dev
["Interface"] == dev_spec
:
153 print "Device '%s' not found" % dev_spec
156 if options
.device_info
!= None:
157 d
= get_device(options
.device_info
, "no hint")
161 props
= ["Udi", "Interface", "Driver", "Capabilities",
162 # "Ip4Address", # bogus, remembers last addr even after disused
164 # "Ip4Config", "Dhcp4Config", # only __repr__
165 "Managed", "DeviceType"]
166 if d
._settings
_type
() == "802-11-wireless":
167 props
.extend(["Mode", "WirelessCapabilities"])
168 elif d
._settings
_type
() == "802-3-ethernet":
169 props
.extend(["Carrier"])
171 print Table
.from_items(d
, *props
)
174 devs
= nm
.GetDevices()
175 # nm.get_wifi_devices()
176 # nm.get_devices_by_type(Device.Type.WIRELESS)
177 for dev
in filter(lambda d
: d
._settings
_type
() == "802-11-wireless", devs
):
178 aap
= dev
["ActiveAccessPoint"]
179 t
= Table("Active", "HwAddress", "Ssid")
180 for ap
in dev
.GetAccessPoints():
181 active
= "*" if ap
.object_path
== aap
.object_path
else ""
182 t
.row(active
, ap
["HwAddress"], ap
["Ssid"])
185 if options
.ap_info
!= None:
186 devs
= nm
.GetDevices()
187 for dev
in filter(lambda d
: d
._settings
_type
() == "802-11-wireless", devs
):
188 aap
= dev
["ActiveAccessPoint"]
189 for ap
in dev
.GetAccessPoints():
190 if ap
["HwAddress"] == options
.ap_info
:
191 t
= Table
.from_items(ap
, "Flags", "WpaFlags", "RsnFlags",
192 "Ssid", "Frequency", "HwAddress",
193 "Mode", "MaxBitrate", "Strength")
194 t
.row("Active", ap
.object_path
== aap
.object_path
)
198 # return is_instance(x, str) and x[0] == "/"
200 # move this to networkmanagersettings
201 def get_connection(svc
, conn_spec
):
202 if svc
== "" or svc
== "user":
204 elif svc
== "system":
207 # if is_opath(conn_spec):
209 applet
= NetworkManagerSettings(svc
)
210 for conn
in applet
.ListConnections():
211 cs
= conn
.GetSettings()
212 if cs
["connection"]["id"] == conn_spec
:
214 print "Connection '%s' not found" % conn_spec
217 def get_connection_devtype(conn
):
218 cs
= conn
.GetSettings()
219 return cs
["connection"]["type"]
221 def list_conections(svc
):
222 acs
= nm
["ActiveConnections"]
223 acos
= map(lambda a
: a
["Connection"].object_path
, acs
)
226 applet
= NetworkManagerSettings(svc
)
227 except dbus
.exceptions
.DBusException
, e
:
230 t
= Table("Active", "Name", "Type")
231 for conn
in applet
.ListConnections():
232 cs
= conn
.GetSettings()
233 active
= "*" if conn
.object_path
in acos
else ""
234 t
.row(active
, cs
["connection"]["id"], cs
["connection"]["type"])
238 list_conections(USER_SERVICE
)
240 list_conections(SYSTEM_SERVICE
)
242 if options
.con_info
!= None:
243 (svc
, con
) = ("", options
.con_info
)
245 (svc
, con
) = con
.split(",")
247 c
= get_connection(svc
, con
)
249 print Table
.from_nested_dict(cs
)
250 type = cs
["connection"]["type"]
251 secu
= cs
[type]["security"]
252 cse
= c
.GetSecrets(secu
, [], False)
253 print Table
.from_nested_dict(cse
)
255 # this shows we do need to add __str__ to the objects
257 acs
= nm
["ActiveConnections"]
258 t
= Table("State", "Name", "AP", "Devices", "Default route")
260 cid
= ac
["Connection"].GetSettings()["connection"]["id"]
262 apmac
= ac
["SpecificObject"]["HwAddress"]
263 except: # no AP for wired. TODO figure out "/" object
265 devs
= ", ".join(map(lambda d
: d
["Interface"], ac
["Devices"]))
266 hdr
= "*" if ac
["Default"] else ""
267 t
.row(ac
["State"], cid
, apmac
, devs
, hdr
)
274 def print_state_changed(*args
):
275 print time
.strftime("(%X)"),
276 print "State:", ", ".join(map(str,args
))
278 if options
.connect
!= None:
279 ssid
= options
.connect
281 us
= NetworkManagerUserSettings([]) # request_name may fail
282 except dbus
.exceptions
.NameExistsException
, e
:
283 print "Another applet is running:", e
287 if options
.unprotected
:
288 c
= settings
.WiFi(ssid
)
289 if options
.wep_hex
!= None:
290 c
= settings
.Wep(ssid
, "", options
.wep_hex
)
291 if options
.wep_pass
!= None:
292 c
= settings
.Wep(ssid
, options
.wep_pass
)
293 if options
.wpa_psk_hex
!= None:
294 c
= settings
.WpaPsk(ssid
, "", options
.wpa_psk_hex
)
295 if options
.wpa_pass
!= None:
296 c
= settings
.WpaPsk(ssid
, options
.wpa_pass
)
298 print "Error, connection settings not specified"
302 svc_conn
= us
.addCon(c
.conmap
)
303 hint
= svc_conn
.settings
["connection"]["type"]
304 dev
= get_device("", hint
)
306 nm
._connect
_to
_signal
("StateChanged", print_state_changed
)
307 # must be async because ourselves are providing the service
308 dummy_handler
= lambda *args
: None
309 nm
.ActivateConnection(svc
, svc_conn
, dev
, appath
,
310 reply_handler
=dummy_handler
,
311 error_handler
=dummy_handler
)
314 if options
.activate_connection
!= None:
315 (svc
, conpath
, devpath
, appath
) = options
.activate_connection
.split(',')
316 conn
= get_connection(svc
, conpath
)
317 hint
= get_connection_devtype(conn
)
318 dev
= get_device(devpath
, hint
)
321 nm
._connect
_to
_signal
("StateChanged", print_state_changed
)
322 # TODO make it accept both objects and opaths
323 nm
.ActivateConnection(svc
, conn
, dev
, appath
)
324 # TODO (optionally) block only until a stable state is reached
328 ######## demo ##########
330 from dbusclient
import DBusMio
331 mio
= DBusMio(dbus
.SystemBus(), "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager")
336 nm
= NetworkManager()
338 # TODO: generic signal (adapt cnm monitor), print name and args
340 nm
["WirelessEnabled"] = "yes"
342 devs
= nm
.GetDevices()
346 # TODO: find API for any object
347 d
._connect
_to
_signal
("StateChanged", print_state_changed
)
350 ######## demo end ##########
355 print "Entering mainloop"
357 except KeyboardInterrupt: