-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathpsdiff
More file actions
executable file
·1729 lines (1443 loc) · 63.8 KB
/
Copy pathpsdiff
File metadata and controls
executable file
·1729 lines (1443 loc) · 63.8 KB
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# psdiff (part of ossobv/vcutil) // wdoekes/2016-2020,2021,2023,2025-2026
# // Public Domain
#
# Generic (coarse) monitoring of daemon processes. Use in conjunction
# with a monitoring suite like Zabbix.
#
import argparse
import collections
import difflib
import os
import re
import subprocess
import sys
import textwrap
import time
import warnings
DBNAME = '/var/lib/psdiff.db'
def human_key(s):
"""Sort key that handles numbers naturally. Works for IPs, ports, etc."""
# On Python3, tuple([]) is slightly faster than [] or tuple() when passing
# the result to sort, which we do.
return tuple([
int(token) if token.isdigit() else token
for token in human_key.re.split(s)
if token]) # against leading and trailing empty separators
human_key.re = re.compile(r'(\d+)') # noqa
class Process(object):
"""
A single process as found in the psdiff.db: an indented cmdline with
properties.
The line:
' INIT {user=root, listen=(tcp:0.0.0.0:22,tcp:[::]:22)}'
is parsed by from_line() into:
Process(indent=1, cmdline='INIT', user='root',
listen=('tcp:0.0.0.0:22', 'tcp:[::]:22'))
and to_line() turns it back into the exact same line. Properties we
do not know about are kept -- in order -- so a db written by a newer
psdiff does not lose information when it is read by an older one.
"""
# 'cmdline {user=root, listen=(a,b)}': the cmdline is greedy, so we
# split on the last ' {', not on one that is part of the cmdline.
re_line = re.compile(r'^( *)(.*) \{(.*)\}$')
# ', ' separates properties, but only when a 'key=' follows: values
# (like a listen list) may contain a comma too.
re_prop = re.compile(r', (?=[a-z_]+=)')
# Properties that hold zero or more values instead of exactly one.
tuple_props = ('listen',)
@classmethod
def from_line(cls, line):
match = cls.re_line.match(line)
if not match:
raise ValueError('unparsable psdiff.db line: {!r}'.format(line))
indent, cmdline, propstr = match.groups()
props = collections.OrderedDict(
cls.parse_prop(prop) for prop in cls.re_prop.split(propstr))
try:
user = props.pop('user')
except KeyError:
raise ValueError(
'psdiff.db line without user: {!r}'.format(line))
return cls(len(indent) // 2, cmdline, user, props=props)
@classmethod
def parse_prop(cls, prop):
"Parse 'user=root' or 'listen=(a,b)' into a (key, value) tuple."
key, sep, value = prop.partition('=')
if not sep:
raise ValueError('unparsable psdiff.db property: {!r}'.format(
prop))
if value.startswith('(') and value.endswith(')'):
value = tuple(i for i in value[1:-1].split(',') if i)
elif key in cls.tuple_props:
value = (value,)
return key, value
@staticmethod
def format_value(value):
"The inverse of parse_prop() value handling."
if not isinstance(value, tuple):
return value
if len(value) == 1:
return value[0] # a single value is written without parens
return '({})'.format(','.join(value))
def __init__(self, indent, cmdline, user, listen=(), props=None):
self.indent = indent
self.cmdline = cmdline
self.user = user
# Everything after 'user=', in the order we found it. Storing
# listen in here -- instead of next to it -- keeps the order of
# any unknown properties intact when we write the line back.
self.props = collections.OrderedDict(props or ())
if listen:
self.listen = listen
@property
def listen(self):
return self.props.get('listen', ())
@listen.setter
def listen(self, value):
if value:
self.props['listen'] = tuple(value)
else:
self.props.pop('listen', None)
def without_listen(self):
"Return a copy without listen info, for --no-net on a --net db."
return type(self)(
self.indent, self.cmdline, self.user, props=[
(key, value) for key, value in self.props.items()
if key != 'listen'])
def same_process(self, other):
"Whether this is the same process, listen info excluded."
if (self.indent != other.indent or self.cmdline != other.cmdline or
self.user != other.user):
return False
keys = set(self.props) | set(other.props)
keys.discard('listen')
return all(
self.props.get(key) == other.props.get(key) for key in keys)
def to_line(self):
"Return the single db line for this process."
return self.render(expand_listen=False)[0]
def to_diff_lines(self):
"""
Return (indent, head, items, tail) for multiline diff output.
Without listen info, items and tail are empty and head holds the
entire line (sans indent). With listen info, every address gets
its own line, so that a diff between two of these shows only the
addresses that actually changed:
/usr/sbin/named {user=bind, listen=(
tcp:0.0.0.0:53,
udp:0.0.0.0:53,
)}
"""
indent = self.indent * u' '
head, items, tail = self.render(expand_listen=True)
return indent, head[len(indent):], items, tail
def render(self, expand_listen=False):
"""
Return (head, items, tail); the single source of db line layout.
Unless expand_listen is set -- and there is listen info -- items
and tail are empty and head is the complete line.
"""
expand_listen = bool(expand_listen and self.listen)
head = [self.indent * u' ', self.cmdline, u' {user=', self.user]
items = ()
tail = []
current = head
for key, value in self.props.items():
if key == 'listen' and expand_listen:
current.append(u', listen=(')
items = self.listen
current = tail # any next properties go after the ')'
current.append(u')')
else:
current.append(u', {}={}'.format(key, self.format_value(
value)))
current.append(u'}')
return u''.join(head), items, u''.join(tail)
def sort_key(self):
return (self.indent, self.cmdline, self.user,
tuple(self.props.items()))
def __hash__(self):
return hash(self.sort_key())
def __eq__(self, other):
return (
self.indent == other.indent and
self.cmdline == other.cmdline and
self.user == other.user and
self.props == other.props)
def __ne__(self, other): # py2
return not self.__eq__(other)
def __lt__(self, other):
return self.sort_key() < other.sort_key()
def __repr__(self):
extra = ''.join(
', {}={!r}'.format(key, value)
for key, value in self.props.items())
return 'Process(indent={!r}, cmdline={!r}, user={!r}{})'.format(
self.indent, self.cmdline, self.user, extra)
def __str__(self):
return self.to_line()
class LiveProcess(object):
"""
A process as found in the ps(1) output: part of a pid/ppid tree.
"""
split = re.compile(r'\s+')
@classmethod
def from_line(cls, line, root):
args = cls.split.split(line, 3)
user = args[0]
pid = int(args[1])
ppid = int(args[2])
exe = args[3][0:8].rstrip()
assert args[3][8] == ' '
cmdline = args[3][9:]
return cls(ppid, pid, user, exe, cmdline, root=root)
def __init__(self, parent, pid, user, exe, cmdline, root=None):
self.parent = parent
self.pid = pid
self.user = user
self.exe = exe
self.cmdline = cmdline
self.root = root or self
self.include = True
if not root:
self.process_map = {}
self.root.process_map[pid] = self
self.children = set()
# Enriched info
self._listens = set()
def skip(self):
self.include = False
# Move the _listens to the parent.
if self._listens:
obj = self
while obj:
obj = obj.parent
if obj.include:
break
assert not obj._listens, (self, obj)
obj.add_listens(self._listens)
self._listens = frozenset() # make it empty/unusable
def has_parent(self, include_self=False,
cmdline__startswith=None, pid=None):
obj = self
if not include_self:
obj = obj.parent
while obj:
if (cmdline__startswith is not None and
obj.cmdline.startswith(cmdline__startswith)):
return True
if pid is not None and obj.pid == pid:
return True
obj = obj.parent
return False
def fix_links(self):
if self.parent is not None:
# Convert ppid to parent.
self.parent = self.root.process_map[self.parent]
# Add us as child of the parent.
self.parent.children.add(self)
def get_process(self, pid):
if not pid:
return None
return self.root.process_map[pid]
def to_process(self, indent=0):
"Return the db representation (a Process) of this process."
return Process(
indent, self.cmdline.rstrip(), self.user, listen=self._listens)
def to_string(self, indent=0):
return self.to_process(indent).to_line()
def sort(self):
# Sort the children and convert the set into a list.
for child in self.children:
child.sort()
self.children = tuple(sorted(self.children))
# Sort the listen addresses the same way we write them out, so
# that comparison and output agree on the order.
self._listens = tuple(sorted(self._listens, key=human_key))
def add_listens(self, listens):
self._listens |= set(listens)
def __hash__(self):
# Needs to be reimplemented because Python3 drops the
# auto-generated one when __eq__ is defined.
return id(self)
def __eq__(self, other):
# Not only identity comparison yields same, otherwise
# we end up comparing children as unequal and then
# sorting of parents fails because non-id siblings
# aren't considered.
return (
self.include == other.include and
self.cmdline == other.cmdline and
self.user == other.user and
self._listens == other._listens and
self.children == other.children)
def __lt__(self, other):
if self.include != other.include:
return (self.include > other.include) # first True
# Lazy comparison.
if self.cmdline != other.cmdline:
return (self.cmdline < other.cmdline)
if self.user != other.user:
return (self.user < other.user)
if self._listens != other._listens:
return (self._listens < other._listens)
assert isinstance(self.children, tuple), self.children
assert isinstance(other.children, tuple), other.children
return (self.children < other.children)
def __repr__(self):
return '<LiveProcess({}, user={}, id={})>'.format(
self.cmdline, self.user, id(self))
def __str__(self):
return self.to_string()
class ProcessFormatter(object):
def __init__(self, root):
self.root = root
# Add self.adjust hook to alter process traits before sort.
self.visit(self.adjust)
# Skip processes.
self.visit((lambda process: (
None if self.include(process) else process.skip())))
# Sort processes.
self.visit((lambda process: process.sort()))
def visit(self, callable_):
"Visit all processes with callable."
for process in self.root.process_map.values():
callable_(process)
def to_strings(self, process, indent=0):
"Return a list of stringified children with indentation."
ret = []
if process.include:
ret.append(self.to_string(process, indent))
for child in process.children: # has been sorted already
ret.extend(self.to_strings(child, indent + 1))
return ret
def to_processes(self):
"""
Return the listing as a list of Process items.
This goes through to_strings() -- and thus through the
to_string() hook that psdiff.conf files may override -- so that
what we compare can never drift from what we write to the db.
"""
processes = []
for line in self.to_strings(self.root):
try:
processes.append(Process.from_line(line))
except ValueError as e:
raise ValueError(
'{} (from {}.to_string(); a psdiff.conf hook must '
'return a valid db line)'.format(
e, type(self).__name__))
return processes
def __str__(self):
return u'\n'.join(self.to_strings(self.root)) + '\n'
def adjust(self, process):
"""
The possibility to adjust cmdline and other process traits.
This is called before sort, so you'll want to use this to alter
cmdline.
"""
pass
def include(self, process):
"The possibility to exclude processes from the listing."
return True
def to_string(self, process, indent=0):
"The old hook to alter cmdline appearance."
return process.to_string(indent)
class FilteredProcessFormatter(ProcessFormatter):
def __init__(self, *args, **kwargs):
self._include_once = set()
super(FilteredProcessFormatter, self).__init__(*args, **kwargs)
def adjust(self, process):
super(FilteredProcessFormatter, self).adjust(process)
if process.cmdline.startswith((
'astcanary', # astcanary /var/run/asterisk/... <pid>
'/usr/sbin/amavisd-new ')):
# These processes have fluctuating arguments. Drop them.
process.cmdline = process.cmdline.split(' ', 1)[0]
elif process.cmdline.startswith(
'sshd: /usr/sbin/sshd -D [listener] '):
parts = process.cmdline.split(' ', 6)
if len(parts) == 7 and parts[4].isdigit() and parts[5] == 'of':
parts[4] = '0'
process.cmdline = ' '.join(parts)
elif process.cmdline.startswith((
'/usr/sbin/zabbix_proxy: ',
'/usr/sbin/zabbix_server: ')):
# zabbix_proxy and zabbix_server add " [info]" which changes.
# Drop it.
process.cmdline = process.cmdline.split(' [', 1)[0]
elif process.cmdline.startswith((
'/usr/bin/containerd-shim-runc-v2 ',
'containerd-shim ',
'docker-containerd-shim ')):
# Docker 18+ instances have fluctuating arguments:
# /usr/bin/containerd-shim-runc-v2 -namespace moby -id <ID> ...
# containerd-shim ... -workdir /var/...containerd/<ID> ...
args = process.cmdline.split()
if '-id' in args:
# -id [ID]
pos = args.index('-id') + 1
if pos < len(args):
args[pos] = '<ID>'
if '-workdir' in args:
# -workdir [PATH]
# /var/lib/containerd/io.containerd.runtime.v1.linux/moby/<ID>
pos = args.index('-workdir') + 1
if pos < len(args):
args[pos] = args[pos].rsplit('/', 1)[0] + '/<ID>'
if len(args) == 4 and args[3] == 'docker-runc':
# Docker 17- instances have fluctuating arguments:
# docker-containerd-shim <ID> /var/...containerd/<ID> \
# docker-runc
args[1] = '<ID>'
args[2] = args[2].rsplit('/', 1)[0] + '/<ID>'
process.cmdline = ' '.join(args)
def include(self, process):
# Ignore kernel threads.
if process.has_parent(include_self=True, pid=2):
return False
# Systemd renames itself after an update. We can't rename it
# back to /sbin/init because it may have been called differently
# (/sbin/init splash or whatever) in the first place.
elif process.pid == 1:
# /sbin/init [splash]
# /lib/systemd/systemd --system --deserialize 19
process.cmdline = 'INIT'
# Children of these commands are generally not daemons, skip
# them:
elif process.has_parent(include_self=True, cmdline__startswith=(
'CRON', 'SCREEN', '-tmux',
'/USR/SBIN/CRON', # older cron
'/usr/sbin/CRON', # newer cron
# Is a daemon, but spawns children of init for extra work.
'/usr/bin/python /usr/bin/salt-minion',
# Comes and goes.
'/usr/libexec/fwupd/fwupd')):
return False
# We want to monitor these daemons, but not their
# (grand)children, as they come and go:
elif process.has_parent(include_self=False, cmdline__startswith=(
'/usr/sbin/dovecot',
'/usr/sbin/gocollect', # gc: sysv/systemd
'gocollect', # gc: ubuntu (upstart)
'/usr/lib/postfix/master', # pf: debian/ubuntu
'/usr/lib/postfix/sbin/master', # pf: ubuntu16.04+
'/usr/libexec/postfix/master', # pf: redhat
'/usr/lib/postgresql/',
'/usr/sbin/sshd ', # sshd: sysv
'sshd: /usr/sbin/sshd ', # sshd: modern
'/lib/systemd/systemd-udevd', # udev: pre-usrmerge path
'/usr/lib/systemd/systemd-udevd', # udev: modern
'/usr/sbin/vsftpd',
'/usr/sbin/zabbix_agent2',
'/usr/sbin/zabbix_agentd')):
return False
# These children may come and go, but we expect at least one:
# - multiprocess apache creates at least N processes but may add/remove
# based on demand
elif process.cmdline.startswith((
'/usr/sbin/apache2 ', # debian/ubuntu
'/usr/sbin/httpd ', # redhat
'php-fpm: ')):
key = (process.parent.pid, process.user, process.cmdline)
if key in self._include_once:
return False
else:
self._include_once.add(key)
# These ones may come and go. Don't care if they exist.
# - uuidd gets spawned at will
# - zfs get can be slow; it's used by various processes (like kubelet)
elif ((process.user == 'uuidd' and
process.cmdline == '/usr/sbin/uuidd --socket-activation') or
(process.user == 'root' and
process.cmdline.startswith(('zfs get ', 'zfs list')))):
return False
# Special case since Ubuntu noble (systemd 255), we expect this one in
# combination with sd-pam, but no other children.
elif process.cmdline in (
'/lib/systemd/systemd --user',
'/usr/lib/systemd/systemd --user') and all(
child.exe == '(sd-pam)' and not child.children
for child in process.children):
return False
# (sd-pam) comes and goes. Generally as child of systemd --user.
elif process.cmdline == process.exe == '(sd-pam)':
return False
return super(FilteredProcessFormatter, self).include(process)
def diff_items(alines, blines):
"""
Diff two sequences of hashable items (Process items, or the listen
addresses of a single Process).
Returns a list of (direction, item) tuples where direction is
-1 (removed), 0 (unchanged/context) or 1 (added):
# alines: ['aa','bb','cc']
# blines: ['bb','dd','ff']
[(-1, 'aa'), (0, 'bb'), (-1, 'cc'), (1, 'dd'), (1, 'ff')]
We use SequenceMatcher.get_opcodes() directly (the same primitive
difflib.unified_diff and difflib.ndiff build on) rather than ndiff
itself: ndiff takes exponential time on some machines for psdiff
dumps of ~200 lines, which isn't acceptable.
See: https://bugs.python.org/issue6931
Unlike unified_diff, we don't truncate to N lines of context around
each change: callers that don't care (the top-level whole-process
diff) drop the context items themselves, and callers that diff the
listen addresses of a process need every address as context, not
just the ones close to a change.
"""
changes = []
for tag, i1, i2, j1, j2 in (
difflib.SequenceMatcher(None, alines, blines).get_opcodes()):
if tag == 'equal':
changes.extend((0, item) for item in alines[i1:i2])
else:
if tag in ('delete', 'replace'):
changes.extend((-1, item) for item in alines[i1:i2])
if tag in ('insert', 'replace'):
changes.extend((1, item) for item in blines[j1:j2])
return changes
def parse_db(data):
"""
Parse psdiff.db contents into a list of Process items.
"""
processes = []
for lineno, line in enumerate(data.split(u'\n'), 1):
if not line:
continue # the trailing LF, mostly
try:
processes.append(Process.from_line(line))
except ValueError as e:
raise ValueError('{} (line {})'.format(e, lineno))
return processes
def format_db(processes):
"""
The inverse of parse_db(): the psdiff.db contents for these
Process items.
"""
return u''.join(
u'{}\n'.format(process.to_line()) for process in processes)
def group_process_changes(changes):
"""
Post-process diff_items() output: pair up adjacent removed/added
processes that are the same process -- only their listen addresses
differ -- so they can be diffed by listen address instead of as two
unrelated processes.
Yields ('single', direction, process) for a process shown on its
own, or ('pair', old_process, new_process) for a same-process pair.
"""
i, n = 0, len(changes)
while i < n:
direction, process = changes[i]
if direction >= 0:
yield ('single', direction, process)
i += 1
continue
removed = []
while i < n and changes[i][0] < 0:
removed.append(changes[i][1])
i += 1
added = []
while i < n and changes[i][0] > 0:
added.append(changes[i][1])
i += 1
unmatched_added = list(added)
for old in removed:
# Only pair when there is listen info to diff; without it
# the pair would have nothing to show.
match = next(
(new for new in unmatched_added
if (old.listen or new.listen) and old.same_process(new)),
None)
if match is None:
yield ('single', -1, old)
else:
unmatched_added.remove(match)
yield ('pair', old, match)
for new in unmatched_added:
yield ('single', 1, new)
def ps_faxu(with_network=False):
cmd = ['ps', 'ax', '-o', 'user,pid,ppid,fname,args']
try:
output = subprocess.check_output
except AttributeError:
# Blegh. Python 2.6. (You did already `pip install argparse`, yes?)
proc = subprocess.Popen(cmd, bufsize=-1, stdout=subprocess.PIPE)
output = proc.communicate()[0]
proc.wait()
else:
output = subprocess.check_output(cmd, bufsize=-1)
# Get socket data as quickly as possible.
sockets_by_pid = None
if with_network:
try:
# Get listen addresses per pid in a dictionary:
# {1234: ['tcp:0.0.0.0:80', 'tcp:0.0.0.0:443']}
sockets_by_pid = netstat()
except (subprocess.CalledProcessError, OSError):
# If there is no 'ss' (super-netstat) or we have too few perms
# to use it fruitfully, accept it.
# - CalledProcessError = ss returned non-zero
# - FileNotFoundError(OSError) = there is no ss
# - PermissionDeniedError(OSError) = we're not allowed to call ss
warnings.warn(
'--net info requested but failed (no perms? no ss(1)?)')
output = output.decode('ascii', 'replace')
root = LiveProcess(None, 0, 'root', 'root', 'root')
for i, line in enumerate(output.split('\n')):
if i == 0 or not line:
pass
else:
LiveProcess.from_line(line, root)
# Update processes with proper links. This must be done last because
# the process output is unordered and we may not have the parent
# process info yet earlier.
for process in root.process_map.values():
process.fix_links()
# We have pids and netstat has pids. Amend the processes with socket info.
if sockets_by_pid is not None:
process_pids = set(root.process_map.keys())
socket_pids = set(sockets_by_pid.keys())
both_pids = process_pids & socket_pids
for pid in both_pids:
root.process_map[pid].add_listens(sockets_by_pid[pid])
for pid in (socket_pids - both_pids):
root.process_map[0].add_listens(sockets_by_pid[pid])
return root
def get_ephemeral_ports():
# '32768<TAB>60999<LF>'
with open('/proc/sys/net/ipv4/ip_local_port_range', 'r') as fp:
ports = tuple(int(port) for port in fp.read().strip().split(None, 1))
assert 0 <= ports[0] < ports[1] < 65536, ports
return ports
def netstat():
# -H no-header
# -n numeric
# -l listen
# -p with-process
cmd = ['ss', '-Hnlp']
proc = subprocess.Popen(
cmd, bufsize=-1, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
env={'LC_ALL': 'C'})
output, error = proc.communicate()
if proc.wait() != 0:
raise ValueError('{cmd} returned {ret}: {err}'.format(
cmd=cmd, ret=proc.returncode, err=error))
error = error.decode('ascii', 'replace')
# On Ubuntu/Noble with kernel 7.0, we get EINVAL on netlink query of --dccp
# sockets. Since we're not specifying the exact list, we cannot exclude
# it either. Silence the error instead.
if set(error.splitlines()) != set(['RTNETLINK answers: Invalid argument']):
print(error, end='', file=sys.stderr)
output = output.decode('ascii', 'replace')
# Fetch local port range.
ephemeral_min, ephemeral_max = get_ephemeral_ports()
output = output.strip().split('\n')
lines = [line.rstrip().split(None, 6) for line in output]
# Netid State Recv-Q Send-Q LocalAddr:Port PeerAddr:Port Proc
proc_listens = collections.defaultdict(list)
for line in lines:
transport = line[0]
# Ignore/skip unix sockets and netlink.
if transport in ('u_dgr', 'u_seq', 'u_str', 'nl'):
continue
addr, port = line[4].rsplit(':', 1) # 0.0.0.0:12345 | [::]:12345
is_ephemeral = None # maybe
if len(line) < 7:
# Some are handled by the kernel (module). Pretend we saw it
# as kernel. (It will get appended to the INIT process.)
if transport == 'udp' and addr in ('0.0.0.0', '[::]') and port in (
'51871', '6081', # cilium/wg + geneve/wg
'8472', # vxlan
'500', '4500', # ipsec
):
line.append('users:(("KERNEL",pid=1,fd=-1))')
is_ephemeral = False
else:
# We need root to get the process info. Bail immediately.
raise OSError(1, 'Operation not permitted') # EPERM
if transport == 'p_raw' and addr == '*' and port.startswith((
'enx', 'fwln', 'fwpr', 'lxc', 'tap')):
# Skip these.
continue
if (is_ephemeral is None and transport in ('mptcp', 'tcp', 'udp')
and ephemeral_min <= int(port) <= ephemeral_max):
is_ephemeral = True
if is_ephemeral and transport in ('mptcp', 'udp'):
port = '0' # likely the port was assigned this way using bind()
bindaddr = '{}:{}:{}'.format(transport, addr, port)
users = line[6]
assert users.startswith('users:('), line
assert users.endswith(')'), line
idx = 7
state = 0
while True:
# ("zabbix_agentd",pid=1744582,fd=6)
if state == 0:
assert users[idx] == '('
state = 1
elif state == 1:
assert users[idx] == '"'
state = 2
elif state == 2:
if users[idx] == '"':
state = 3
elif state == 3:
assert users[idx] == ','
nidx = users.index(')', idx + 1)
pidinfo = users[idx + 1:nidx].split(',', 1)[0]
assert pidinfo.startswith('pid='), users
pid = int(pidinfo[4:])
proc_listens[pid].append(bindaddr)
state = 4
idx = nidx
elif state == 4:
if users[idx] == ')':
state = 5
break
elif users[idx] == ',':
state = 0
idx += 1
new_listens = {}
for key, value in proc_listens.items():
new_listens[key] = value
# {fd: [addr1, addr2]}
# {1047: ['icmp6:*:58', 'tcp:127.0.0.1:2601']}
return new_listens
def eval_psdiff_d(dirname):
sources = [
os.path.join(dirname, f) for f in os.listdir(dirname)
if not f.startswith('.') and f.endswith('.py')]
sources.sort()
mixins = []
for source_file in sources:
try:
with open(source_file, 'r') as fh:
source = fh.read()
# You really don't need FilteredProcessFormatter or
# ProcessFormatter or eval_psdiff_conf or any of that.
# If you're going to do really fancy stuff, use custom
# psdiff.conf and go from there.
io = {}
exec(source, io)
mixins.append(io['ProcessFormatterMixin']) # one Mixin per file
except Exception:
import traceback
raise ValueError(
'exec error reading {!r}\n\n {}'.format(
source_file,
'\n '.join(traceback.format_exc().split('\n'))))
return {'LocalProcessFormatterMixins': mixins}
def eval_psdiff_conf(filename):
with open(filename, 'r') as fh:
source = fh.read()
# Ooohh.. eval/exec. Supply FilteredProcessFormatter and
# ProcessFormatter so they can be used as superclass.
# And pass eval_psdiff_d so you can use a custom
# psdiff.conf and _also_ load psdiff.d files.
io = {
'FilteredProcessFormatter': FilteredProcessFormatter,
'ProcessFormatter': ProcessFormatter,
'eval_psdiff_conf': eval_psdiff_conf,
'eval_psdiff_d': eval_psdiff_d,
}
exec(source, io)
return {
'LocalFilteredProcessFormatter': io['LocalFilteredProcessFormatter']}
def get_formatter_class():
for path in ('/usr/local/etc/psdiff.conf', '/etc/psdiff.conf'):
# First check, and then open without exception handling. That way we
# see if anything is wrong with permissions and such.
if os.path.exists(path):
return eval_psdiff_conf(path)['LocalFilteredProcessFormatter']
# No psdiff.conf? Check for psdiff.d.
for path in ('/usr/local/etc/psdiff.d', '/etc/psdiff.d'):
if os.path.exists(path):
# Mere existence of the path is enough for us to use that: if you
# create an empty /usr/local/etc/psdiff.d, then /etc/psdiff.d will
# NOT be used.
# Don't forget the 'object' in ProcessFormatterMixin(object) for
# python2.
mixins = eval_psdiff_d(path)['LocalProcessFormatterMixins']
class_ = type(
'LocalFilteredProcessFormatter',
tuple(mixins + [FilteredProcessFormatter]),
{})
return class_
# Nothing found? Return the plain unaltered version.
return FilteredProcessFormatter
def get_new_processes(formatter_class, with_network=False):
root = ps_faxu(with_network=with_network)
formatter = formatter_class(root)
return formatter.to_processes()
def show_diff(changes, missing=True, extra=True):
has_diff = False
for item in group_process_changes(changes):
if item[0] == 'single':
_, direction, process = item
if direction < 0 and missing:
show_diff_process('-', process)
has_diff = True
elif direction > 0 and extra:
show_diff_process('+', process)
has_diff = True
else:
_, old, new = item
if show_diff_processes(old, new, missing, extra):
has_diff = True
return has_diff
def print_line(line):
# NOTE: We never print() with u'' below, because in py2 it would
# "guess" the encoding of the recipient (tty) instead of choosing
# utf-8.
if isinstance('', bytes): # py2
line = line.encode('utf-8', 'replace')
print(line)
def show_diff_process(prefix, process):
"""
Print a process, prefixed with '-', '+' or ' '.
A process with listen info gets a line per listen address:
-/usr/sbin/named {user=bind, listen=(
- tcp:0.0.0.0:53,
- udp:0.0.0.0:53,
-)}
so that show_diff_processes() can mark only the addresses that
changed.
"""
indent, head, items, tail = process.to_diff_lines()
print_line(u'{}{}{}'.format(prefix, indent, head))
for item in items:
print_line(u'{}{} {},'.format(prefix, indent, item))
if items:
print_line(u'{}{}{}'.format(prefix, indent, tail))
def show_diff_processes(old, new, missing, extra):
"""
Diff two same-process items -- same cmdline/user, different listen
addresses -- by listen address.
The process itself and the closing ')}' are shown as context; only
the changed addresses get a '-' or '+' prefix.
"""
shown = [
(direction, item)
for direction, item in diff_items(old.listen, new.listen) if (
direction == 0
or (direction < 0 and missing)
or (direction > 0 and extra))]
if not any(direction for direction, item in shown):
return False
# One of the two may have no listen info at all; take the framing
# from the one that has (they are the same process otherwise).
indent, head, _, tail = (old if old.listen else new).to_diff_lines()
print_line(u' {}{}'.format(indent, head))
prefixes = {0: ' ', -1: '-', 1: '+'}
for direction, item in shown:
print_line(u'{}{} {},'.format(prefixes[direction], indent, item))
print_line(u' {}{}'.format(indent, tail))
return True
def manual_parent(processes, parent_cmdline):
"""
Return the (index, process) that manual add/remove works below.
"""
for index, process in enumerate(processes):