Ubuntu RAMメモリダンプ

Ubuntu RAMメモリダンプ

LIME、AVMLなどのツールを使用せずにpyhtonスクリプトを使用してUbuntuシステムのメモリダンプを取得したいと思います。 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構造(論理ページがどのファイルにマップされるか)だけである場合は、この方法が便利です。

おすすめ記事