使用expect实现fdisk /dev/sdb 免交互创建分区,要求一次性创建一个20G/dev/sdb1的普通分区和一个4G/dev/sdb的swap分区和一个逻辑分区10G /dev/sdb5
时间: 2023-09-08 09:11:47 浏览: 43
可以使用expect脚本实现免交互创建分区,具体实现如下:
```expect
#!/usr/bin/expect
set timeout 5
spawn fdisk /dev/sdb
expect "Command (m for help):"
send "n\r"
expect "Select (default p):"
send "p\r"
expect "Partition number (2-4, default 2):"
send "1\r"
expect "First sector (2048-41943039, default 2048):"
send "\r"
expect "Last sector, +/-sectors or +/-size{K,M,G,T,P} (2048-41943039, default 41943039):"
send "+20G\r"
expect "Command (m for help):"
send "n\r"
expect "Select (default p):"
send "p\r"
expect "Partition number (2-4, default 2):"
send "2\r"
expect "First sector (41943040-41943039, default 41943040):"
send "\r"
expect "Last sector, +/-sectors or +/-size{K,M,G,T,P} (41943040-41943039, default 41943039):"
send "+4G\r"
expect "Command (m for help):"
send "n\r"
expect "Select (default p):"
send "e\r"
expect "Partition number (2-4, default 2):"
send "\r"
expect "First sector (8392704-41943039, default 8392704):"
send "\r"
expect "Last sector, +/-sectors or +/-size{K,M,G,T,P} (8392704-41943039, default 41943039):"
send "+10G\r"
expect "Command (m for help):"
send "t\r"
expect "Partition number (1-5):"
send "2\r"
expect "Hex code (type L to list all codes):"
send "82\r"
expect "Command (m for help):"
send "w\r"
expect eof
```
脚本中,使用spawn命令启动fdisk命令,并使用expect命令匹配fdisk命令的交互提示,并发送对应的输入,以达到自动创建分区的目的。其中,"+20G"、"+4G"和"+10G"分别表示创建20G、4G和10G大小的分区。最后,使用expect命令匹配fdisk命令的结束符,结束交互。