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
11 # find other modules in our prefix, if specified
12 if len(sys
.argv
) > 2 and sys
.argv
[1] == "--prefix":
14 sys
.argv
[1:] = sys
.argv
[3:]
15 sys
.path
.append(prefix
+ "/share/cnetworkmanager");
25 from binascii
import hexlify
26 import ConfigParser
# knm config
27 from optparse
import OptionParser
33 print "Install python-1-dbus.rpm or or python-dbus.rpm or python-dbus.deb"
35 import xml
.dom
.minidom
39 # todo - only if loop wanted
40 print "Install python-gobject2.rpm or pygobject2.rpm or python-gobject.deb"
42 # python-gnome.rpm has gconf for nm-applet...
46 from dbus
.mainloop
.glib
import DBusGMainLoop
47 DBusGMainLoop(set_as_default
=True)
51 bus
= dbus
.SystemBus()
53 # FOOC = connection (service) string
54 # FOOI = interface string
57 # foopi = property interface
58 NMC
= 'org.freedesktop.NetworkManager'
60 PI
= 'org.freedesktop.DBus.Properties'
61 SSC
= "org.freedesktop.NetworkManagerSystemSettings"
62 USC
= "org.freedesktop.NetworkManagerUserSettings"
63 NMIC
= "org.freedesktop.NetworkManagerInfo"
66 ii
= dbus
.Interface(obj
, 'org.freedesktop.DBus.Introspectable')
70 # TODO: pull them from introspection.xml
71 NM_STATE
= ["UNKNOWN", "ASLEEP", "CONNECTING", "CONNECTED", "DISCONNECTED",]
73 def __init__(self
, opath
):
75 self
.nmo
= bus
.get_object(NMC
, self
.opath
)
76 self
.nmi
= dbus
.Interface(self
.nmo
, NMI
)
77 self
.nmpi
= dbus
.Interface(self
.nmo
, PI
)
83 "Dumps its own info (not owned objects)."
89 for device
in self
.Devices():
93 print "Active Connections"
94 aconns
= self
.ActiveConnections()
99 print "Wifi Networks:"
100 for dev
in self
.Devices():
103 def err_handler(self
, *args
):
106 def silent_handler(self
, *args
):
110 def quitter_handler(self
, *args
):
111 # exit the loop that runs only because of us
115 def WatchState(self
):
116 bus
.add_signal_receiver(self
.state_changed_handler
,
117 dbus_interface
="org.freedesktop.NetworkManager",
118 signal_name
="StateChanged")
120 def state_changed_handler(self
, *args
):
122 ss
= self
.NM_STATE
[s
]
123 print time
.strftime("(%X)"),
128 "Detects NM version and chooses appropriate class"
130 nmo
= bus
.get_object(NMC
, opath
)
131 nmi
= dbus
.Interface(nmo
, NMI
)
133 dummy
= nmi
.getDevices()
135 except dbus
.exceptions
.DBusException
:
142 def SetWifiEnabled(self
, v
):
143 # TODO: async call, catch the state signal and exit
144 # weird: synchronous call works, but times out
145 # asynchronous call does not work
146 self
.nmi
.setWirelessEnabled(v
,
147 reply_handler
=self
.quitter_handler
,
148 error_handler
=self
.quitter_handler
)
152 def SetOnline(self
, v
):
155 reply_handler
=self
.quitter_handler
,
156 error_handler
=self
.quitter_handler
)
159 reply_handler
=self
.quitter_handler
,
160 error_handler
=self
.quitter_handler
)
165 print "State:", self
.NM_STATE
[self
.nmi
.state()]
166 we
= self
.nmi
.getWirelessEnabled()
167 if isinstance(we
, tuple):
168 print "Wifi enabled:", bool(we
[0])
169 print "Wifi HW enabled:", bool(we
[1])
171 print "Wifi enabled:", bool(we
)
174 dup
= self
.nmi
.getDialup()
176 except dbus
.exceptions
.DBusException
, e
:
177 #if e.get_dbus_name() == "org.freedesktop.NetworkManager.NoDialup":
183 opaths
= self
.nmi
.getDevices()
184 return map(cDevice_06
, opaths
)
186 def ActiveConnections(self
):
187 return [] # at most one active connection, FIXME find it
189 def ActivateConnection(self
, conn
, device
, ap
):
190 # passing *_handler makes the call asynchronous
191 self
.nmi
.setActiveDevice(device
.opath
, ssid_str(conn
.Ssid()),
192 reply_handler
=self
.silent_handler
,
193 error_handler
=self
.err_handler
,
200 def SetWifiEnabled(self
, v
):
201 self
.nmpi
.Set(NMI
, "WirelessEnabled", v
)
203 def SetOnline(self
, v
):
204 self
.nmi
.Sleep(not v
)
207 print "State:", self
.NM_STATE
[self
.nmpi
.Get(NMI
, "State")]
208 print "Wifi enabled:", self
.nmpi
.Get(NMI
, "WirelessEnabled")
209 print "Wifi HW enabled:", self
.nmpi
.Get(NMI
, "WirelessHardwareEnabled")
212 opaths
= self
.nmi
.GetDevices()
213 return map(cDevice_07
, opaths
)
215 def ActiveConnections(self
):
216 aconns
= self
.nmpi
.Get(NMI
, "ActiveConnections")
217 return map(cActiveConnection
, aconns
)
219 def ActivateConnection(self
, conn
, device
, ap
):
220 # passing *_handler makes the call asynchronous
221 self
.nmi
.ActivateConnection(USC
,
222 conn
.__dbus
_object
_path
__,
225 reply_handler
=self
.silent_handler
,
226 error_handler
=self
.err_handler
,
230 class cActiveConnection
:
231 def __init__(self
, opath
):
236 co
= bus
.get_object(NMC
, self
.opath
)
237 copi
= dbus
.Interface(co
, PI
)
238 for P
in ["ServiceName", "Connection", "SpecificObject",]:
239 print " %s: %s" % (P
, copi
.Get(NMI
, P
))
240 devs
= copi
.Get(NMI
, "Devices")
245 def bitmask_str(map, value
):
247 for mask
in sorted(map.keys()):
248 if value
& mask
: ret
.append(map[mask
])
253 def __init__(self
, opath
):
255 self
.devo
= bus
.get_object(NMC
, self
.opath
)
256 self
.devi
= dbus
.Interface(self
.devo
, NMI
+ ".Device")
257 self
.devpi
= dbus
.Interface(self
.devo
, PI
)
261 DEVICE_TYPE
= ["UNKNOWN", "802_3_ETHERNET", "802_11_WIRELESS",
262 "GSM", "CDMA",] #OLPC: 3 is MESH
264 def DeviceType(self
):
265 return self
.DEVICE_TYPE
[self
.DeviceType0()]
267 def ip_str(self
, i32
):
269 ret
.append("%d" % (i32
% 256))
271 ret
.append("%d" % (i32
% 256))
273 ret
.append("%d" % (i32
% 256))
275 ret
.append("%d" % (i32
% 256))
279 def DumpIp4Config(self
, opath
):
280 print " Ip4Config:", opath
281 o
= bus
.get_object(NMC
, opath
)
282 pi
= dbus
.Interface(o
, PI
)
284 for P
in ["Address", "Netmask", "Broadcast", "Gateway",]: # beta2?
285 print " %s: %s" % (P
, self
.ip_str(pi
.Get(NMI
, P
)))
288 addrs
= pi
.Get(NMI
, "Addresses")
290 print " %s/%s via %s" % tuple(map(self
.ip_str
, addr
))
291 nss
= pi
.Get(NMI
, "Nameservers")
292 print " Nameservers:", " ".join(map(self
.ip_str
, nss
))
293 doms
= pi
.Get(NMI
, "Domains")
294 print " Domains:", " ".join(doms
)
296 NM_DEVICE_CAP
= {1: "NM_SUPPORTED", 2: "CARRIER_DETECT", 4: "SCANNING", }
300 print "Device:", self
.opath
303 IW_MODE
= ["AUTO", "ADHOC", "INFRA", "MASTER",
304 "REPEAT", "SECOND", "MONITOR",]
310 for ap
in self
.APs():
317 class cDevice_06(cDevice
):
318 def DeviceType0(self
):
320 self
.dt
= self
.devi
.getProperties()[2]
322 self
.__class
__ = cDeviceEth_06
324 self
.__class
__ = cDeviceWifi_06
328 "UNKNOWN", "DEVICE_PREPARE", "DEVICE_CONFIG", "NEED_USER_KEY",
329 "IP_CONFIG_START", "IP_CONFIG_GET", "IP_CONFIG_COMMIT",
330 "ACTIVATED", "FAILED", "CANCELLED", ]
334 print " Driver:", self
.devi
.getDriver()
335 props
= self
.devi
.getProperties() # osusb ussss sssii biuus as
336 print " Self:", props
[0] # o
337 print " Interface:", props
[1] # s
338 print " Type:", self
.DEVICE_TYPE
[props
[2]] # u
339 print " UDI:", props
[3] # s
340 print " Active:", bool(props
[4]) # b
341 print " Activation Stage:", self
.NM_ACT_STAGE
[props
[5]] # u
342 print " IP:", props
[6] # s
343 print " Mask:", props
[7] # s
344 print " Bcast:", props
[8] # s
345 print " HwAddress:", props
[9] # s
346 print " GW:", props
[10] # s
347 print " NS1:", props
[11] # s
348 print " NS2:", props
[12] # s
352 print " (unknown device type, not dumping more)"
354 class cDeviceEth_06(cDevice_06
, cDeviceEth
):
356 props
= self
.devi
.getProperties() # osusb ussss sssii biuus as
357 print " Link Active:", bool(props
[15]) # b
358 print " Speed:", props
[16] # i
359 print " Generic Capabilities:", bitmask_str(self
.NM_DEVICE_CAP
, props
[17]) # u
361 class cDeviceWifi_06(cDevice_06
):
363 0x00000001: "PROTO_NONE",
364 0x00000002: "PROTO_WEP",
365 0x00000004: "PROTO_WPA",
366 0x00000008: "PROTO_WPA2",
367 0x00000010: "RESERVED1",
368 0x00000020: "RESERVED2",
369 0x00000040: "KEY_MGMT_PSK",
370 0x00000080: "KEY_MGMT_802_1X",
371 0x00000100: "RESERVED3",
372 0x00000200: "RESERVED4",
373 0x00000400: "RESERVED5",
374 0x00000800: "RESERVED6",
375 0x00001000: "CIPHER_WEP40",
376 0x00002000: "CIPHER_WEP104",
377 0x00004000: "CIPHER_TKIP",
378 0x00008000: "CIPHER_CCMP",
382 self
.wdevi
= dbus
.Interface(self
.devo
, NMI
+ ".Device.Wireless")
383 aps
= self
.devi
.getProperties()[20]
384 return map(cAP_06
, aps
)
387 props
= self
.devi
.getProperties() # osusb ussss sssii biuus as
388 print " Mode:", self
.IW_MODE
[props
[13]] # i
389 print " Strength:", props
[14] # i
390 print " Link Active:", bool(props
[15]) # b
391 print " Speed:", props
[16] # i
392 print " Generic Capabilities:", bitmask_str(self
.NM_DEVICE_CAP
, props
[17]) # u
393 print " Capabilities:", bitmask_str(self
.NM_802_11_CAP
, props
[18]) # u
394 print " Current net:", props
[19] # s
395 nets
= props
[20] # as
396 print " Seen nets:", " ".join(nets
)
398 print " Access Points"
399 for ap
in self
.APs():
402 class cDevice_07(cDevice
):
403 def DeviceType0(self
):
405 self
.dt
= self
.devpi
.Get(NMI
, "DeviceType")
407 self
.__class
__ = cDeviceEth_07
409 self
.__class
__ = cDeviceWifi_07
413 "UNKNOWN", "UNMANAGED", "UNAVAILABLE", "DISCONNECTED", "PREPARE",
414 "CONFIG", "NEED_AUTH", "IP_CONFIG", "ACTIVATED", "FAILED",]
419 # "Ip4Config", only for NM_DEVICE_STATE_ACTIVATED
420 for P
in ["Udi", "Interface", "Driver",]:
421 print " %s: %s" % (P
, self
.devpi
.Get(NMI
, P
))
422 addr
= self
.devpi
.Get(NMI
, "Ip4Address")
423 print " Ip4Address:", self
.ip_str(addr
)
424 caps
= self
.devpi
.Get(NMI
, "Capabilities")
425 print " Capabilities:", bitmask_str(self
.NM_DEVICE_CAP
, caps
)
426 state
= self
.NM_DEVICE_STATE
[self
.devpi
.Get(NMI
, "State")]
427 print " Dev State:", state
428 if state
== "ACTIVATED":
429 self
.DumpIp4Config(self
.devpi
.Get(NMI
, "Ip4Config"))
431 dt
= self
.DeviceType()
432 print " Dev Type:", dt
435 class cDeviceEth_07(cDevice_07
, cDeviceEth
):
437 for P
in ["HwAddress", "Speed", "Carrier"]:
438 print " %s: %s" % (P
, self
.devpi
.Get(NMI
, P
))
440 class cDeviceWifi_07(cDevice_07
):
441 NM_802_11_DEVICE_CAP
= {1:"CIPHER_WEP40", 2:"CIPHER_WEP104",
442 4:"CIPHER_TKIP", 8:"CIPHER_CCMP",
446 self
.wdevi
= dbus
.Interface(self
.devo
, NMI
+ ".Device.Wireless")
447 aps
= self
.wdevi
.GetAccessPoints()
448 return map(cAP_07
, aps
)
451 print " Dev Mode:", self
.IW_MODE
[self
.devpi
.Get(NMI
, "Mode")]
452 wcaps
= self
.devpi
.Get(NMI
, "WirelessCapabilities")
453 print " Wifi Capabilities:", bitmask_str(self
.NM_802_11_DEVICE_CAP
, wcaps
)
454 for P
in ["HwAddress", "Bitrate", "ActiveAccessPoint"]:
455 print " %s: %s" % (P
, self
.devpi
.Get(NMI
, P
))
457 print " Access Points"
458 for ap
in self
.APs():
461 """An AP found around us"""
463 def __init__(self
, opath
):
465 self
.apo
= bus
.get_object(NMC
, self
.opath
)
466 self
.appi
= dbus
.Interface(self
.apo
, PI
)
468 self
.devi
= dbus
.Interface(self
.apo
, NMI
+ ".Devices")
470 NM_802_11_AP_FLAGS
= {1: "PRIVACY",}
473 1: "PAIR_WEP40", 2: "PAIR_WEP104", 4: "PAIR_TKIP", 8: "PAIR_CCMP",
474 16: "GROUP_WEP40", 32: "GROUP_WEP104", 64: "GROUP_TKIP",
475 128: "GROUP_CCMP", 256: "KEY_MGMT_PSK", 512: "KEY_MGMT_802_1X",}
477 def ListNets(self
, marker
= " "):
479 mbr
= self
.Mbr() / 1024 # 07 1000, 06 1024?
480 priv_s
= self
.PrivS()
481 print "%s%3d: %s (%dMb%s)" % (marker
, self
.Strength(), self
.Ssid(), mbr
, priv_s
)
484 def Mbr(self
, props
=None):
486 props
= self
.devi
.getProperties()
491 props
= self
.devi
.getProperties()
492 caps_s
= bitmask_str(cDeviceWifi_06
.NM_802_11_CAP
, props
[7]) + ","
494 if caps_s
.find("PROTO_WEP,") != -1:
496 if caps_s
.find("PROTO_WPA,") != -1:
498 if caps_s
.find("PROTO_WPA2,") != -1:
500 if caps_s
.find("KEY_MGMT_802_1X,") != -1:
501 priv_s
+= " Enterprise"
504 def Strength(self
, props
=None):
506 props
= self
.devi
.getProperties()
509 def Ssid(self
, props
=None):
511 props
= self
.devi
.getProperties()
516 props
= self
.devi
.getProperties() # ossid iiib
517 print " Self:", props
[0]
518 print " Ssid:", self
.Ssid(props
)
519 print " HwAddress:", props
[2]
520 print " Strength:", self
.Strength(props
)
521 print " Frequency:", props
[4]
522 print " MaxBitrate:", self
.Mbr(props
)
523 print " AP Mode:", cDevice
.IW_MODE
[props
[6]]
524 print " Capabilities:", bitmask_str(cDeviceWifi_06
.NM_802_11_CAP
, props
[7])
525 print " Broadcast:", props
[8]
533 def opath_validchar(c
):
534 # _ is also escaped even though it is valid
536 string
.ascii_letters
.find(c
) != -1 or \
537 string
.digits
.find(c
) != -1
542 # TODO find a more elegant way
543 if not opath_validchar(c
):
549 def opath_unescape(s
):
551 unhex
= lambda xx
: chr(eval("0x"+xx
))
553 return re
.sub("_.._", lambda p
: unhex(p
.group()[1:3]), s
)
557 return self
.appi
.Get(NMI
, "MaxBitrate")
560 priv
= self
.appi
.Get(NMI
, "Flags") != 0
561 wpa
= self
.appi
.Get(NMI
, "WpaFlags") != 0
562 wpa2
= self
.appi
.Get(NMI
, "RsnFlags") != 0
565 if not wpa
and not wpa2
:
566 priv_s
= priv_s
+ " WEP"
568 priv_s
= priv_s
+ " WPA"
570 priv_s
= priv_s
+ " WPA2"
574 return int(self
.appi
.Get(NMI
, "Strength"))
577 return ssid_str(self
.appi
.Get(NMI
, "Ssid"))
580 print " AP:", self
.opath
581 print " Ssid:", self
.Ssid()
582 for P
in ["Frequency", "HwAddress", "MaxBitrate",]:
583 print " %s: %s" % (P
, self
.appi
.Get(NMI
, P
))
584 print " Strength:", self
.Strength()
585 print " AP Mode:", cDevice
.IW_MODE
[self
.appi
.Get(NMI
, "Mode")]
586 print " AP Flags:", bitmask_str(self
.NM_802_11_AP_FLAGS
,
587 self
.appi
.Get(NMI
, "Flags"))
588 print " AP WPA Flags:", bitmask_str(self
.NM_802_11_AP_SEC
,
589 self
.appi
.Get(NMI
, "WpaFlags"))
590 print " AP RSN Flags:", bitmask_str(self
.NM_802_11_AP_SEC
,
591 self
.appi
.Get(NMI
, "RsnFlags"))
593 # this is the client side of the applet; see also UserSettings
595 def __init__(self
, svc
, opath
):
598 self
.so
= bus
.get_object(self
.svc
, self
.opath
)
599 self
.si
= dbus
.Interface(self
.so
, 'org.freedesktop.NetworkManagerSettings')
602 return self
.svc
== SSC
;
605 for conn
in self
.Connections():
610 def DumpSystem(self
):
611 sspi
= dbus
.Interface(self
.so
, PI
)
612 print "Unmanaged Devices"
613 umds
= sspi
.Get(NMI
, "UnmanagedDevices")
616 # dump_settings_conn(svc, conn) umd?
619 def myConnection(self
, opath
):
620 return cConnection(self
.svc
, opath
)
622 def Connections(self
):
623 opaths
= self
.si
.ListConnections()
624 return map(self
.myConnection
, opaths
)
626 NETWORK_TYPE_ALLOWED
= 1
627 class cApplet_06(cApplet
):
628 def __init__(self
, svc
, opath
):
631 self
.io
= bus
.get_object(self
.svc
, self
.opath
)
632 self
.ii
= dbus
.Interface(self
.io
, 'org.freedesktop.NetworkManagerInfo')
637 def myConnection(self
, opath
):
638 return cConnection_06(self
, opath
)
640 # TODO also VPN conns
641 def Connections(self
):
642 names
= self
.ii
.getNetworks(NETWORK_TYPE_ALLOWED
)
643 return map(self
.myConnection
, names
)
646 def __init__(self
, svc
, opath
):
649 self
.co
= bus
.get_object(self
.svc
, self
.opath
)
650 self
.ci
= dbus
.Interface(self
.co
, 'org.freedesktop.NetworkManagerSettings.Connection')
653 print "Conn:", self
.opath
654 settings
= self
.Settings()
657 si
= dbus
.Interface(self
.co
, 'org.freedesktop.NetworkManagerSettings.Connection.Secrets')
658 security
= settings
.Security()
660 print " SECRETS:", security
663 secrets
= cSettings(si
.GetSecrets(security
,[],False))
665 except dbus
.exceptions
.DBusException
, e
:
666 if e
.get_dbus_name() == "org.freedesktop.DBus.Error.AccessDenied":
667 print " Access denied"
670 print " FIXME figure out 802-1x secrets"
673 return cSettings(self
.ci
.GetSettings())
675 def dump_time(unixtime
):
676 return time
.asctime(time
.localtime(unixtime
))
678 class cConnection_06
:
679 def __init__(self
, applet
, id):
684 print "Conn:", self
.id
686 np
= self
.applet
.ii
.getNetworkProperties(self
.id, NETWORK_TYPE_ALLOWED
)
689 print " time:", dump_time(np
[1])
690 print " trusted:", bool(np
[2])
691 print " bssids:", ", ".join(np
[3])
693 print " we_cipher:", enctype
695 print " secret:", np
[5]
697 print " wep_auth_algorithm:", np
[6]
699 print " wpa_psk_key_mgt:", np
[6]
700 print " wpa_psk_wpa_version:", np
[7]
702 return # nm-applet will not tell kfn anyway
703 devp
= "/org/freedesktop/NetworkManager/Devices/ath0" #FIXME
704 netp
= devp
+ "/Networks/" + opath_escape(self
.id)
707 kfn
= self
.applet
.ii
.getKeyForNetwork(devp
, netp
, ssid
, attempt
, newkey
)
712 NM_AUTH_TYPE_WPA_PSK_AUTO
= 0x00000000
713 NM_AUTH_TYPE_NONE
= 0x00000001
714 NM_AUTH_TYPE_WEP40
= 0x00000002
715 NM_AUTH_TYPE_WPA_PSK_TKIP
= 0x00000004
716 NM_AUTH_TYPE_WPA_PSK_CCMP
= 0x00000008
717 NM_AUTH_TYPE_WEP104
= 0x00000010
718 NM_AUTH_TYPE_WPA_EAP
= 0x00000020
719 NM_AUTH_TYPE_LEAP
= 0x00000040
721 IW_AUTH_ALG_OPEN_SYSTEM
= 0x00000001
722 IW_AUTH_ALG_SHARED_KEY
= 0x00000002
723 IW_AUTH_ALG_LEAP
= 0x00000004
726 def __init__(self
, conmap
):
727 #print "INIT", conmap
731 return self
.conmap
["connection"]["type"]
734 return self
.conmap
["connection"]["id"]
738 return self
.conmap
["802-11-wireless"]["ssid"]
741 # probably 802-3-ethernet
746 return self
.conmap
["connection"]["timestamp"]
754 def SeenBssids(self
):
756 return self
.conmap
["802-11-wireless"]["seen-bssids"]
764 return NM_AUTH_TYPE_WEP104
766 return NM_AUTH_TYPE_WPA_PSK_AUTO
768 return NM_AUTH_TYPE_NONE
769 print "Defaulting cipher type to none"
770 return NM_AUTH_TYPE_NONE
774 return self
.conmap
["802-11-wireless-security"]["psk"]
778 return self
.conmap
["802-11-wireless-security"]["wep-key0"]
784 def WepAuthAlgorithm(self
):
785 print "FIXME Defaulting WEP auth alg to open"
786 return IW_AUTH_ALG_OPEN_SYSTEM
789 print "FIXME Defaulting PSK key mgmt to 2"
792 def PskWpaVersion(self
):
793 print "FIXME Defaulting WPA version to 2"
798 return self
.conmap
[self
.Type()]["security"]
802 def isNet(self
, net_name
):
803 return self
.ID() == net_name
or self
.Ssid() == net_name
805 # FIXME check spec/NM what to censor
806 secrets
= dict.fromkeys(["wep-key0", "psk"])
809 "For GetSettings: censor secrets."
812 for n1
, v1
in self
.conmap
.iteritems():
814 for n2
, v2
in v1
.iteritems():
816 if self
.secrets
.has_key(n2
):
822 "For GetSecrets: only secrets."
831 for n1
, v1
in self
.conmap
.iteritems():
833 for n2
, v2
in v1
.iteritems():
834 print " %s: %s" % (n2
, v2
)
836 def mkconmap_wifi(ssid
):
839 'id': '_cnm_handcrafted_',
840 'uuid': str(uuid
.uuid1()), # new in oS 11.1
841 'type': '802-11-wireless',
844 'ssid': dbus
.ByteArray(ssid
),
845 'mode': 'infrastructure',
849 def elongate(s
, tlen
):
850 "repeat string s to target length tlen"
853 copies_needed
= int(math
.ceil(tlen
/ float(len(s
))))
854 return (s
* copies_needed
)[:tlen
]
856 # http://www.mail-archive.com/networkmanager-list@gnome.org/msg07935.html
857 def wep_passphrase_to_hash(p
):
858 return hashlib
.md5(elongate(p
, 64)).hexdigest()
860 def mkconmap_wep_pass(ssid
, key
):
861 cm
= mkconmap_wifi(ssid
)
862 cm
["802-11-wireless"]["security"] = "802-11-wireless-security"
863 cm
["802-11-wireless-security"] = {}
864 cm
["802-11-wireless-security"]["key-mgmt"] = "none"
865 cm
["802-11-wireless-security"]["wep-tx-keyidx"] = 0
866 cm
["802-11-wireless-security"]["wep-key0"] = wep_passphrase_to_hash(key
)
869 def mkconmap_wep(ssid
, key
):
870 cm
= mkconmap_wifi(ssid
)
871 cm
["802-11-wireless"]["security"] = "802-11-wireless-security"
872 cm
["802-11-wireless-security"] = {}
873 cm
["802-11-wireless-security"]["key-mgmt"] = "none"
874 cm
["802-11-wireless-security"]["wep-tx-keyidx"] = 0
875 cm
["802-11-wireless-security"]["wep-key0"] = key
878 def mkconmap_psk(ssid
, key
):
879 cm
= mkconmap_wifi(ssid
)
880 cm
["802-11-wireless"]["security"] = "802-11-wireless-security"
881 cm
["802-11-wireless-security"] = {}
882 cm
["802-11-wireless-security"]["key-mgmt"] = "wpa-psk"
883 cm
["802-11-wireless-security"]["psk"] = key
884 cm
["802-11-wireless-security"]["group"] = ["tkip", "ccmp"]
885 cm
["802-11-wireless-security"]["pairwise"] = ["tkip", "ccmp"]
889 # server analog of cApplet
890 class UserSettings(dbus
.service
.Object
):
892 def __init__(self
, opath
, conmaps
):
893 dbus
.service
.Object
.__init
__(self
, bus
, opath
)
894 #print "CONMAPS:", conmaps
895 self
.conns
= map(self
.newCon
, conmaps
)
897 def addCon(self
, conmap
):
898 c
= self
.newCon(conmap
)
903 def newCon(self
, conmap
):
904 cpath
= "/MyConnection/%d" % self
.counter
905 self
.counter
= self
.counter
+ 1
906 c
= Connection(cpath
, conmap
)
907 self
.NewConnection(cpath
) # announce it
910 @dbus.service
.method(dbus_interface
='org.freedesktop.NetworkManagerSettings',
911 in_signature
='', out_signature
='ao')
912 def ListConnections(self
):
913 return [c
.__dbus
_object
_path
__ for c
in self
.conns
]
915 #this is for EMITTING a signal, not receiving it
916 @dbus.service
.signal(dbus_interface
='org.freedesktop.NetworkManagerSettings',
918 def NewConnection(self
, opath
):
920 #print "signalling newconn:", opath
922 def GetByNet(self
, net_name
):
923 "Returns connection, or None"
925 if c
.isNet(net_name
):
930 class UserSettings_06(UserSettings
):
932 def __init__(self
, opath
, conmaps
):
933 dbus
.service
.Object
.__init
__(self
, bus
, opath
)
934 #print "CONMAPS:", conmaps
935 self
.conns
= map(self
.newCon
, conmaps
)
938 def newCon(self
, conmap
):
939 cpath
= "/MyConnection/%d" % self
.counter
940 self
.counter
= self
.counter
+ 1
941 c
= Connection_06(cpath
, conmap
)
942 #self.NewConnection(cpath) # announce it
945 @dbus.service
.method(dbus_interface
="org.freedesktop.NetworkManagerInfo",
946 in_signature
="i", out_signature
='as')
947 def getNetworks(self
, i
):
948 # FIXME bytearray to str WHERE?
949 #n = [ssid_str(c.Ssid()) for c in self.conns]
950 n
= [c
.ID() for c
in self
.conns
]
951 print "getNetworks:", n
954 @dbus.service
.method(dbus_interface
="org.freedesktop.NetworkManagerInfo",
955 in_signature
="", out_signature
='ao') # out??
956 def getVPNConnections(self
):
959 @dbus.service
.method(dbus_interface
="org.freedesktop.NetworkManagerInfo",
961 #out_signature='sibasi') #varies
962 def getNetworkProperties(self
, net
, type):
964 # type is 1, NETWORK_TYPE_ALLOWED
965 c
= self
.GetByNet(net
)
967 return c
.getNetworkProperties()
968 print "Oops, could not getNetworkProperties for " + net
971 @dbus.service
.method(dbus_interface
="org.freedesktop.NetworkManagerInfo",
972 in_signature
="oosib")
973 #out_signature="isi") varies
974 def getKeyForNetwork(self
, dev
, net
, ssid
, attempt
, newkey
):
975 print "GKFN", dev
, net
, ssid
, attempt
, bool(newkey
)
977 m
= "Cannot ask for key"
979 raise dbus
.exceptions
.DBusException(m
)
981 snet
= opath_unescape(net
[net
.rfind("/")+1 : ]) # only stuff after /
982 c
= self
.GetByNet(snet
)
984 return c
.getKeyForNetwork()
985 print "Oops, could not getKeyForNetwork " + net
987 @dbus.service
.method(dbus_interface
="org.freedesktop.NetworkManagerInfo",
989 #in_signature="sbs isi", varies
990 def updateNetworkInfo(self
, ssid
, automatic
, bssid
, *security
):
991 print "Connected successfully"
995 print " automatic:", bool(automatic
)
996 print " bssid:", bssid
997 print " security:", security
1000 def GetByNet(self
, net_name
):
1001 "Returns connection, or None"
1002 for c
in self
.conns
:
1003 if c
.isNet(net_name
):
1008 # server analog of cConnection
1009 class Connection(dbus
.service
.Object
):
1010 def __init__(self
, opath
, conmap
):
1011 dbus
.service
.Object
.__init
__(self
, bus
, opath
)
1012 self
.settings
= cSettings(conmap
)
1014 @dbus.service
.method(dbus_interface
='org.freedesktop.NetworkManagerSettings.Connection',
1015 sender_keyword
='sender',
1016 in_signature
='', out_signature
='a{sa{sv}}')
1017 def GetSettings(self
, sender
):
1018 #print "Getting settings:", self. __dbus_object_path__
1019 # return self.settings.ConMap()
1020 # grr, censoring secrets makes NM complain!?
1021 # bnc#479566#c3: Until I figure out how to make it work with
1022 # censored secrets, only pass the settings to the same user.
1023 sender_uid
= bus
.get_unix_user(sender
)
1024 if sender_uid
!= 0 and sender_uid
!= os
.geteuid():
1025 e
= "User %u is not permitted to read the settings" % sender_uid
1027 raise dbus
.exceptions
.DBusException(e
) # could do NM_SETTINGS_ERROR_* instead
1028 return self
.settings
.conmap
1030 @dbus.service
.method(dbus_interface
='org.freedesktop.NetworkManagerSettings.Connection.Secrets',
1031 in_signature
='sasb', out_signature
='a{sa{sv}}')
1032 def GetSecrets(self
, tag
, hints
, ask
):
1033 # FIXME respect args
1034 print "Getting secrets:", self
.__dbus
_object
_path
__
1035 return self
.settings
.SecMap()
1037 @dbus.service
.method(dbus_interface
='org.freedesktop.NetworkManagerSettings.Connection',
1038 in_signature
='', out_signature
='s')
1040 return self
.settings
.ID()
1043 return self
.settings
.Ssid()
1045 def isNet(self
, net_name
):
1046 return self
.settings
.isNet(net_name
)
1048 class Connection_06(Connection
):
1049 def __init__(self
, opath
, conmap
):
1050 dbus
.service
.Object
.__init
__(self
, bus
, opath
)
1052 self
.settings
= cSettings(conmap
)
1054 # dbus.service.method
1055 def getNetworkProperties(self
):
1056 # essid, timestamp, ?, bssids, we_cipher, ?, ...
1057 # we_cipher=16: i wep_auth_algorithm
1058 # we_cipher=0: i wpa_psk_key_mgt, i wpa_psk_wpa_version
1059 ssid
= ssid_str(self
.settings
.Ssid())
1060 time
= self
.settings
.Timestamp() # last sucessfully connected? seen?
1061 trusted
= self
.settings
.Trusted()
1062 bssids
= dbus
.Array(self
.settings
.SeenBssids(), signature
="s")
1063 r
= [ssid
, time
, trusted
, bssids
]
1064 security
= self
.getKeyForNetwork("fake key")
1068 # dbus.service.method
1069 def getKeyForNetwork(self
, fake
="no"):
1071 key
= self
.settings
.Key()
1076 cip
= self
.settings
.WeCipher()
1077 if cip
== NM_AUTH_TYPE_NONE
:
1078 security
= tuple([cip
])
1079 elif cip
== NM_AUTH_TYPE_WEP40
or cip
== NM_AUTH_TYPE_WEP104
:
1080 wep_auth_algorithm
= self
.settings
.WepAuthAlgorithm()
1081 security
= (cip
, key
, wep_auth_algorithm
)
1082 elif cip
== NM_AUTH_TYPE_WPA_PSK_AUTO
or cip
== NM_AUTH_TYPE_TKIP
or \
1083 cip
== NM_AUTH_TYPE_CCMP
:
1084 wpa_psk_key_mgt
= self
.settings
.PskKeyMgt()
1085 wpa_psk_wpa_version
= self
.settings
.PskWpaVersion()
1086 security
= (cip
, key
, wpa_psk_key_mgt
, wpa_psk_wpa_version
)
1087 elif cip
== NM_AUTH_TYPE_WPA_EAP
:
1088 security
= tuple([cip
]) # TODO more...
1089 elif cip
== NM_AUTH_TYPE_LEAP
:
1090 security
= tuple([cip
]) # TODO more...
1094 class ConfigParserKNM
:
1095 "Parse ~/.kde/share/config/knetworkmanagerrc"
1098 p
= ConfigParser
.RawConfigParser()
1099 ok
= p
.read(os
.getenv("HOME") + "/.kde/share/config/knetworkmanagerrc")
1102 for s
in p
.sections():
1105 if path
[0] in ["ConnectionSetting", "ConnectionSecrets"]:
1107 self
.conmaps_d
.setdefault(cid
, {})
1111 for (n
, v
) in p
.items(s
):
1112 # WTF, Value_ is transformed to value_
1113 if n
[:6] == "value_":
1115 v
= self
.ParseValue(v
)
1116 #print "# %s:%s" % (n, v)
1117 # do not overwrite ConnectionSecrets
1118 # with empty ConnectionSettings field
1120 vv
= self
.conmaps_d
[cid
][part
][n
]
1125 if len(values
) != 0: # empty 802-1x confuses NM!?
1126 self
.conmaps_d
[cid
].setdefault(part
, {})
1127 self
.conmaps_d
[cid
][part
].update(**values
)
1128 #print "PARSED", cid, part, values
1131 return self
.conmaps_d
.values()
1133 def ParseValue(self
, v
):
1134 v
= eval('"%s"' % v
) # unescape backslashes
1135 dom
= xml
.dom
.minidom
.parseString(v
)
1136 return self
.ParseNode(dom
.documentElement
)
1138 def ParseNode(self
, n
):
1141 v
= self
.NodeText(n
)
1146 return dbus
.Byte(int(v
))
1149 elif t
== "int32" or t
== "uint32":
1155 if c
.localName
!= None: # whitespace
1156 v
.append(self
.ParseNode(c
))
1160 def NodeText(self
, n
):
1161 if n
.hasChildNodes():
1162 return n
.firstChild
.wholeText
1170 bus
.add_signal_receiver(self
.abbr_h
,
1171 path_keyword
="path",
1172 interface_keyword
="interface",
1173 member_keyword
="member")
1175 def ignore(self
, dbus_interface
, signal_name
):
1176 self
.watch(self
.null_h
, dbus_interface
, signal_name
)
1178 def null_h(self
, *args
, **kwargs
):
1181 def watch(self
, handler
, dbus_interface
, signal_name
):
1182 self
.specific
[dbus_interface
+"."+ signal_name
] = True
1183 bus
.add_signal_receiver(handler
,
1184 dbus_interface
=dbus_interface
,
1185 signal_name
=signal_name
,
1186 path_keyword
="path")
1188 def abbr_h(self
, *args
, **kwargs
):
1189 ifc
= kwargs
["interface"]
1190 sig
= kwargs
["member"]
1191 if self
.specific
.has_key(ifc
+"."+ sig
):
1194 opath
= kwargs
["path"]
1195 line
= "SIG %s: %s.%s%s" % (self
.abbrev(opath
,"/"),
1196 self
.abbrev(ifc
,"."),
1200 def abbrev(self
, s
, sep
):
1201 words
= s
.split(sep
)
1202 words
= map (self
.a1
, words
)
1203 result
= sep
.join(words
)
1204 if self
.amap
.has_key(result
):
1205 if self
.amap
[result
] != s
:
1206 print "ABBR COLLISION %s was %s now %s" % (result
, self
.amap
[result
], s
)
1208 print "ABBR %s is %s" % (result
, s
)
1209 self
.amap
[result
] = s
1216 # first char, delete lowercase and _ from the rest
1217 return s
[0] + s
[1:].translate(string
.maketrans("", ""),
1218 string
.lowercase
+ "_")
1220 class Monitor(MonitorBase
):
1222 MonitorBase
.__init
__(self
)
1226 dbus_interface
="org.freedesktop.NetworkManager.Device.Wireless",
1227 signal_name
="PropertiesChanged")
1230 dbus_interface
="org.freedesktop.NetworkManager.AccessPoint",
1231 signal_name
="PropertiesChanged")
1233 self
.ignore("org.freedesktop.Hal.Device", "PropertyModified")
1234 self
.ignore("fi.epitest.hostap.WPASupplicant.Interface", "ScanResultsAvailable")
1235 self
.ignore("com.redhat.PrinterSpooler", "QueueChanged")
1236 self
.ignore("org.freedesktop.NetworkManager", "StateChange") # deprecated
1237 self
.watch(self
.nm_sc_h
, "org.freedesktop.NetworkManager", "StateChanged")
1238 self
.watch(self
.wpas_isc_h
, "fi.epitest.hostap.WPASupplicant.Interface", "StateChange")
1239 self
.watch(self
.nmd_sc_h
, "org.freedesktop.NetworkManager.Device", "StateChanged")
1240 self
.watch(self
.bus_noc_h
, "org.freedesktop.DBus", "NameOwnerChanged")
1242 def bus_noc_h(self
, *args
, **kwargs
):
1243 (name
, old
, new
) = args
1248 print "\tBUS NOC\t%s %s" % (name
, new
)
1250 def wpas_isc_h(self
, *args
, **kwargs
):
1251 opath
= kwargs
["path"]
1253 print "\tWPAS %s\t(%s, was %s)" % (new
, opath
, old
.lower())
1255 def nmd_sc_h(self
, *args
, **kwargs
):
1256 opath
= kwargs
["path"]
1257 (new
, old
, reason
) = args
1258 news
= cDevice_07
.NM_DEVICE_STATE
[new
]
1259 olds
= cDevice_07
.NM_DEVICE_STATE
[old
]
1262 reasons
= "reason %d" % reason
1263 print "\tDevice State %s\t(%s, was %s%s)" % (news
, opath
, olds
.lower(), reasons
)
1265 def nm_sc_h(self
, *args
, **kwargs
):
1267 ss
= cNM
.NM_STATE
[s
]
1268 print "\tNM State:", ss
1270 def propc_h(self
, *args
, **kwargs
):
1271 opath
= kwargs
["path"]
1273 for k
, v
in props
.iteritems():
1276 line
= "\tPROP\t%s\t%s\t(%s)" % (k
, v
, opath
)
1282 op
= OptionParser(version
="%prog " + VERSION
)
1283 op
.add_option("-d", "--dev",
1284 action
="store_true", default
=False,
1285 help="list devices")
1286 op
.add_option("-c", "--actcon",
1287 action
="store_true", default
=False,
1288 help="list active connections")
1289 op
.add_option("-u", "--usrcon",
1290 action
="store_true", default
=False,
1291 help="list user connection settings (can CRASH nm-applet)")
1292 op
.add_option("-s", "--syscon",
1293 action
="store_true", default
=False,
1294 help="list system connection settings")
1295 op
.add_option("-a", "--ap",
1296 action
="store_true", default
=False,
1297 help="list found access points")
1298 op
.add_option("-n", "--nets",
1299 action
="store_true", default
=False,
1300 help="list found wireless networks")
1301 # TODO http://docs.python.org/lib/optparse-adding-new-types.html
1302 op
.add_option("-w", "--wifi",
1303 choices
=["0","1","off","on","no","yes","false","true"],
1305 help="enable or disable wireless")
1306 op
.add_option("-o", "--online",
1307 choices
=["0","1","off","on","no","yes","false","true"],
1309 help="enable or disable network at all")
1311 op
.add_option("-C", "--connect",
1312 help="connect to a wireless network NET (using knetworkmanagerrc or the key options below)",
1314 op
.add_option("--unprotected",
1315 action
="store_true", default
=False,
1316 help="network does not require a key")
1317 op
.add_option("--wep-hex",
1319 help="use this WEP key of 26 hex digits")
1320 op
.add_option("--wep-pass",
1322 help="use this WEP passphrase")
1323 op
.add_option("--wpa-psk-hex",
1325 help="use this WPA key of 64 hex digits")
1326 op
.add_option("--wpa-pass",
1328 help="use this WPA passphrase")
1329 op
.add_option("-m", "--monitor",
1330 action
="store_true", default
=False,
1331 help="loop to show dbus signals")
1334 (options
, args
) = op
.parse_args()
1342 nmp
= '/org/freedesktop/NetworkManager'
1345 except dbus
.exceptions
.DBusException
, e
:
1347 print "NetworkManager is not running"
1349 if options
.dev
or options
.actcon
:
1352 true_choices
= ["1", "on", "yes", "true"]
1353 if options
.wifi
!= None:
1354 nm
.SetWifiEnabled(options
.wifi
in true_choices
)
1355 if options
.online
!= None:
1356 nm
.SetOnline(options
.online
in true_choices
)
1362 print "SYSTEM Connections"
1363 if nm
.Api() == "06":
1364 print "Cannot do that with NM 0.6"
1366 ss
= cApplet(SSC
, '/org/freedesktop/NetworkManagerSettings')
1370 print "USER Connections"
1372 if nm
.Api() == "06":
1373 us
= cApplet_06(NMIC
, "/org/freedesktop/NetworkManagerInfo")
1375 us
= cApplet(USC
, '/org/freedesktop/NetworkManagerSettings')
1377 except dbus
.exceptions
.DBusException
, e
:
1379 #if e.get_dbus_name() == "org.freedesktop.DBus.Error.ServiceUnknown":
1380 print "Applet is not running"
1382 nmo
= bus
.get_object(NMC
, nmp
)
1383 nmi
= dbus
.Interface(nmo
, NMI
)
1385 def service_pid(name
):
1386 DBS
= 'org.freedesktop.DBus'
1388 dbo
= bus
.get_object(DBS
, '/')
1389 dbi
= dbus
.Interface(dbo
, DBI
)
1390 owner
= dbi
.GetNameOwner(name
)
1391 pid
= dbi
.GetConnectionUnixProcessID(owner
)
1394 # TODO UserSettings_06
1395 if options
.connect
!= None:
1396 if nm
.Api() == "06":
1400 brn
= bus
.request_name(name
, _dbus_bindings
.NAME_FLAG_DO_NOT_QUEUE
)
1401 if brn
== _dbus_bindings
.REQUEST_NAME_REPLY_EXISTS
:
1402 print "Could not provide settings service, another applet is running (pid %s)" % service_pid(name
)
1404 cfg
= ConfigParserKNM()
1405 if nm
.Api() == "06":
1406 us
= UserSettings_06("/org/freedesktop/NetworkManagerInfo",
1409 us
= UserSettings("/org/freedesktop/NetworkManagerSettings",
1412 def Connect(wanted_net
): # any. or take arg. net is config name or ssid name
1413 # ... in general, look for string in all config data. ssid for wifi, whatever for dialup
1414 # TODO also respect autoconnect
1416 # ActivateConn wants setting device ap; can find device from ap? ap is "specific" for wifi devices
1417 #print "Connection wanted to", wanted_net
1418 found_con
= found_ap
= found_dev
= None
1419 for dev
in nm
.Devices():
1420 for ap
in dev
.APs():
1421 if wanted_net
== ap
.Ssid():
1424 break # FIXME both loops
1425 found_con
= us
.GetByNet(wanted_net
)
1426 if found_ap
== None:
1427 print "No AP found with SSID", wanted_net
1429 if found_con
== None:
1430 print "No settings for net %s, assuming no key is needed" % wanted_net
1431 c
= mkconmap_wifi(wanted_net
)
1432 found_con
= us
.addCon(c
)
1433 nm
.ActivateConnection(found_con
, found_dev
, found_ap
) # TODO async
1434 # TODO run loop, exit it when we have serviced the required calls
1437 if options
.connect
!= None:
1438 if options
.unprotected
:
1439 c
= mkconmap_wifi(options
.connect
)
1441 if options
.wep_hex
!= None:
1442 c
= mkconmap_wep(options
.connect
, options
.wep_hex
)
1444 if options
.wep_pass
!= None:
1445 c
= mkconmap_wep_pass(options
.connect
, options
.wep_pass
)
1447 if options
.wpa_psk_hex
!= None:
1448 c
= mkconmap_psk(options
.connect
, options
.wpa_psk_hex
)
1450 if options
.wpa_pass
!= None:
1451 wpa_psk_hex
= hexlify(pbkdf2
.pbkdf2(options
.wpa_pass
, options
.connect
, 4096, 32))
1452 print "pbkdf2", wpa_psk_hex
1453 c
= mkconmap_psk(options
.connect
, wpa_psk_hex
)
1456 if Connect(options
.connect
):
1463 loop
= gobject
.MainLoop()