简体   繁体   English

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

[英]Creating an Expect Script for Linux "adduser" command

I'm a newbie when it comes to Expect, and I thought that I'd get my feet wet by first trying out expect on my local machine.我是一个关于 Expect 的新手,我认为首先在我的本地机器上尝试 expect 会弄湿我的脚。

To that end, I thought I'd try running Expect against the "adduser" command.为此,我想我会尝试针对“adduser”命令运行 Expect。

I can't get it to work properly, seems like everything is running properly, I am able to get to the last prompt, and it does exit, but the user remains uncreated.我无法让它正常工作,似乎一切都在正常运行,我能够到达最后一个提示,并且它确实退出了,但用户仍未创建。

What am I doing wrong?我究竟做错了什么?

#/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"

Save the following as 'automateUser' ... chmod 775 ... and then on the command line.将以下内容另存为 'automateUser' ... chmod 775 ... 然后在命令行上。

sudo expect -d automateUser须藤期望 -d 自动化用户

#!/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

If you type less /etc/passwd after, you should see your testuser in the list.如果您在之后输入较少的 /etc/passwd,您应该会在列表中看到您的 testuser。

  • adding the -d switch can make expect behave more predictably and it's great for debugging添加 -d 开关可以使 expect 的行为更具可预测性,并且非常适合调试
  • expect-s can be precise or loose (eg exact match vs 'contains') expect-s 可以是精确的或松散的(例如,精确匹配与“包含”)
  • certain operations may require root ... like adduser某些操作可能需要 root ... 像 adduser

Tested against Ubuntu 16.04 with Expect version 5.45.针对 Ubuntu 16.04 和 Expect 版本 5.45 进行了测试。

Looks like all these are wrong: expect " Something []: "看起来所有这些都是错误的: expect " Something []: "

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

  1. that uses "exact" matching since you don't need the power of glob or regex patterns, and使用“精确”匹配,因为您不需要 glob 或 regex 模式的功能,并且
  2. the braces ensure that the brackets are not interpreted as Tcl command substitution syntax.大括号确保括号不被解释为 Tcl 命令替换语法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM