-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiskmanagerAPI.py
414 lines (352 loc) · 13.8 KB
/
diskmanagerAPI.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
import os
import subprocess
import re
class Check_external_devices:
"""
Module Check_external_devices
Give detailed information about external drives.
"""
def list_media_devices(self):
"""
List of all attached drives.
"""
with open("/proc/partitions", "r") as f:
devices = []
for line in f.readlines()[2:]: # skip header lines
words = [ word.strip() for word in line.split() ]
minor_number = int(words[1])
device_name = words[3]
if (minor_number % 16) == 0:
path = "/sys/class/block/" + device_name
if os.path.islink(path):
if os.path.realpath(path).find("/usb") > 0:
devices.append("/dev/" + device_name)
return devices
def list_files(self,root, indent=1):
"""
List of files in drives.
`root` Root path
`indent` For giving space(default=1)
"""
for filename in os.listdir(root):
path = os.path.join(root, filename)
if os.path.isfile(path):
print("-" * indent, filename)
elif os.path.isdir(path):
print("+" * indent, filename)
self.list_files(path, indent + 1)
def get_device_name(self,device):
"""
Gives name of the device
`device` Device name
"""
return os.path.basename(device)
def get_device_block_path(self,device):
"""
Gives block path of the device
`device` Device name
"""
return "/sys/block/%s" % self.get_device_name(device)
def get_media_path(self,device):
"""
Gives path of the device
`device` Device name
"""
return "/media/" + self.get_device_name(device)
def get_partition(self,device):
"""
Shows all partitions
`device` Device name
"""
os.system("sudo fdisk -l %s > output" % device)
with open("output", "r") as f:
data = f.read()
return data.split("\n")[-2].split()[0].strip()
def is_mounted(self,device):
"""
Check whether device is mounted or not
`device` Device name
"""
return os.path.ismount(self.get_media_path(device))
def mount_partition(self,partition, name="usb"):
"""
For mounting the device
`name` Device name(default=usb)
"""
path = self.get_media_path(name)
if not self.is_mounted(path):
os.system("mkdir -p " + path)
os.system("mount %s %s" % (partition, path))
def unmount_partition(self,name="usb"):
"""
For unmounting the device
`name` Device name(default=usb)
"""
path = self.get_media_path(name)
if self.is_mounted(path):
os.system("umount " + path)
def mount(self,device, name=None):
"""
For mounting the device
`device` Device name
'name' Variable which will be assigned by variable 'device'(default=None)
"""
if not name:
name = self.get_device_name(device)
self.mount_partition(self.get_partition(device), name)
def unmount(self,device, name=None):
"""
For unmounting the device
`device` Device name
'name' Variable which will be assigned by variable 'device'(default=None)
"""
if not name:
name = self.get_device_name(device)
self.unmount_partition(name)
def is_removable(self,device):
"""
Check whether drive is remoable or not
`device` Device name
"""
path = self.get_device_block_path(device) + "/removable"
if os.path.exists(path):
with open(path, "r") as f:
return f.read().strip() == "1"
return None
def get_size(self,device):
"""
Shows size of the drive
`device` Device name
"""
path = self.get_device_block_path(device) + "/size"
if os.path.exists(path):
with open(path, "r") as f:
return int(f.read().strip()) * 512
return -1
def get_model(self,device):
"""
Shows model of the drive
`device` Device name
"""
path = self.get_device_block_path(device) + "/device/model"
if os.path.exists(path):
with open(path, "r") as f:
return f.read().strip()
return None
def get_vendor(self,device):
"""
Shows vendor name of the device
`device` Device name
"""
path = self.get_device_block_path(device) + "/device/vendor"
if os.path.exists(path):
with open(path, "r") as f:
return f.read().strip()
return None
def get_values(self):
"""
TO display all values
"""
devices = self.list_media_devices()
deviceList={}
deviceFinal=[]
for device in devices:
deviceList["drive"]=self.get_device_name(device)
deviceList["mounted"]="Yes" if self.is_mounted(device) else "No"
deviceList["removable"]="Yes" if self.is_removable(device) else "No"
deviceList["size(GB)"]= "%.2f" % (self.get_size(device) / 1024 ** 3)
deviceList["model"]=self.get_model(device)
deviceList["vendor"]=self.get_vendor(device)
deviceFinal.append(deviceList.copy())
return deviceFinal
class Delete_partition:
"""
Module `Delete_partition`
Use to delte any partition
"""
def delete(self,drive_name,command,part_number=None):
"""
For deleting any partition.
"""
if command=="Delete":
partitions=subprocess.Popen(["sudo","fdisk","{}".format(drive_name)],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
output=partitions.communicate(b"d")[0].decode()
print(output)
if part_number:
partitions=subprocess.Popen(["sudo","fdisk","{}".format(drive_name)],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
msg="d\n{}\nw".format(part_number)
encoded_msg = msg.encode('utf-8')
output=partitions.communicate(encoded_msg)[0].decode()
print(output)
# drives={}
# drivesList=[]
# with open("/proc/partitions", "r") as f:
# for line in f.readlines()[2:]:
# split = re.split('[\s]+',line)
# if split[0]=='':
# del split[0]
# drives["major"]=split[0]
# drives["minor"]=split[1]
# drives["block"]=split[2]
# drives["namee"]=split[3]
# drivesList.append(drives.copy())
# print(drivesList)
# drive_name=input("enter drive name:")
# minor_number=input("enter minor_number:")
# os.system("sudo parted "+drive_name+" rm "+minor_number)
class Display_partition:
"""
Module `Display_partition`
Display all internal partitions of the main Harddrive
"""
def __init__(self):
self.commandList=[]
self.newCommand={}
self.split=" "
commands= os.popen ("sudo parted -l").read().strip().splitlines()[1:2]
for command in commands:
self.split= re.split('[\s]+',command)
self.split=self.split[1][:-1]
print(self.split)
def get_partition(self):
"""
Display all partitions present in internal drive.
"""
commandList=[]
newCommand={}
commands= os.popen ("sudo fdisk -l {}".format(self.split)).read().strip().splitlines()[8:]
for command in commands:
if not command:
continue
split = re.split('[\s]+',command)
if split[0]=='':
del split[0]
newCommand["device"]=split[0]
newCommand["start"]=split[1]
newCommand["end"]=split[2]
newCommand["sectors"]=split[3]
newCommand["size"]=split[4]
newCommand["type"]=split[5]
commandList.append(newCommand.copy())
return commandList
def create_partition(self,drive_name,command,part_command=None,part_number=None,first=None,last=None):
"""
Create_Partition is used to resize partition available in harddrive
"""
partList=[]
partDic={}
if command=="Display":
partitions=subprocess.Popen(["sudo","fdisk","{}".format(drive_name)],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
output=partitions.communicate(b"p")[0].decode()
print(output)
elif command=="Make" and part_command=="Extended":
partitions=subprocess.Popen(["sudo","fdisk","{}".format(drive_name)],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
msg="n\ne\n{}\n".format(part_number)
encoded_msg = msg.encode('utf-8')
output=partitions.communicate(encoded_msg)[0].decode()
print(output)
if first:
partitions=subprocess.Popen(["sudo","fdisk","{}".format(drive_name)],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
msg=msg+str(first)
encoded_msg = msg.encode('utf-8')
output=partitions.communicate(encoded_msg)[0].decode()
print(output)
if last:
partitions=subprocess.Popen(["sudo","fdisk","{}".format(drive_name)],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
msg=msg+str(first)+"\n"+last+"\nw"
encoded_msg = msg.encode('utf-8')
output=partitions.communicate(encoded_msg)[0].decode()
print(output)
else:
print("Error: enter LAst value..")
else:
print("Error: enter First value..")
elif command=="Make" and part_command=="Primary":
partitions=subprocess.Popen(["sudo","fdisk","{}".format(drive_name)],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
msg="n\np\n{}\n".format(part_number)
encoded_msg = msg.encode('utf-8')
output=partitions.communicate(encoded_msg)[0].decode()
print(output)
if first:
partitions=subprocess.Popen(["sudo","fdisk","{}".format(drive_name)],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
msg=msg+str(first)
encoded_msg = msg.encode('utf-8')
output=partitions.communicate(encoded_msg)[0].decode()
print(output)
if last:
partitions=subprocess.Popen(["sudo","fdisk","{}".format(drive_name)],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
msg=msg+str(first)+"\n"+last+"\nw"
encoded_msg = msg.encode('utf-8')
output=partitions.communicate(encoded_msg)[0].decode()
print(output)
else:
print("Error: enter LAst value..")
else:
print("Error: enter First value..")
class Repair_filesystem:
"""
Module `Repair_filesystem`
Use to repair filesystem of devices
"""
def repair(self):
"""
Use to repair filesystem.
"""
cmdList=[]
cmdDic={}
commands=os.popen("lsblk").read().strip().splitlines()
for command in commands:
split = re.split('[\s]+',command)
if split[0]=='':
del split[0]
cmdDic["name"]=split[0]
cmdDic["maj:min"]=split[1]
cmdDic["rm"]=split[2]
cmdDic["size"]=split[3]
cmdList.append(cmdDic.copy())
print(cmdList)
drive_name=input("enter drive name:")
fsckDic={}
umountDic={}
resultDic={}
mountDic={}
umnt=os.popen("sudo umount "+drive_name).read().strip().splitlines()
for word in umnt:
umountDic["output"]=word
print(umountDic)
cmd=os.popen("sudo fsck "+drive_name).read().strip().splitlines()
for line in cmd:
fsckDic["output"]=line
print(fsckDic)
result=os.popen("echo $?").read().strip().splitlines()
for ans in result:
resultDic["output"]=ans
print(resultDic)
if result==0:
print("No errors")
mnt=os.popen("sudo mount "+drive_name).read().strip().splitlines()
for word in mnt:
mountDic["output"]=word
print(mountDic)
else:
mountDic["output"]="{} errors were there".format(result)
print(mountDic)
class Partition_image:
"""
Module `Partition_image`
Use to create and restore partition image of the drive
"""
def create_image(self):
"""
To create partition image of th disk
"""
drive=input("drive name:")
path=input("enter path:")
os.system("sudo dd if={} conv=sync,noerror bs=64K | gzip -c > {}".format(drive,path))
def restore_image(self):
"""
To restore partition image of th disk
"""
drive=input("drive name:")
path=input("enter path:")
os.system(" gunzip -c {} | dd of={}".format(path,drive))