forked from slemire/sshpoller
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsshpoller.py
executable file
·455 lines (380 loc) · 13 KB
/
sshpoller.py
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Import standard python modules
import argparse
from getpass import getpass
import csv
import json
import logging
import sys
from time import sleep, time
import tempfile
import yaml
from multiprocessing import Process, Queue
# TextFSM module : https://github.com/google/textfsm
import clitable
# Netmiko module : https://github.com/ktbyers/netmiko
from netmiko import ConnectHandler, ssh_exception
# InfluxDB module : https://github.com/influxdata/influxdb-python
from influxdb import InfluxDBClient
CSV_DELIMITER = ','
# TEXTFSM config settings
index_file = 'index'
template_dir = 'templates'
class SSH_Poller:
""" SSH Poller class """
# InfluxDB settings (you should change these)
db_host = 'localhost'
db_port = 8086
db_name = 'db_name'
db_user = 'root'
db_password = 'root'
def __init__(self, task):
self.data_list = []
self.hostname = task['hostname']
self.port = task['port']
self.username = task['username']
self.password = task['password']
self.device_type = task['device_type']
self.parser_mode = task['parser_mode']
self.command_list = []
self.precommand_list = task['precommands']
self.interval = task['interval']
self.prompt = ''
self.sock = ConnectHandler
for command in task['commands']:
# Command doesn't contain tags attribute
if len(command.split(':')) == 1:
self.command_list.append({'command': command.split(':')[0], 'tag': ''})
# Command contains tags attribute
elif len(command.split(':')) == 2:
self.command_list.append({'command': command.split(':')[0], 'tag': command.split(':')[1]})
def connect(self):
""" Connects SSH session """
try:
self.sock = ConnectHandler(
device_type=self.device_type,
ip=self.hostname,
port=self.port,
username=self.username,
password=self.password)
logging.debug('Connection to %s successful!' % self.hostname)
self.prompt = self.sock.find_prompt()
if self.prompt:
logging.debug('Prompt found: %s' % self.prompt)
# Send commands after login that won't be parsed
if self.precommand_list:
for precommand in self.precommand_list:
self.sock.send_command(precommand)
else:
logging.debug('No prompt found')
except ssh_exception.NetMikoAuthenticationException:
logging.error('Authentication error, username was %s' % self.username)
return False
except:
print("Unexpected error:", sys.exc_info()[0])
raise
return True
def disconnect(self):
""" Disconnects SSH session """
self.sock.disconnect()
logging.debug('Connection cleaned-up')
def parse_fsm(self, result, command):
""" Parses command output through TextFSM """
result = ''.join(result)
cli_table = clitable.CliTable(index_file, template_dir)
attrs = {'Command': command['command'], 'Platform': self.device_type}
try:
cli_table.ParseCmd(result, attrs)
# Timestamp precision is set to 'seconds'
timestamp = int(time())
for field in clitable_to_dict(cli_table):
data = {}
data['tag'] = {'host': self.hostname, 'command': command['tag']}
data['command'] = command['command']
data['fields'] = dict((k, float_if_possible(v)) for (k, v) in field.items())
if command['tag']:
data['tag'][command['tag']] = data['fields'][command['tag']]
data['timestamp'] = timestamp
self.data_list.append(data)
return True
except clitable.CliTableError as e:
logging.error('FSM parsing error: %s' % str(e))
return False
def parse_csv(self, result, command):
""" Parse command output as csv """
# CVS module needs to read from a file, let's create one
csvfile = tempfile.TemporaryFile()
result_list = result.split('\n')
# Add lines until we find first empty line
for line in result_list:
if line != "":
csvfile.write("%s\n" % line)
else:
break
csvfile.seek(0)
reader = csv.DictReader(csvfile)
# Timestamp precision is set to 'seconds'
timestamp = int(time())
for idx, row in enumerate(reader):
data = {}
data['tag'] = {'host': self.hostname, 'instance': idx}
data['command'] = command['command']
row = dict((k, float_if_possible(v)) for (k, v) in row.items())
data['fields'] = row
data['timestamp'] = timestamp
self.data_list.append(data)
return True
def send_commands(self):
""" Send all commands in task
Stores all parsed output in self.data_list
"""
for command in self.command_list:
logging.debug('Sending command: %s' % command['command'])
result = self.sock.send_command(command['command'])
logging.debug('Output of command: %s' % command['command'])
logging.debug(result)
if self.parser_mode == 'fsm':
self.parse_fsm(result, command)
elif self.parser_mode == 'csv':
self.parse_csv(result, command)
def output_json(self):
""" Return results in JSON format """
print(json.dumps(self.data_list, indent=2))
def output_influxdb(self):
""" Writes data to the InfluxDB """
client = InfluxDBClient(self.db_host, self.db_port, self.db_user, self.db_password, self.db_name)
# TODO: Refactor to batch to optimize writes to the DB
for data in self.data_list:
measurement = data['command']
# Build JSON body for the REST API call
json_body = [
{
'measurement': measurement,
'tags': data['tag'],
'fields': data['fields'],
'time': data['timestamp']
}
]
client.write_points(json_body, time_precision='s')
def quotes_in_str(value):
""" Add quotes around value if it's a string """
if type(value) == str:
return ("\"%s\"" % value)
else:
return (value)
def int_if_possible(value):
""" Convert to int if possible """
try:
return int(value)
except:
return value
def float_if_possible(value):
""" Convert to float if possible """
try:
return float(value)
except:
return value
def clitable_to_dict(cli_table):
"""Converts TextFSM cli_table object to list of dictionaries """
objs = []
for row in cli_table:
temp_dict = {}
for index, element in enumerate(row):
temp_dict[cli_table.header[index].lower()] = element
objs.append(temp_dict)
return objs
def worker(input_queue, output_queue):
""" Worker thread """
# Fetch a task from the queue
task = input_queue.get()
# Exit if guardian is found
if task == 'STOP':
return
poller = SSH_Poller(task)
if poller.connect():
if task['mode'] == 'json':
logging.info('JSON mode selected')
poller.send_commands()
poller.output_json()
elif task['mode'] == 'influx':
logging.info('InfluxDB mode selected, polling every %s seconds' % task['interval'])
if task['interval'] == 0:
# Interval not set, we'll just poll once
poller.send_commands()
poller.output_influxdb()
else:
# Interval is set, start polling loop
while True:
poller.send_commands()
poller.output_influxdb()
sleep(float(task['interval']))
else:
return
def main(args, loglevel):
# Logging format
logging.basicConfig(format="%(asctime)s %(levelname)s: %(message)s", level=loglevel)
# Set variables from CLI args
hostname = args.hostname
port = args.port
username = args.username
password = args.password
mode = args.mode # Valid choices: json, influx
device_type = args.device_type # See netmiko's doc for valid types
parser_mode = args.parse # Valid choices : fsm, csv
commands = args.commands
precommands = args.precommands
num_threads = args.threads
interval = args.interval
yaml_filename = args.yaml
yaml_task_list = []
# Ask for credentials if not passed from CLI args
if not username:
username = raw_input('Enter username:')
if not password:
password = getpass('Enter password:')
# YAML file parsing
if yaml_filename:
f = open(yaml_filename)
buf = f.read()
f.close()
yaml_task_list = yaml.load(buf)
num_threads = len(yaml_task_list)
input_queue = Queue()
output_queue = Queue()
if yaml_filename:
# Add our task to the queue
for yaml_task in yaml_task_list:
task = {
'hostname': yaml_task['device_name'],
'username': username,
'password': password,
'mode': 'influx',
'device_type': yaml_task['device_type'],
'parser_mode': yaml_task['parse_mode'],
'commands': yaml_task['commands'],
'precommands': yaml_task['post_login_commands'],
'interval': interval
}
if yaml_task['port']:
task['port'] = yaml_task['port']
else:
task['port'] = 22
input_queue.put(task)
logging.debug('Added task to the queue: %s' % task)
else:
# Add our task to the queue
task = {
'hostname': hostname,
'port': port,
'username': username,
'password': password,
'mode': mode,
'device_type': device_type,
'parser_mode': parser_mode,
'commands': commands,
'precommands': precommands,
'interval': interval
}
input_queue.put(task)
logging.debug('Added task to the queue: %s' % task)
# Add guardian to the queue
for i in range(1, num_threads + 1):
input_queue.put('STOP')
# Start processes
for i in range(1, num_threads + 1):
p = Process(target=worker, args=(input_queue, output_queue))
p.start()
logging.debug('Process %s PID %s started' % (i, p.pid))
if __name__ == '__main__':
# Setup parser
parser = argparse.ArgumentParser(
description="Screen scrapping poller with JSON & InfluxDB output",
epilog="As an alternative to the commandline, params can be placed in a file, one per line, and specified on the commandline like '%(prog)s @params.conf'.",
fromfile_prefix_chars='@'
)
# Hostname and YAML are mutually exclusive
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument(
"-H",
"--hostname",
help="hostname",
)
group.add_argument(
"-y",
"--yaml",
help="YAML input file",
)
parser.add_argument(
"-c",
"--commands",
nargs="+",
help="Command:Tags",
)
parser.add_argument(
"-C",
"--precommands",
nargs="+",
help="Commands sent after connection (will not be parsed)",
)
parser.add_argument(
"-d",
"--device_type",
help="Device type (FSM mode only)",
default='linux'
)
parser.add_argument(
"-m",
"--mode",
help="Output mode (default = json)",
choices=['json', 'influx'],
default='json'
)
parser.add_argument(
"-i",
"--interval",
help="Polling interval (sec)",
default=0
)
parser.add_argument(
"-u",
"--username",
help="SSH username"
)
parser.add_argument(
"-p",
"--password",
help="SSH password"
)
parser.add_argument(
"-o",
"--port",
help="SSH port",
default=22
)
parser.add_argument(
"-P",
"--parse",
help="Text input format (default = fsm)",
choices=['fsm', 'csv'],
default='fsm'
)
parser.add_argument(
"-t",
"--threads",
help="# of threads",
default=1
)
parser.add_argument(
"-v",
"--verbose",
help="increase output verbosity",
action="store_true"
)
args = parser.parse_args()
# Setup logging
if args.verbose:
loglevel = logging.DEBUG
else:
loglevel = logging.ERROR
main(args, loglevel)