forked from seveas/python-networkmanager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
n-m
executable file
·232 lines (193 loc) · 7.99 KB
/
n-m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
#!/usr/bin/python
#
# Command-line tool to interact with NetworkManager. With this tool, you can
# inspect various configuration items and (de-)activate connections.
#
# (C) 2011-2013 Dennis Kaarsemaker
# License: GPL3+
from __future__ import print_function
usage = """%prog [options] action [arguments]
Actions:
list - List all defined and active connections
activate - Activate a connection
deactivate - Deactivate a connection
offline - Deactivate all connections
enable - Enable specific connection types
disable - Disable specific connection types
info - Information about a connection"""
import datetime
from dbus.exceptions import DBusException
import NetworkManager
import optparse
import socket
import struct
import sys
PY3 = sys.version_info[0] >= 3
def main():
p = optparse.OptionParser(usage=usage)
opts, args = p.parse_args()
if not args:
p.print_help()
sys.exit(1)
if args[0] == 'list':
list_()
elif args[0] == 'offline':
offline()
elif args[0] == 'visible':
visible()
elif len(args) < 2:
p.print_help()
sys.exit(1)
elif args[0] == 'activate':
activate(args[1:])
elif args[0] == 'deactivate':
deactivate(args[1:])
elif args[0] == 'enable':
enable(args[1:])
elif args[0] == 'disable':
disable(args[1:])
elif args[0] == 'info':
info(args[1:])
elif args[0] == 'dump':
dump(args[1:])
else:
p.print_help()
sys.exit(1)
def list_():
active = [x.Connection.GetSettings()['connection']['id']
for x in NetworkManager.NetworkManager.ActiveConnections]
connections = [(x.GetSettings()['connection']['id'], x.GetSettings()['connection']['type'])
for x in NetworkManager.Settings.ListConnections()]
fmt = "%%s %%-%ds %%s" % max([len(x[0]) for x in connections])
for conn in sorted(connections):
prefix = '* ' if conn[0] in active else ' '
print(fmt % (prefix, conn[0], conn[1]))
def activate(names):
connections = NetworkManager.Settings.ListConnections()
connections = dict([(x.GetSettings()['connection']['id'], x) for x in connections])
if not NetworkManager.NetworkManager.NetworkingEnabled:
NetworkManager.NetworkManager.Enable(True)
for n in names:
if n not in connections:
print("No such connection: %s" % n, file=sys.stderr)
sys.exit(1)
print("Activating connection '%s'" % n)
conn = connections[n]
ctype = conn.GetSettings()['connection']['type']
if ctype == 'vpn':
for dev in NetworkManager.NetworkManager.GetDevices():
if dev.State == NetworkManager.NM_DEVICE_STATE_ACTIVATED and dev.Managed:
break
else:
print("No active, managed device found", file=sys.stderr)
sys.exit(1)
else:
dtype = {
'802-11-wireless': 'wlan',
'gsm': 'wwan',
}
if dtype in connection_types:
enable(dtype)
dtype = {
'802-11-wireless': NetworkManager.NM_DEVICE_TYPE_WIFI,
'802-3-ethernet': NetworkManager.NM_DEVICE_TYPE_ETHERNET,
'gsm': NetworkManager.NM_DEVICE_TYPE_MODEM,
}.get(ctype,ctype)
devices = NetworkManager.NetworkManager.GetDevices()
for dev in devices:
if dev.DeviceType == dtype and dev.State == NetworkManager.NM_DEVICE_STATE_DISCONNECTED:
break
else:
print("No suitable and available %s device found" % ctype, file=sys.stderr)
sys.exit(1)
NetworkManager.NetworkManager.ActivateConnection(conn, dev, "/")
def deactivate(names):
active = NetworkManager.NetworkManager.ActiveConnections
active = dict([(x.Connection.GetSettings()['connection']['id'], x) for x in active])
for n in names:
if n not in active:
print("No such connection: %s" % n, file=sys.stderr)
sys.exit(1)
print("Deactivating connection '%s'" % n)
NetworkManager.NetworkManager.DeactivateConnection(active[n])
def offline():
try:
NetworkManager.NetworkManager.Enable(False)
except DBusException as e:
if e.get_dbus_name() != 'org.freedesktop.NetworkManager.AlreadyEnabledOrDisabled':
raise
connection_types = ['wireless','wwan','wimax']
def enable(names):
for n in names:
if n not in connection_types:
print("No such connection type: %s" % n, file=sys.stderr)
sys.exit(1)
setattr(NetworkManager.NetworkManager, n.title() + 'Enabled', True)
def disable(names):
for n in names:
if n not in connection_types:
print("No such connection type: %s" % n, file=sys.stderr)
sys.exit(1)
setattr(NetworkManager.NetworkManager, n.title() + 'Enabled', False)
def info(names):
connections = [x.GetSettings() for x in NetworkManager.Settings.ListConnections()]
connections = dict([(x['connection']['id'], x) for x in connections])
for n in names:
if not PY3:
n = n.decode('utf-8')
if n not in connections:
print("No such connection: %s" % n, file=sys.stderr)
return
line = "Info about '%s'" % n
print(line + "\n" + '=' * len(line))
conn = connections[n]
print("Type:", conn['connection']['type'])
print("Connect automatically:", ["No","Yes"][conn['connection'].get('autoconnect', True)])
if 'timestamp' in conn['connection']:
print("Last connected on:", str(datetime.datetime.fromtimestamp(conn['connection']['timestamp'])))
else:
print("Never connected")
print("IPv4 settings (%s)" % conn['ipv4']['method'])
print(" Address(es):", ', '.join([x[0] for x in conn['ipv4']['addresses']]) or '(Automatic)')
print(" DNS servers:", ', '.join(conn['ipv4']['dns']) or '(Automatic)')
print(" Routes:", ", ".join(["%s/%d -> %s" % x[:3] for x in conn['ipv4']['routes']]))
print(" Can be default route:", ["Yes","No"][conn['ipv4'].get('never-default', False)])
if conn['connection']['type'] == '802-3-ethernet':
print("Physical link")
print(" MAC address:", conn['802-3-ethernet'].get('mac-address', '(Automatic)'))
elif conn['connection']['type'] == '802-11-wireless':
print("Wireless link")
print(" MAC address:", conn['802-11-wireless'].get('mac-address', '(Automatic)'))
print(" SSID:", conn['802-11-wireless']['ssid'])
if 'security' in conn['802-11-wireless']:
print(" Wireless security:", conn[conn['802-11-wireless']['security']]['key-mgmt'])
elif conn['connection']['type'] == 'vpn':
print("VPN")
print(" Type:", conn['vpn']['service-type'].rsplit('.',1)[-1])
print(" Remote:", conn['vpn']['data']['remote'])
def dump(names):
from pprint import pprint
connections = {}
for conn in NetworkManager.Settings.ListConnections():
settings = conn.GetSettings()
secrets = conn.GetSecrets()
for key in secrets:
settings[key].update(secrets[key])
connections[settings['connection']['id']] = settings
for n in names:
if n not in connections:
print("No such connection: %s" % n, file=sys.stderr)
pprint(connections[n])
def visible():
for device in NetworkManager.NetworkManager.GetDevices():
if device.DeviceType != NetworkManager.NM_DEVICE_TYPE_WIFI:
continue
print("Visible on %s" % device.Udi[device.Udi.rfind('/')+1:])
device = device.SpecificDevice()
active = device.ActiveAccessPoint
aps = device.GetAccessPoints()
for ap in aps:
prefix = '* ' if ap.object_path == active.object_path else ' '
print("%s %s" % (prefix, ap.Ssid))
if __name__ == '__main__':
main()