python案例-将linux服务器上的所有用户执行的历史命令输出到文件
需求
将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)