Me gustaría un programa o más preferiblemente una forma de registrar el uso del disco.
Para explicar lo que quiero decir, cuando alguien instala Ubuntu, se utilizan aproximadamente 4,5 GB de disco. Luego, cuando instala/desinstala programas, este uso aumenta o disminuye.
Lo que quiero es una forma de registrar automáticamente el disco actual que se usa en un archivo txt cuando hay un cambio (algo está instalado/guardado o desinstalado/eliminado) con la hora y la fecha en que ocurrió este cambio.
Respuesta aceptada:
Usando el df
comando para realizar un seguimiento del espacio en disco, y el lsblk
comando para realizar un seguimiento de las unidades montadas, el siguiente script, ejecutado en segundo plano, registrará los cambios en el espacio libre de todas las unidades montadas. Crea un archivo de registro:~/disklog
donde escribe los cambios (en k
).
Si lo ejecuta en la terminal, generará el resultado simultáneamente.
El contenido del archivo de registro se parece a:
[mountpoint / change / date/time / used]
/ . . . . . . . . . . . . . . . . . . 36 k Fri Mar 27 08:17:30 2015 used 87989352 k
/media/intern_2 . . . . . . . . . . . -1792 k Fri Mar 27 08:17:32 2015 used 562649592 k
/ . . . . . . . . . . . . . . . . . . -4 k Fri Mar 27 08:17:39 2015 used 87989356 k
/ . . . . . . . . . . . . . . . . . . -36 k Fri Mar 27 08:17:43 2015 used 87989392 k
/ . . . . . . . . . . . . . . . . . . -4 k Fri Mar 27 08:17:55 2015 used 87989396 k
/ . . . . . . . . . . . . . . . . . . 4 k Fri Mar 27 08:18:11 2015 used 87989392 k
/ . . . . . . . . . . . . . . . . . . -32 k Fri Mar 27 08:18:13 2015 used 87989424 k
Cómo usar
- Copie el siguiente script en un archivo vacío, guárdelo como
log_diskusage.py
-
En la sección principal del script, establezca el intervalo de tiempo, el umbral y el número máximo de líneas en el archivo de registro:
#--- set time interval in seconds, threshold in k, and the max number of lines in the logfile interval = 20 # the interval between the checks threshold = 0 # in K, you'd probably set this higher max_lines = 5000 # if you want no limit, comment out the line line_limit() in the script #---
- El
interval
para ejecutar las comprobaciones de espacio en disco, tal como está, 20 segundos - El
treshold
:probablemente no desee llevar un registro de todos los cambios (muy) pequeños, ya que el disco tiene muchos de pequeños cambios en el espacio libre en disco. Tal como está, está configurado en10k
- Las
max_lines
, ya que el archivo de registro crecerá rápidamente, especialmente si establece el umbral en cero
- El
-
Pruebe el script con el comando:
python3 /path/to/log_diskusage.py
-
Si todo funciona bien, agréguelo a sus Aplicaciones de inicio:Dash> Aplicaciones de inicio> Agregar.
El guión
#!/usr/bin/env python3
import subprocess
import os
import time
log = os.environ["HOME"]+"/disklog.txt"
#--- set time interval in seconds, threshold in k
interval = 1
threshold = 0
max_lines = 5000
#---
def line_limit():
lines = open(log).readlines()
if len(lines) > max_lines:
with open(log, "wt") as limit:
for l in lines[-max_lines:]:
limit.write(l)
get = lambda cmd: subprocess.check_output([cmd]).decode("utf-8")
def disk_change():
mounted = [l[l.find("/"):] for l in get("lsblk").splitlines() if "/" in l]
data = get("df").splitlines()
matches = [("/", data[1].split()[-4])]
for l in mounted:
if l != "/":
match = [(l, d.replace(l, "").split()[-3]) for d in data if l in d][0]
matches.append(match)
return matches
disk_data1 = disk_change()
while True:
time.sleep(interval)
disk_data2 = disk_change()
for latest in disk_data2:
try:
compare = [(latest[0], int(latest[1]), int(item[1])) for item in disk_data1 if latest[0] == item[0]][0]
if not compare[1] == compare[2]:
diff = compare[2]-compare[1]
if abs(diff) > threshold:
with open(log, "a") as logfile:
drive = compare[0]; lt = 18-int((len(drive)/2)); lk = 14-len(str(diff))
s = drive+" ."*lt+lk*" "+str(diff)+" k \t"+str(time.strftime("%c"))+"\t"+"used "+str(compare[1])+" k\n"
logfile.write(s)
print(s, end = "")
# if you don't want to set a limit to the max number of lines, comment out the line below
line_limit()
except IndexError:
pass
disk_data1 = disk_data2