linux定时 top、netstat 输出到文件

正确的终端命令:

top -n 1 -b > ~/Desktop/top.txt
netstat -antlp

脚本调用终端命令

import subprocess
import datetime
p = subprocess.Popen(
    'top -n 1 -b > ~/Desktop/top/{}.txt'.format(datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S')),
    shell=True,
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT
)
p = subprocess.Popen(
    '''netstat -antlp''',
    shell=True,
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT
)
# print(p.stdout.readlines()) 
# 输出到文件时,不要print,否则,文件里面就没有了
with open('/home/liang/Desktop/netstat/{}.txt'.format(datetime.datetime.now().strftime('%Y-%m-%d_%H:%M:%S')), 'wb') as f:
    f.writelines(p.stdout.readlines())

crontab定时执行脚本

crontab -e 打开 crontab 的编辑页面
i进入编辑模式
最下面加上

*/1 * * * * /home/liang/miniconda3/envs/draw3.9/bin/python /home/liang/PycharmProjects/my_script/a7.py

你可能感兴趣的:(python,后端,linux,python,运维,top,netstat)