为Linux“adduser”命令创建Expect脚本

问题描述 投票:1回答:2

对于Expect来说,我是一个新手,我以为我会先在本地机器上尝试期待我的脚。

为此,我想我会尝试对“adduser”命令运行Expect。

我无法让它正常工作,似乎一切正常运行,我能够到达最后一个提示,它确实退出,但用户仍然未创建。

我究竟做错了什么?

#/usr/bin/expect -f 
spawn adduser testuser

expect "Enter new UNIX password"
send "testpassword\r"

expect "Retype new UNIX password"
send "testpassword\r"

expect "        Full Name []: "
send "\r"

expect "        Room Number []: "
send "\r"

expect "        Work Phone []: "
send "\r"

expect "        Home Phone []: "
send "\r"

expect "        Other []: "
send "\r"

expect "Is the information correct? \[Y/n\] "
send "\r"
linux expect
2个回答
1
投票

将以下内容保存为'automateUser'... chmod 775 ...然后在命令行中。

sudo期待-d automateUser

#!/usr/bin/expect

spawn adduser testuser

expect "Enter new UNIX password" { send "testpass\r" }
expect "Retype new UNIX password" { send "testpass\r" }
expect "Full Name" { send "\r" }
expect "Room Number" { send "\r" }
expect "Work Phone" { send "\r" }
expect "Home Phone" { send "\r" }
expect "Other" { send "\r" }
expect "correct?" { send "y\r" }

interact

如果您输入较少的/ etc / passwd后,您应该在列表中看到您的testuser。

  • 添加-d开关可以使期望行为更加可预测,并且它非常适合调试
  • expect-s可以是精确的或松散的(例如完全匹配vs'包含')
  • 某些操作可能需要root ...像adduser

使用Expect版本5.45对Ubuntu 16.04进行了测试。


0
投票

看起来所有这些都是错的:expect " Something []: "

我会用expect -ex {Something []: }

  1. 使用“精确”匹配,因为你不需要全局或正则表达式模式的力量,和
  2. 大括号确保括号不被解释为Tcl命令替换语法。
© www.soinside.com 2019 - 2024. All rights reserved.