Ubuntu RAM 内存转储

Ubuntu RAM 内存转储

我想使用 pyhton 脚本获取 ubuntu 机器的内存转储,而不使用 LIME、AVML 等工具。我想使用像 gcore 这样的 linux 内置命令。创建所有 RAM 进程的内存转储后,我想将这些内存转储二进制文件的内容读取为人类可读文件。我尝试使用循环设备来挂载这些文件,但显示此错误“挂载:/mnt:错误的 fs 类型、错误的选项、/dev/loop0 上的错误超级块、缺少代码页或帮助程序或其他错误。”下面是我用于获取内存转储的代码:

import subprocess
import os import csv from getpass import getpass
# Check current value of ptrace_scope
result = subprocess.run(['cat', '/proc/sys/kernel/yama/ptrace_scope'], stdout=subprocess.PIPE, text=True) print("Current value of ptrace_scope:", result.stdout)
# If the value is 1 or 2, it means the ptrace_scope is restricted
if result.stdout.strip() in ['1', '2']:
Update ptrace_scope to 0 to allow tracing of all processes
subprocess.run(['sudo', 'tee', '/proc/sys/kernel/yama/ptrace_scope'], input='0', stdout=subprocess.PIPE, text=True)
print("ptrace_scope has been updated to allow tracing of all processes.")
else: print("ptrace_scope is already allowing tracing of all processes.")
try:
Prompt for password to run sudo command
password = input("Enter your password: ")
Use the -S option to read the password from standard input
# Pass the password to sudo command using echo
subprocess.run(['echo', password, '|', 'sudo', '-S', 'chmod', '-R', '777', '/home/memory_dump'], check=True, shell=True) print("File permissions have been updated successfully.") except subprocess.CalledProcessError as e: print(f"Failed to update file permissions. Error: {e}")
def memory_dump(pids, core_dump_dir, password):
Create core dumps for processes with specified PIDs.
# Loop through the PIDs and take core dumps
# Execute ps aux command and capture the output
# Print the list of PIDs
for pid in pids: try:
Execute gcore command to take core dump
subprocess.run(['sudo', '-S', 'gcore', '-o', core_dump_dir, str(pid)], input=password.encode(), check=True) print(f"Core dump for PID {pid} has been successfully created.") except subprocess.CalledProcessError as e: print(f"Failed to create core dump for PID {pid}. Error: {e}")
# Prompt the user to enter the password
password = getpass("Enter your password: ")
# User-specified path to save the CSV file
csv_path = input("Enter the path to save the CSV file (e.g. /path/to/save/): ")
Prompt the user for a filename
filename = input("Enter the filename for the CSV file (e.g. processes.csv): ")
# Join the user-specified path and filename to create the full file path
csv_file_path = os.path.join(csv_path, filename)
# List of PIDs for which core dumps are to be taken
Execute ps aux command and capture the output
ps_output = subprocess.check_output(['ps', 'aux']).decode('utf-8')
# Split the output into lines
ps_lines = ps_output.splitlines()
# Extract the PIDs and process names from the lines
processes = [] for line in ps_lines[1:]:
Skip the first line, which contains the column headers
# Split the line by whitespace
fields = line.split()
The PID is the second field (index 1)
pid = int(fields[1])
The process name is the last field (last element in the list)
process_name = fields[-1]
Add the PID and process name as a tuple to the list of processes
processes.append((pid, process_name))
# Print the list of PIDs and process names
print("List of PIDs and Process Names:") for process in processes: print("PID: {}, Process Name: {}".format(process[0], process[1]))
# Save the list of PIDs and process names to the user-specified CSV file
with open(csv_file_path, 'w', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerow(['PID', 'Process Name'])  # Write header row for process in processes: writer.writerow([process[0], process[1]])
Directory to store the core dumps
core_dump_dir = '/home/memory_dump'
Create the core dump directory if it doesn't exist
if not os.path.exists(core_dump_dir): os.makedirs(core_dump_dir)
# Get the list of PIDs from the processes list
pids = [process[0] for process in processes]
# Call the function to create core dumps
memory_dump(pids, core_dump_dir, password)

下面是我用于读取核心转储文件的代码:

import subprocess
import os import getpass
def coredump_mount(folder_path, destination_folder_path, sudo_password):
""" Mounts the contents of core dump files in a folder to a loop device and copies the files to a destination folder. """
# Check if the folder path is valid
if not os.path.exists(folder_path): print(f"Folder path {folder_path} does not exist!") exit(1)
# Check if the destination folder path is valid
if not os.path.exists(destination_folder_path): print(f"Destination folder path {destination_folder_path} does not exist!") exit(1)
# Loop through all the files in the folder
file_list = os.listdir(folder_path) for i in range(0, len(file_list), 5): group_files = file_list[i:i+5]
for filename in group_files:
Construct the file path by joining the folder path and the filename
file_path = os.path.join(folder_path, filename)
# Check if the file is a regular file and not a directory
if os.path.isfile(file_path):
Create a loop device with sudo and provide the password
subprocess.run(["sudo", "-S", "losetup", '--force', f"/dev/loop{i%5}", file_path], input=sudo_password, text=True)
# Mount the loop device to a mount point with sudo and provide the password
subprocess.run(["sudo", "-S", "mount", f"/dev/loop{i%5}", "/mnt"], input=sudo_password, text=True)
# Copy files from the loop device to the destination folder with sudo and provide the password
subprocess.run(["sudo", "-S", "cp", "-r", "/mnt/.", destination_folder_path], input=sudo_password, text=True)
# Unmount the loop device with sudo and provide the password
subprocess.run(["sudo", "-S", "mount", "-o", "rw", f"/dev/loop{i%5}", "/mnt"], input=sudo_password, text=True)
# Detach the loop device with sudo and provide the password
subprocess.run(["sudo", "-S", "losetup", "-f", file_path], input=sudo_password, text=True)
# Get folder path from user
folder_path = input("Please enter the folder path containing core dump files: ")
# Get destination folder path from user
destination_folder_path = input("Please enter the destination folder path: ")
# Get sudo password securely from the user
sudo_password = getpass.getpass("Please enter your sudo password: ")
# Call the function with user inputs
coredump_mount(folder_path, destination_folder_path, sudo_password)

读取核心转储代码时出现错误:

"mount: /mnt: wrong fs type, bad option, bad superblock on /dev/loop0, missing codepage or helper program, or other error."

答案1

/dev/loop不涉及内存。它使普通文件看起来像块设备,这对于文件系统映像和mount.

核心转储的结构与文件系统不同。那么就无法挂载了。

请注意,您可以使用 直接访问活动进程的内存/dev/nnn/mem,但/dev/nnn/maps如果您想要的只是内存的结构(哪些逻辑页映射到哪些文件),那么这会很方便。

相关内容