This repository has been archived by the owner on Jan 27, 2023. It is now read-only.
/
n-m
executable file
·200 lines (165 loc) · 7.01 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
#!/usr/bin/python
"""
n-m is a command-line tool to deal with network-manager. It can connect you to
defined networks and disconnect you again.
"""
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
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 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 n not in connections:
print("No such connection: %s" % n, file=sys.stderr)
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)])
print("Last connected on:", str(datetime.datetime.fromtimestamp(conn['connection']['timestamp'])))
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'])
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):
connections = [x.GetSettings() for x in NetworkManager.Settings.ListConnections()]
connections = dict([(x['connection']['id'], x) for x in connections])
for n in names:
if n not in connections:
print("No such connection: %s" % n, file=sys.stderr)
from pprint import pprint
pprint(connections[n])
if __name__ == '__main__':
main()