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",
41 help="Info about device DEV (by interface or UDI(TODO))",
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()
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
)
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()
85 print dev
["Interface"], dev
["DeviceType"], dev
["State"]
87 # --device-info, TODO clean up
88 def get_device(dev_spec
, hint
):
91 devs
= NetworkManager().GetDevices()
94 if dev
._settings
_type
() == hint
:
95 candidates
.append(dev
)
96 # print "Candidates:", candidates
97 if len(candidates
) == 1:
100 if dev
["Interface"] == dev_spec
:
102 print "Device '%s' not found" % dev_spec
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")
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
:
127 dump_props(ap
, "Flags", "WpaFlags", "RsnFlags",
128 "Ssid", "Frequency", "HwAddress",
129 "Mode", "MaxBitrate", "Strength")
131 # print "Ssid(2):", ap.Get("org.freedesktop.NetworkManager.AccessPoint", "Ssid", byte_arrays=True)
134 dump_prop(d
, "Carrier")
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"]
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):
151 applet
= NetworkManagerSettings(svc
)
152 for conn
in applet
.ListConnections():
153 cs
= conn
.GetSettings()
154 if cs
["connection"]["id"] == conn_spec
:
156 print "Connection '%s' not found" % conn_spec
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"]
174 list_conections(USER_SERVICE
)
176 list_conections(SYSTEM_SERVICE
)
178 # this shows we do need to add __str__ to the objects
180 acs
= nm
["ActiveConnections"]
182 cid
= ac
["Connection"].GetSettings()["connection"]["id"]
184 apmac
= ac
["SpecificObject"]["HwAddress"]
185 except: # no AP for wired. TODO figure out "/" object
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":
195 elif svc
== "system":
198 conn
= get_connection(svc
, conpath
)
199 hint
= get_connection_devtype(conn
)
200 dev
= get_device(devpath
, hint
)
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
209 ######## demo ##########
211 from networkmanager
.dbusclient
import DBusMio
212 mio
= DBusMio(dbus
.SystemBus(), "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager")
216 def print_state_changed(*args
):
217 print "State changed:", ",".join(map(str,args
))
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()
231 # TODO: find API for any object
232 d
._connect
_to
_signal
("StateChanged", print_state_changed
)
239 print "Entering mainloop"
241 except KeyboardInterrupt: