python案例1

需求

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

分析

将整个处理过程分为两步
1、linux上~/.bash_history文件记录着用户的历史命令,读取后输出到文件即可
2、/etc/passwd记录着所有用户及其用户目录,遍历即可

实现

准备工作

验证python环境

1、输出python版本号,说明具有python环境

1
#python -V

2、创建history.py文件
print(‘helo’)

3、运行该脚本

1
#python history.py

输出helo说明运行正常

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

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

1
2
3
4
5
6
7
8
9
10
11
12
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)

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

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

1
2
3
4
5
6
7
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);

总结

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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)