2 # cnetworkmanager: Command Line Interface for NetworkManager
3 # by: http://en.opensuse.org/User:Mvidner
4 # license: http://www.gnu.org/licenses/gpl-2.0.html or later
7 print "cnetworkmanager %s - Command Line Interface for NetworkManager" % VERSION
12 import ConfigParser
# knm config
13 from optparse
import OptionParser
19 print "Install python-1-dbus.rpm or python-dbus.deb"
21 import xml
.dom
.minidom
25 # todo - only if loop wanted
26 print "Install python-gobject2.rpm or python-gobject.deb"
28 # python-gnome.rpm has gconf for nm-applet...
32 from dbus
.mainloop
.glib
import DBusGMainLoop
33 DBusGMainLoop(set_as_default
=True)
37 bus
= dbus
.SystemBus()
39 # FOOC = connection (service) string
40 # FOOI = interface string
43 # foopi = property interface
44 NMC
= 'org.freedesktop.NetworkManager'
46 PI
= 'org.freedesktop.DBus.Properties'
47 SSC
= "org.freedesktop.NetworkManagerSystemSettings"
48 USC
= "org.freedesktop.NetworkManagerUserSettings"
51 ii
= dbus
.Interface(obj
, 'org.freedesktop.DBus.Introspectable')
55 # TODO: pull them from introspection.xml
56 NM_STATE
= ["UNKNOWN", "ASLEEP", "CONNECTING", "CONNECTED", "DISCONNECTED",]
58 def __init__(self
, opath
):
60 self
.nmo
= bus
.get_object(NMC
, self
.opath
)
61 self
.nmi
= dbus
.Interface(self
.nmo
, NMI
)
62 self
.nmpi
= dbus
.Interface(self
.nmo
, PI
)
65 "Dumps its own info (not owned objects)."
71 for device
in self
.Devices():
75 print "Active Connections"
76 aconns
= self
.ActiveConnections()
81 print "Wifi Networks:"
82 for dev
in self
.Devices():
85 def reply_handler(self
, opath
):
86 print "Connected:", opath
88 def err_handler(self
, *args
):
91 def silent_handler(self
, *args
):
95 def quitter_handler(self
, *args
):
96 # exit the loop that runs only because of us
100 def ActivateConnection(self
, conn
, device
, ap
):
101 # passing *_handler makes the call asynchronous
102 self
.nmi
.ActivateConnection(USC
,
103 conn
.__dbus
_object
_path
__,
106 reply_handler
=self
.reply_handler
,
107 error_handler
=self
.err_handler
,
111 "Detects NM version and chooses appropriate class"
113 nmo
= bus
.get_object(NMC
, opath
)
114 nmi
= dbus
.Interface(nmo
, NMI
)
116 dummy
= nmi
.getDevices()
118 except dbus
.exceptions
.DBusException
:
122 def SetWifiEnabled(self
, v
):
123 # TODO: async call, catch the state signal and exit
124 # weird: synchronous call works, but times out
125 # asynchronous call does not work
126 self
.nmi
.setWirelessEnabled(v
,
127 reply_handler
=self
.quitter_handler
,
128 error_handler
=self
.quitter_handler
)
132 def SetOnline(self
, v
):
133 self
.nmi
.sleep(not v
,
134 reply_handler
=self
.quitter_handler
,
135 error_handler
=self
.quitter_handler
)
140 print "State:", self
.NM_STATE
[self
.nmi
.state()]
141 (we
, whe
) = self
.nmi
.getWirelessEnabled()
142 print "Wifi enabled:", bool(we
)
143 print "Wifi HW enabled:", bool(whe
)
145 dup
= self
.nmi
.getDialup()
146 except dbus
.exceptions
.DBusException
, e
:
147 if e
.get_dbus_name() == "org.freedesktop.NetworkManager.NoDialup":
152 opaths
= self
.nmi
.getDevices()
153 return map(cDevice_06
, opaths
)
155 def ActiveConnections(self
):
156 return [] # at most one active connection, FIXME find it
160 def SetWifiEnabled(self
, v
):
161 self
.nmpi
.Set(NMI
, "WirelessEnabled", v
)
163 def SetOnline(self
, v
):
164 self
.nmi
.Sleep(not v
)
167 print "State:", self
.NM_STATE
[self
.nmpi
.Get(NMI
, "State")]
168 print "Wifi enabled:", self
.nmpi
.Get(NMI
, "WirelessEnabled")
169 print "Wifi HW enabled:", self
.nmpi
.Get(NMI
, "WirelessHardwareEnabled")
172 opaths
= self
.nmi
.GetDevices()
173 return map(cDevice_07
, opaths
)
175 def ActiveConnections(self
):
176 aconns
= self
.nmpi
.Get(NMI
, "ActiveConnections")
177 return map(cActiveConnection
, aconns
)
181 class cActiveConnection
:
182 def __init__(self
, opath
):
187 co
= bus
.get_object(NMC
, self
.opath
)
188 copi
= dbus
.Interface(co
, PI
)
189 for P
in ["ServiceName", "Connection", "SharedServiceName", "SharedConnection", "SpecificObject",]:
190 print " %s: %s" % (P
, copi
.Get(NMI
, P
))
191 devs
= copi
.Get(NMI
, "Devices")
196 def bitmask_str(map, value
):
198 for mask
in sorted(map.keys()):
199 if value
& mask
: ret
.append(map[mask
])
204 def __init__(self
, opath
):
206 self
.devo
= bus
.get_object(NMC
, self
.opath
)
207 self
.devi
= dbus
.Interface(self
.devo
, NMI
+ ".Device")
208 self
.devpi
= dbus
.Interface(self
.devo
, PI
)
212 DEVICE_TYPE
= ["UNKNOWN", "802_3_ETHERNET", "802_11_WIRELESS",
215 def DeviceType(self
):
216 return self
.DEVICE_TYPE
[self
.DeviceType0()]
218 def ip_str(self
, i32
):
220 ret
.append("%d" % (i32
% 256))
222 ret
.append("%d" % (i32
% 256))
224 ret
.append("%d" % (i32
% 256))
226 ret
.append("%d" % (i32
% 256))
230 def DumpIp4Config(self
, opath
):
231 print " Ip4Config:", opath
232 o
= bus
.get_object(NMC
, opath
)
233 pi
= dbus
.Interface(o
, PI
)
235 for P
in ["Address", "Netmask", "Broadcast", "Gateway",]: # beta2?
236 print " %s: %s" % (P
, self
.ip_str(pi
.Get(NMI
, P
)))
239 addrs
= pi
.Get(NMI
, "Addresses")
241 print " %s/%s via %s" % tuple(map(self
.ip_str
, addr
))
242 hn
= pi
.Get(NMI
, "Hostname")
243 print " Hostname:", hn
244 nss
= pi
.Get(NMI
, "Nameservers")
245 print " Nameservers:", " ".join(map(self
.ip_str
, nss
))
246 doms
= pi
.Get(NMI
, "Domains")
247 print " Domains:", " ".join(doms
)
248 nisd
= pi
.Get(NMI
, "NisDomain")
249 print " NisDomain:", nisd
250 niss
= pi
.Get(NMI
, "NisServers")
251 print " NisServers:", " ".join(map(self
.ip_str
, niss
))
253 NM_DEVICE_CAP
= {1: "NM_SUPPORTED", 2: "CARRIER_DETECT", 4: "SCANNING", }
257 print "Device:", self
.opath
260 IW_MODE
= ["AUTO", "ADHOC", "INFRA", "MASTER",
261 "REPEAT", "SECOND", "MONITOR",]
264 for ap
in self
.APs():
272 class cDevice_06(cDevice
):
273 def DeviceType0(self
):
275 self
.dt
= self
.devi
.getProperties()[2]
277 self
.__class
__ = cDeviceEth_06
279 self
.__class
__ = cDeviceWifi_06
283 "UNKNOWN", "DEVICE_PREPARE", "DEVICE_CONFIG", "NEED_USER_KEY",
284 "IP_CONFIG_START", "IP_CONFIG_GET", "IP_CONFIG_COMMIT",
285 "ACTIVATED", "FAILED", "CANCELLED", ]
289 print " Driver:", self
.devi
.getDriver()
290 props
= self
.devi
.getProperties() # osusb ussss sssii biuus as
291 print " Self:", props
[0] # o
292 print " Interface:", props
[1] # s
293 print " Type:", self
.DEVICE_TYPE
[props
[2]] # u
294 print " UDI:", props
[3] # s
295 print " Active:", bool(props
[4]) # b
296 print " Activation Stage:", self
.NM_ACT_STAGE
[props
[5]] # u
297 print " IP:", props
[6] # s
298 print " Mask:", props
[7] # s
299 print " Bcast:", props
[8] # s
300 print " HwAddress:", props
[9] # s
301 print " GW:", props
[10] # s
302 print " NS1:", props
[11] # s
303 print " NS2:", props
[12] # s
306 class cDeviceEth_06(cDevice_06
, cDeviceEth
):
308 props
= self
.devi
.getProperties() # osusb ussss sssii biuus as
309 print " Link Active:", bool(props
[15]) # b
310 print " Speed:", props
[16] # i
311 print " Generic Capabilities:", bitmask_str(self
.NM_DEVICE_CAP
, props
[17]) # u
313 class cDeviceWifi_06(cDevice_06
):
315 0x00000001: "PROTO_NONE",
316 0x00000002: "PROTO_WEP",
317 0x00000004: "PROTO_WPA",
318 0x00000008: "PROTO_WPA2",
319 0x00000010: "RESERVED1",
320 0x00000020: "RESERVED2",
321 0x00000040: "KEY_MGMT_PSK",
322 0x00000080: "KEY_MGMT_802_1X",
323 0x00000100: "RESERVED3",
324 0x00000200: "RESERVED4",
325 0x00000400: "RESERVED5",
326 0x00000800: "RESERVED6",
327 0x00001000: "CIPHER_WEP40",
328 0x00002000: "CIPHER_WEP104",
329 0x00004000: "CIPHER_TKIP",
330 0x00008000: "CIPHER_CCMP",
334 self
.wdevi
= dbus
.Interface(self
.devo
, NMI
+ ".Device.Wireless")
335 aps
= self
.devi
.getProperties()[20]
336 return map(cAP_06
, aps
)
339 props
= self
.devi
.getProperties() # osusb ussss sssii biuus as
340 print " Mode:", self
.IW_MODE
[props
[13]] # i
341 print " Strength:", props
[14] # i
342 print " Link Active:", bool(props
[15]) # b
343 print " Speed:", props
[16] # i
344 print " Generic Capabilities:", bitmask_str(self
.NM_DEVICE_CAP
, props
[17]) # u
345 print " Capabilities:", bitmask_str(self
.NM_802_11_CAP
, props
[18]) # u
346 print " Current net:", props
[19] # s
347 nets
= props
[20] # as
348 print " Seen nets:", " ".join(nets
)
350 print " Access Points"
351 for ap
in self
.APs():
354 class cDevice_07(cDevice
):
355 def DeviceType0(self
):
357 self
.dt
= self
.devpi
.Get(NMI
, "DeviceType")
359 self
.__class
__ = cDeviceEth_07
361 self
.__class
__ = cDeviceWifi_07
365 "UNKNOWN", "UNMANAGED", "UNAVAILABLE", "DISCONNECTED", "PREPARE",
366 "CONFIG", "NEED_AUTH", "IP_CONFIG", "ACTIVATED", "FAILED",]
371 # "Ip4Config", only for NM_DEVICE_STATE_ACTIVATED
372 for P
in ["Udi", "Interface", "Driver",]:
373 print " %s: %s" % (P
, self
.devpi
.Get(NMI
, P
))
374 addr
= self
.devpi
.Get(NMI
, "Ip4Address")
375 print " Ip4Address:", self
.ip_str(addr
)
376 caps
= self
.devpi
.Get(NMI
, "Capabilities")
377 print " Capabilities:", bitmask_str(self
.NM_DEVICE_CAP
, caps
)
378 state
= self
.NM_DEVICE_STATE
[self
.devpi
.Get(NMI
, "State")]
379 print " Dev State:", state
380 if state
== "ACTIVATED":
381 self
.DumpIp4Config(self
.devpi
.Get(NMI
, "Ip4Config"))
383 dt
= self
.DeviceType()
384 print " Dev Type:", dt
387 class cDeviceEth_07(cDevice_07
, cDeviceEth
):
389 for P
in ["HwAddress", "Speed", "Carrier"]:
390 print " %s: %s" % (P
, self
.devpi
.Get(NMI
, P
))
392 class cDeviceWifi_07(cDevice_07
):
393 NM_802_11_DEVICE_CAP
= {1:"CIPHER_WEP40", 2:"CIPHER_WEP104",
394 4:"CIPHER_TKIP", 8:"CIPHER_CCMP",
398 self
.wdevi
= dbus
.Interface(self
.devo
, NMI
+ ".Device.Wireless")
399 aps
= self
.wdevi
.GetAccessPoints()
400 return map(cAP_07
, aps
)
403 print " Dev Mode:", self
.IW_MODE
[self
.devpi
.Get(NMI
, "Mode")]
404 wcaps
= self
.devpi
.Get(NMI
, "WirelessCapabilities")
405 print " Wifi Capabilities:", bitmask_str(self
.NM_802_11_DEVICE_CAP
, wcaps
)
406 for P
in ["HwAddress", "Bitrate", "ActiveAccessPoint"]:
407 print " %s: %s" % (P
, self
.devpi
.Get(NMI
, P
))
409 print " Access Points"
410 for ap
in self
.APs():
413 """An AP found around us"""
415 def __init__(self
, opath
):
417 self
.apo
= bus
.get_object(NMC
, self
.opath
)
418 self
.appi
= dbus
.Interface(self
.apo
, PI
)
420 self
.devi
= dbus
.Interface(self
.apo
, NMI
+ ".Devices")
422 NM_802_11_AP_FLAGS
= {1: "PRIVACY",}
425 1: "PAIR_WEP40", 2: "PAIR_WEP104", 4: "PAIR_TKIP", 8: "PAIR_CCMP",
426 16: "GROUP_WEP40", 32: "GROUP_WEP104", 64: "GROUP_TKIP",
427 128: "GROUP_CCMP", 256: "KEY_MGMT_PSK", 512: "KEY_MGMT_802_1X",}
429 def ListNets(self
, marker
= " "):
431 mbr
= self
.Mbr() / 1024 # 07 1000, 06 1024?
432 priv_s
= self
.PrivS()
433 print "%s%3d: %s (%dMb%s)" % (marker
, self
.Strength(), self
.Ssid(), mbr
, priv_s
)
436 def Mbr(self
, props
=None):
438 props
= self
.devi
.getProperties()
443 props
= self
.devi
.getProperties()
444 caps_s
= bitmask_str(cDeviceWifi_06
.NM_802_11_CAP
, props
[7]) + ","
446 if caps_s
.find("PROTO_WEP,") != -1:
448 if caps_s
.find("PROTO_WPA,") != -1:
450 if caps_s
.find("PROTO_WPA2,") != -1:
452 if caps_s
.find("KEY_MGMT_802_1X,") != -1:
453 priv_s
+= " Enterprise"
456 def Strength(self
, props
=None):
458 props
= self
.devi
.getProperties()
461 def Ssid(self
, props
=None):
463 props
= self
.devi
.getProperties()
468 props
= self
.devi
.getProperties() # ossid iiib
469 print " Self:", props
[0]
470 print " Ssid:", self
.Ssid(props
)
471 print " HwAddress:", props
[2]
472 print " Strength:", self
.Strength(props
)
473 print " Frequency:", props
[4]
474 print " MaxBitrate:", self
.Mbr(props
)
475 print " AP Mode:", cDevice
.IW_MODE
[props
[6]]
476 print " Capabilities:", bitmask_str(cDeviceWifi_06
.NM_802_11_CAP
, props
[7])
477 print " Broadcast:", props
[8]
481 return self
.appi
.Get(NMI
, "MaxBitrate")
484 priv
= self
.appi
.Get(NMI
, "Flags") != 0
485 wpa
= self
.appi
.Get(NMI
, "WpaFlags") != 0
486 wpa2
= self
.appi
.Get(NMI
, "RsnFlags") != 0
489 if not wpa
and not wpa2
:
490 priv_s
= priv_s
+ " WEP"
492 priv_s
= priv_s
+ " WPA"
494 priv_s
= priv_s
+ " WPA2"
498 return int(self
.appi
.Get(NMI
, "Strength"))
500 def ssid_str(noself
, array
):
507 return self
.ssid_str(self
.appi
.Get(NMI
, "Ssid"))
510 print " AP:", self
.opath
511 print " Ssid:", self
.Ssid()
512 for P
in ["Frequency", "HwAddress", "MaxBitrate",]:
513 print " %s: %s" % (P
, self
.appi
.Get(NMI
, P
))
514 print " Strength:", self
.Strength()
515 print " AP Mode:", cDevice
.IW_MODE
[self
.appi
.Get(NMI
, "Mode")]
516 print " AP Flags:", bitmask_str(self
.NM_802_11_AP_FLAGS
,
517 self
.appi
.Get(NMI
, "Flags"))
518 print " AP WPA Flags:", bitmask_str(self
.NM_802_11_AP_SEC
,
519 self
.appi
.Get(NMI
, "WpaFlags"))
520 print " AP RSN Flags:", bitmask_str(self
.NM_802_11_AP_SEC
,
521 self
.appi
.Get(NMI
, "RsnFlags"))
523 # this is the client side of the applet; see also UserSettings
525 def __init__(self
, svc
, opath
):
528 self
.so
= bus
.get_object(self
.svc
, self
.opath
)
529 self
.si
= dbus
.Interface(self
.so
, 'org.freedesktop.NetworkManagerSettings')
532 return self
.svc
== SSC
;
535 for conn
in self
.Connections():
540 def DumpSystem(self
):
541 sspi
= dbus
.Interface(self
.so
, PI
)
542 print "Unmanaged Devices"
543 umds
= sspi
.Get(NMI
, "UnmanagedDevices")
546 # dump_settings_conn(svc, conn) umd?
549 def myConnection(self
, opath
):
550 return cConnection(self
.svc
, opath
)
552 def Connections(self
):
553 opaths
= self
.si
.ListConnections()
554 return map(self
.myConnection
, opaths
)
557 def __init__(self
, svc
, opath
):
560 self
.co
= bus
.get_object(self
.svc
, self
.opath
)
561 self
.ci
= dbus
.Interface(self
.co
, 'org.freedesktop.NetworkManagerSettings.Connection')
564 print "Conn:", self
.opath
565 print " Id:", self
.ci
.GetID()
566 settings
= self
.Settings()
569 si
= dbus
.Interface(self
.co
, 'org.freedesktop.NetworkManagerSettings.Connection.Secrets')
570 security
= settings
.Security()
572 print " SECRETS:", security
574 secrets
= cSettings(si
.GetSecrets(security
,[],False))
578 return cSettings(self
.ci
.GetSettings())
582 def __init__(self
, conmap
):
586 return self
.conmap
["connection"]["type"]
589 return self
.conmap
["connection"]["id"]
593 return self
.conmap
[self
.Type()]["security"]
597 def isNet(self
, net_name
):
598 # FIXME also ssid ...
599 return self
.GetID() == net_name
601 # FIXME check spec/NM what to censor
602 secrets
= dict.fromkeys(["wep-key0", "psk"])
605 "For GetSettings: censor secrets."
608 for n1
, v1
in self
.conmap
.iteritems():
610 for n2
, v2
in v1
.iteritems():
612 if self
.secrets
.has_key(n2
):
618 "For GetSecrets: only secrets."
627 for n1
, v1
in self
.conmap
.iteritems():
629 for n2
, v2
in v1
.iteritems():
630 print " %s: %s" % (n2
, v2
)
632 # just an example, unused now
633 hardwired_conmaps
= [
637 "type": "802-11-wireless",
640 "ssid": dbus
.ByteArray("onenet"),
641 "mode": "infrastructure",
642 "security": "802-11-wireless-security",
646 "802-11-wireless-security": {
647 "key-mgmt": "wpa-psk",
649 "psk": "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", # CENSORED
655 'type': '802-11-wireless',
658 'ssid': dbus
.ByteArray('frogs'),
659 'mode': 'infrastructure',
660 'security': '802-11-wireless-security',
662 '802-11-wireless-security': {
665 'wep-key0': 'aaaaaaaaaaaaaaaaaaaaaaaaaa', # CENSORED
670 class UserSettings_06
:
671 @dbus.service
.method(dbus_interface
="org.freedesktop.NetworkManagerInfo",
672 in_signature
="i", out_signature
='as')
673 def getNetworks(self
, i
):
674 return ["frogs"] # FIXME
676 @dbus.service
.method(dbus_interface
="org.freedesktop.NetworkManagerInfo",
677 in_signature
="", out_signature
='ao') # out??
678 def getVpnConnections(self
):
681 @dbus.service
.method(dbus_interface
="org.freedesktop.NetworkManagerInfo",
682 in_signature
="si", out_signature
='sibasisi')
683 # or additional i ???
684 def getNetworkProperties(self
, net
, i
):
685 # essid, timestamp, ?, bssids, we_cipher, ?, ...
686 # we_cipher=16: i wep_auth_algorithm
687 # we_cipher=0: i wpa_psk_key_mgt, i wpa_psk_wpa_version
688 return ("frogs", 1213713468, 0, ['00:13:10:06:E3:77'], 16, "", 1)
691 @dbus.service
.method(dbus_interface
="org.freedesktop.NetworkManagerInfo",
692 in_signature
="oosib", out_signature
="isi")
693 def getKeyForNetwork(self
, dev
, net
, ssid
, i
, b
):
694 return (16, "66666666666666666666666666",1) # FIXME
696 @dbus.service
.method(dbus_interface
="org.freedesktop.NetworkManagerInfo",
697 in_signature
="sbsisi", out_signature
='')
698 def updateNetworkInfo(self
, ssid
, b
, ap
, i1
, secret
, i2
):
703 # server analog of cApplet
704 class UserSettings(dbus
.service
.Object
):
706 def __init__(self
, opath
, conmaps
):
707 dbus
.service
.Object
.__init
__(self
, bus
, opath
)
708 #print "CONMAPS:", conmaps
709 self
.conns
= map(self
.newCon
, conmaps
)
712 def newCon(self
, conmap
):
713 cpath
= "/MyConnection/%d" % self
.counter
714 self
.counter
= self
.counter
+ 1
715 c
= Connection(cpath
, conmap
)
716 self
.NewConnection(cpath
) # announce it
719 @dbus.service
.method(dbus_interface
='org.freedesktop.NetworkManagerSettings',
720 in_signature
='', out_signature
='ao')
721 def ListConnections(self
):
722 return [c
.__dbus
_object
_path
__ for c
in self
.conns
]
724 #this is for EMITTING a signal, not receiving it
725 @dbus.service
.signal(dbus_interface
='org.freedesktop.NetworkManagerSettings',
727 def NewConnection(self
, opath
):
729 #print "signalling newconn:", opath
731 def GetByNet(self
, net_name
):
732 "Returns connection, or None"
734 if c
.isNet(net_name
):
739 # server analog of cConnection
740 class Connection(dbus
.service
.Object
):
741 def __init__(self
, opath
, conmap
):
742 dbus
.service
.Object
.__init
__(self
, bus
, opath
)
743 self
.settings
= cSettings(conmap
)
745 @dbus.service
.method(dbus_interface
='org.freedesktop.NetworkManagerSettings.Connection',
746 in_signature
='', out_signature
='a{sa{sv}}')
747 def GetSettings(self
):
748 #print "Getting settings:", self. __dbus_object_path__
749 # return self.settings.ConMap()
750 # grr, censoring secrets makes NM complain!?
751 return self
.settings
.conmap
753 @dbus.service
.method(dbus_interface
='org.freedesktop.NetworkManagerSettings.Connection.Secrets',
754 in_signature
='sasb', out_signature
='a{sa{sv}}')
755 def GetSecrets(self
, tag
, hints
, ask
):
757 print "Getting secrets:", self
.__dbus
_object
_path
__
758 return self
.settings
.SecMap()
760 @dbus.service
.method(dbus_interface
='org.freedesktop.NetworkManagerSettings.Connection',
761 in_signature
='', out_signature
='s')
763 return self
.settings
.GetID()
765 def isNet(self
, net_name
):
766 return self
.settings
.isNet(net_name
)
768 class ConfigParserKNM
:
769 "Parse ~/.kde/share/config/knetworkmanagerrc"
772 p
= ConfigParser
.RawConfigParser()
773 ok
= p
.read(os
.getenv("HOME") + "/.kde/share/config/knetworkmanagerrc")
776 for s
in p
.sections():
779 if path
[0] in ["ConnectionSetting", "ConnectionSecrets"]:
781 self
.conmaps_d
.setdefault(cid
, {})
785 for (n
, v
) in p
.items(s
):
786 # WTF, Value_ is transfrmed to value_
787 if n
[:6] == "value_":
789 v
= self
.ParseValue(v
)
791 if len(values
) != 0: # empty 802-1x confuses NM!?
792 self
.conmaps_d
[cid
].setdefault(part
, {})
793 self
.conmaps_d
[cid
][part
].update(**values
)
794 #print "PARSED", cid, part, values
797 return self
.conmaps_d
.values()
799 def ParseValue(self
, v
):
800 v
= eval('"%s"' % v
) # unescape backslashes
801 dom
= xml
.dom
.minidom
.parseString(v
)
802 return self
.ParseNode(dom
.documentElement
)
804 def ParseNode(self
, n
):
812 return dbus
.Byte(int(v
))
815 elif t
== "int32" or t
== "uint32":
821 if c
.localName
!= None: # whitespace
822 v
.append(self
.ParseNode(c
))
826 def NodeText(self
, n
):
827 if n
.hasChildNodes():
828 return n
.firstChild
.wholeText
832 def abbr_signal_handler(*args
, **kwargs
):
833 ifc
= kwargs
["interface"]
834 sig
= kwargs
["member"]
835 opath
= kwargs
["path"]
836 line
= "SIG %s: %s.%s%s" % (abbrev(opath
,"/"), abbrev(ifc
,"."), sig
, args
)
842 bus
.add_signal_receiver(self
.abbr_signal_handler
,
844 interface_keyword
="interface",
845 member_keyword
="member")
847 def abbr_signal_handler(self
, *args
, **kwargs
):
848 ifc
= kwargs
["interface"]
849 sig
= kwargs
["member"]
850 opath
= kwargs
["path"]
851 line
= "SIG %s: %s.%s%s" % (self
.abbrev(opath
,"/"),
852 self
.abbrev(ifc
,"."),
856 def abbrev(self
, s
, sep
):
858 words
= map (self
.a1
, words
)
859 result
= sep
.join(words
)
860 if not self
.amap
.has_key(s
):
861 print "ABBR %s is %s" % (result
, s
)
862 self
.amap
[s
] = result
864 if self
.amap
[s
] != result
:
865 print "ABBR COLLISION %s was %s now %s" % (s
, self
.amap
[s
], result
)
876 op
= OptionParser(version
="%prog " + VERSION
)
877 op
.add_option("-d", "--dev",
878 action
="store_true", default
=False,
880 op
.add_option("-c", "--actcon",
881 action
="store_true", default
=False,
882 help="list active connections")
883 op
.add_option("-u", "--usrcon",
884 action
="store_true", default
=False,
885 help="list user connection settings (can CRASH nm-applet)")
886 op
.add_option("-s", "--syscon",
887 action
="store_true", default
=False,
888 help="list system connection settings")
889 op
.add_option("-a", "--ap",
890 action
="store_true", default
=False,
891 help="list found access points")
892 op
.add_option("-n", "--nets",
893 action
="store_true", default
=False,
894 help="list found wireless networks")
895 # TODO http://docs.python.org/lib/optparse-adding-new-types.html
896 op
.add_option("-w", "--wifi",
897 choices
=["0","1","off","on","no","yes","false","true"],
899 help="enable or disable wireless")
900 op
.add_option("-o", "--online",
901 choices
=["0","1","off","on","no","yes","false","true"],
903 help="enable or disable network at all")
905 op
.add_option("-C", "--connect",
906 help="connect to a wireless network NET (using knetworkmanagerrc)",
908 op
.add_option("-m", "--monitor",
909 action
="store_true", default
=False,
910 help="loop to show dbus signals")
913 (options
, args
) = op
.parse_args()
921 nmp
= '/org/freedesktop/NetworkManager'
923 if options
.dev
or options
.actcon
:
926 true_choices
= ["1", "on", "yes", "true"]
927 if options
.wifi
!= None:
928 nm
.SetWifiEnabled(options
.wifi
in true_choices
)
929 if options
.online
!= None:
930 nm
.SetOnline(options
.online
in true_choices
)
936 print "SYSTEM Connections"
937 ss
= cApplet(SSC
, '/org/freedesktop/NetworkManagerSettings')
941 print "USER Connections"
943 us
= cApplet(USC
, '/org/freedesktop/NetworkManagerSettings')
945 except dbus
.exceptions
.DBusException
, e
:
947 if e
.get_dbus_name() == "org.freedesktop.DBus.Error.ServiceUnknown":
948 print "Applet is not running"
950 nmo
= bus
.get_object(NMC
, nmp
)
951 nmi
= dbus
.Interface(nmo
, NMI
)
953 # TODO UserSettings_06
954 if options
.connect
!= None:
955 brn
= bus
.request_name(USC
, _dbus_bindings
.NAME_FLAG_DO_NOT_QUEUE
)
956 if brn
== _dbus_bindings
.REQUEST_NAME_REPLY_EXISTS
:
957 print "Could not provide settings service, another applet is running"
959 cfg
= ConfigParserKNM()
960 us
= UserSettings("/org/freedesktop/NetworkManagerSettings",
963 def Connect(wanted_net
): # any. or take arg. net is config name or ssid name
964 # ... in general, look for string in all config data. ssid for wifi, whatever for dialup
965 # TODO also respect autoconnect
967 # ActivateConn wants setting device ap; can find device from ap? ap is "specific" for wifi devices
968 #print "Connection wanted to", wanted_net
969 found_con
= found_ap
= found_dev
= None
970 for dev
in nm
.Devices():
972 if wanted_net
== ap
.Ssid():
975 break # FIXME both loops
976 found_con
= us
.GetByNet(wanted_net
)
978 print "No AP found with SSID", wanted_net
980 elif found_con
== None:
981 print "No settings for net", wanted_net
984 nm
.ActivateConnection(found_con
, found_dev
, found_ap
) # TODO async
985 # TODO run loop, exit it when we have serviced the required calls
988 if options
.connect
!= None:
989 if Connect(options
.connect
):
996 loop
= gobject
.MainLoop()