非交互式使用 parted

parted 跟 fdiks 类似,默认都是交互式的来划分硬盘,现在需要非交互式的来自动划分硬盘。

最直接的方式是在使用 parted 时,加上一个 -s 参数,这样就可以避免手工干预了,下面这个是划分一个 3T 的硬盘,使用 gpt 方式的分区表,将整个硬盘分为一个区:

$ sudo parted -s /dev/sdb mklable gpt
$ sudo parted  -s /dev/sdb mkpart  data 0 2998961MB
$ sudo mkfs.ext4 /dev/sdb1
$ mkdir /data;mount /dev/sdb1 /data

注意:使用 gpt 的方式没有主分区,扩展(逻辑)分区的说法。

还有一个方式是使用 expect,首先在交互式的方式下是这样进行分区的:

$ sudo parted  /dev/sdb
GNU Parted 2.2
Using /dev/sdb
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) mklabel gpt
Warning: The existing disk label on /dev/sdb will be destroyed and all data on this disk will be lost. Do you want to continue?
Yes/No? Yes
(parted) mkpart data
File system type?  [ext2]? ext4
Start? 0
End? -1
Warning: The resulting partition is not properly aligned for best performance.
Ignore/Cancel? I
(parted) quit
Information: You may need to update /etc/fstab.                          

$ sudo  mkfs.ext4 /dev/sdb1
mke2fs 1.41.11 (14-Mar-2010)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
Stride=0 blocks, Stripe width=0 blocks
183042048 inodes, 732168183 blocks
36608409 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=4294967296
22344 block groups
32768 blocks per group, 32768 fragments per group
8192 inodes per group
Superblock backups stored on blocks:
    32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,
    4096000, 7962624, 11239424, 20480000, 23887872, 71663616, 78675968,
    102400000, 214990848, 512000000, 550731776, 644972544

Writing inode tables: done
Creating journal (32768 blocks): done
Writing superblocks and filesystem accounting information: done

This filesystem will be automatically checked every 22 mounts or
180 days, whichever comes first.  Use tune2fs -c or -i to override.

接下来使用 expect 方式实现:

$ tree
.
|– main.sh
|– mkfs.sh
`– parted.sh

0 directories, 3 files

$ cat main.sh
#!/bin/sh

dev=$1

expect ./parted.sh $dev
./fs.sh ${dev}

$ cat parted.sh
#!/usr/bin/expect -f

set dev  [ lindex $argv 0 ]
set timeout -1

spawn parted $dev

expect {
        "*parted*" {
               send — "mklabel gpt\r"
                    expect {
                            "Warning*" {send — "Y\r"}
                                 }   
                    }   
}

expect — "*parted*"
send — "mkpart data\r"

expect — "*ext2*"
send — "ext4\r"
   
expect — "*Start"
send — "0\r"
   
expect — "*End*"
send — "-1\r"

expect — "*Ignore*"
send — "I\r"

expect — "*parted*"
send — "quit\r"

expect eof

$ cat mkfs.sh
#!/bin/sh

dev=$1

mkdir /data
mkfs.ext4 ${dev}1
echo ${dev}1 /data ext4 defaults 0 2 >> /etc/fstab
mount -a

参考:
http://www.gnu.org/s/parted/manual/html_node/mkpart.html#mkpart