python案例-读取linux用history bash并生成日志文件

需求

将linux服务器上的所有用户执行的历史命令输出到文件

分析

1、linux上~/.bash_history文件记录着用户的历史命令,读取后输出到文件即可
2、/etc/passwd记录着所有用户及其用户目录,遍历即可

1.准备工作

1、验证python环境

#python -V

输出python版本号,说明具有python环境
2、创建history.py文件

print('helo')

3、运行该脚本

#python history.py

输出helo说明运行正常

2.功能实现:读取单个用户历史命令并输出到文件

输出root用户历史命令到/output/root.log文件

import os
user_name = 'root'
user_home = '/root'
bash_history_file_name = user_home+'/.bash_history'
        ## judge bash_history exists ??
        if(os.path.exists(bash_history_file_name)):
            ## read user bash history from userHome
            with open(bash_history_file_name, 'r') as sourceFile:
                history_datas = sourceFile.read()
                ## wirte bash history info to log file (name with userName)
                with open('/output/'+user_name+'.log', 'w') as outputFile:
                    outputFile.write(history_datas)

3.功能实现:读取所有用户目录

读取/etc/pwsswd并解析出用户名及用户路径

with open('/etc/passwd', 'r') as passwdFile:
    allLines = passwdFile.readlines();
    for line in allLines:
        userInfo = line.split(":")
        user_name = userInfo[0] ## get user_name
        user_home = userInfo[5] ## get user_home
        print(user_name+" "+user_home);

总结

读取所有用户的历史命令,并按照不同的用户,并输出到不同日志文件

import os

## read all user and bash home from passwd file
with open('/etc/passwd', 'r') as passwdFile:
    allLines = passwdFile.readlines();
    for line in allLines:
        userInfo = line.split(":")
        user_name = userInfo[0] ## get user_name
        user_home = userInfo[5] ## get user_home
        #print(user_name+" "+user_home);

        bash_history_file_name = user_home+'/.bash_history'
        ## judge bash_history exists ??
        if(os.path.exists(bash_history_file_name)):
            ## read user bash history from userHome
            with open(bash_history_file_name, 'r') as sourceFile:
                history_datas = sourceFile.read()
                ## wirte bash history info to log file (name with userName)
                with open('/output/'+user_name+'.log', 'w') as outputFile:
                    outputFile.write(history_datas)



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值