-
Notifications
You must be signed in to change notification settings - Fork 3
/
lsdisks
executable file
·90 lines (73 loc) · 2.5 KB
/
lsdisks
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
#! /usr/bin/env python
import logging
import os
import os.path
import sys
## auxiliary functions
try:
from collections import defaultdict
except ImportError:
class defaultdict(dict):
"""
A backport of `defaultdict` to Python 2.4
See http://docs.python.org/library/collections.html
>>> dl = defaultdict(list)
>>> dl['emptylist']
[]
>>> di = defaultdict(int)
>>> di['zero']
0
>>> ds = defaultdict(str)
>>> ds['empty']
''
"""
def __new__(cls, default_factory=None):
return dict.__new__(cls)
def __init__(self, default_factory):
self.default_factory = default_factory
def __missing__(self, key):
try:
return self.default_factory()
except:
raise KeyError("Key '%s' not in dictionary" % key)
def __getitem__(self, key):
if not dict.__contains__(self, key):
dict.__setitem__(self, key, self.__missing__(key))
return dict.__getitem__(self, key)
## main
from optparse import OptionParser
def main():
parser = OptionParser(
version="%prog 1.0",
usage="""Usage: %prog [options]
Print a table with Linux disk device name, serial number /
manufacturer ID, UUID and PCI bus address of all attached disk
devices.
""")
parser.add_option("-s", "--short",
action="store_true",
dest="short",
default=False,
help="Only print disk device name and serial number.")
(options, args) = parser.parse_args()
# gather disk information from the `/dev/` filesystem
disks = defaultdict(lambda: defaultdict(lambda: ''))
widths = defaultdict(lambda: 0)
if options.short:
columns = ["id"]
else:
columns = ["id", "uuid", "label", "path"]
for col in columns:
devdir = ("/dev/disk/by-%s" % col)
devnames = os.listdir(devdir)
for devname in devnames:
disk = os.path.basename(os.readlink(os.path.join(devdir, devname)))
devname = devname.replace(r'\x2f', '/')
disks[disk][col] = devname
widths[col] = max(widths[col], len(devname))
# print disk information
fmt = "%-6s" + str.join(" ", [("%%-%ds" % widths[col]) for col in columns])
for disk in disks:
print (fmt % tuple([ disk ] + [ disks[disk][col] for col in columns]))
if __name__ == '__main__':
main()