You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在RHEL服务器中通过Bash/Python3脚本自动化创建磁盘分区

Absolutely, you can automate this partitioning process without relying on expect—both parted and fdisk offer non-interactive modes that work perfectly in Bash scripts. Here are two reliable approaches tailored to your needs:

1. Using parted with Script Mode

parted has a --script flag that skips all interactive prompts, making it easy to automate. We’ll also use aligned starting points (1MiB instead of 0) to avoid the performance alignment warning you saw manually.

Here’s a Bash script that partitions sdf, sdg, and sdh each with two 10GiB primary partitions:

#!/bin/bash

# Define the list of disks to process
TARGET_DISKS=("sdf" "sdg" "sdh")

for disk in "${TARGET_DISKS[@]}"; do
    echo "Starting partition setup for /dev/$disk..."
    
    # Create an MS-DOS partition table
    parted --script /dev/$disk mklabel msdos
    
    # First primary partition: 1MiB to 10GiB (~10GB)
    parted --script /dev/$disk mkpart primary 1MiB 10GiB
    
    # Second primary partition: 10GiB to 20GiB (~another 10GB)
    parted --script /dev/$disk mkpart primary 10GiB 20GiB
    
    # Refresh the partition table so the system recognizes new partitions
    partprobe /dev/$disk
    
    echo "Completed partitioning for /dev/$disk"
done

2. Using fdisk with Piped Commands

If you prefer fdisk, you can pipe a sequence of commands to it directly. This method also avoids interactive prompts and handles alignment automatically.

Here’s the equivalent script using fdisk:

#!/bin/bash

TARGET_DISKS=("sdf" "sdg" "sdh")

for disk in "${TARGET_DISKS[@]}"; do
    echo "Setting up partitions on /dev/$disk with fdisk..."
    
    # Pipe commands to fdisk:
    # o = create new DOS partition table
    # n = new partition, p = primary, 1 = number, default start, +10G = end
    # Repeat for second partition (number 2)
    # w = write changes to disk
    echo -e "o\nn\np\n1\n\n+10G\nn\np\n2\n\n+10G\nw" | fdisk /dev/$disk
    
    # Refresh partition table
    partprobe /dev/$disk
    
    echo "Done with /dev/$disk"
done

Notes:

  • Both scripts will create two ~10GB primary partitions on each target disk, matching your manual example.
  • partprobe ensures the system detects the new partitions immediately without needing a reboot.
  • After running the script, you can verify the result with lsblk—you’ll see the sdf1, sdf2, etc., partitions as expected.

内容的提问来源于stack exchange,提问作者Judy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 18:57:46