本文将对Python监测主机行为进行详细阐述,从多个方面探讨其实现方法和应用场景。
一、监测主机网页访问
1、使用Python的requests库发送GET或POST请求,通过监测响应内容来判断主机是否正常访问网页。
import requests
url = "http://www.example.com"
response = requests.get(url)
if response.status_code == 200:
print("主机正常访问网页")
else:
print("主机无法访问网页")
2、通过解析日志文件,筛选出主机的网页访问记录,进一步分析主机的使用情况。
import re
log_file = "/var/log/apache/access.log"
with open(log_file, "r") as f:
for line in f:
# 使用正则表达式匹配出网页访问记录
match = re.search(r'GET /(.*?) HTTP', line)
if match:
page = match.group(1)
print("访问了网页:" + page)
二、监测主机文件操作
1、使用Python的os模块进行文件操作,如判断文件是否存在、获取文件属性等。
import os
file_path = "/path/to/file.txt"
if os.path.exists(file_path):
print("文件存在")
else:
print("文件不存在")
file_size = os.path.getsize(file_path)
print("文件大小:" + str(file_size) + " bytes")
2、通过监测文件的创建、修改时间来分析主机的文件操作情况。
import os
import time
file_path = "/path/to/file.txt"
last_modified = os.path.getmtime(file_path)
last_modified_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(last_modified))
print("文件最后修改时间:", last_modified_time)
三、监测主机进程活动
1、使用Python的psutil库来监测主机的进程活动情况,如获取进程列表、进程CPU使用率等。
import psutil
process_list = psutil.process_iter()
for process in process_list:
print("进程名:", process.name())
print("进程ID:", process.pid)
print("CPU使用率:", process.cpu_percent())
2、结合使用os模块和psutil库,可以监测并分析主机中特定进程的运行情况。
import os
import psutil
def get_process_status(process_name):
for process in psutil.process_iter():
if process.name() == process_name:
print("进程名:", process.name())
print("进程ID:", process.pid)
get_process_status("python.exe")
四、监测主机网络连接
1、使用Python的socket库进行主机的网络连接监测,如ping测试。
import socket
def ping(host):
try:
socket.gethostbyname(host)
print("主机可以PING通")
except socket.error:
print("主机无法PING通")
ping("www.example.com")
2、通过监测主机的网络连接状态,可以进一步分析主机的网络质量和稳定性。
import subprocess
def check_network_connection():
result = subprocess.call(["ping", "-c", "1", "www.example.com"])
if result == 0:
print("主机网络连接正常")
else:
print("主机网络连接不正常")
check_network_connection()
五、监测主机系统资源
1、使用Python的psutil库来监测主机的CPU、内存、磁盘等系统资源情况。
import psutil
cpu_usage = psutil.cpu_percent()
print("CPU使用率:", cpu_usage)
memory_usage = psutil.virtual_memory().percent
print("内存使用率:", memory_usage)
disk_usage = psutil.disk_usage("/").percent
print("磁盘使用率:", disk_usage)
2、结合使用os模块和psutil库,可以监测主机的系统负载情况。
import os
import psutil
load_avg = os.getloadavg()
print("1分钟内系统负载:", load_avg[0])
print("5分钟内系统负载:", load_avg[1])
print("15分钟内系统负载:", load_avg[2])
六、监测主机安全行为
1、使用Python的logging库记录主机的安全行为日志,如登录日志、访问控制等。
import logging
logging.basicConfig(filename='security.log', level=logging.INFO)
def login(username, password):
# 登录验证逻辑
if username == "admin" and password == "123456":
logging.info("用户{}登录成功".format(username))
return True
else:
logging.warning("用户{}登录失败".format(username))
return False
login("admin", "123456")
2、通过分析安全行为日志,可以监测并预防主机的安全威胁。
import re
log_file = "security.log"
with open(log_file, "r") as f:
for line in f:
# 使用正则表达式匹配出登录失败记录
match = re.search(r'登录失败', line)
if match:
print("检测到登录失败记录:" + line)
通过以上方法,我们可以利用Python对主机的行为进行监测和分析,进而对主机的使用情况、安全性等进行评估和优化。