delete root partition in python

python, filesystem, partitioning, operating-system, root

main.py

To delete the root partition of a system in Python, you can use the `os` module to execute system commands.

Here's an example that uses `subprocess.Popen` to execute the `fdisk` command with the `-l` option to get information about the disk partitions, and then uses `subprocess.Popen` again to execute the `fdisk` command with the `-w` option to save the changes made to the partition table.

```python
import subprocess

def delete_root_partition():
    # Get the list of disk partitions
    p = subprocess.Popen('fdisk -l', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = p.communicate()

    # Find the root partition (usually /dev/sda1 or /dev/nvme0n1p1)
    for line in out.decode().split('\n'):
        if line.startswith('/dev/') and 'Linux' in line:
            root_partition = line.split()[0]
            break
    else:
        print('Could not find root partition')
        return

    # Delete the root partition
    p = subprocess.Popen(f'fdisk {root_partition}', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
    p.stdin.write(b'd\nw\n')
    p.stdin.flush()
    out, err = p.communicate()

    # Print the output
    print(out.decode())
    print(err.decode())
1243 chars
32 lines

Note that this code should be executed with elevated privileges, such as by using sudo python script.py. It also assumes that there is only one Linux partition on the disk, which may not be the case for more complex partitioning schemes.

related categories

gistlibby LogSnag