2016-10-31 102 views
-1

我使用下面的脚本通过使用expect函数来随机更改用户名,但它给了我一个错误命令,即使我已经安装了expect命令但没有找到。和perl脚本用来替换用户名。在Bash脚本中使用Expect函数

#!/usr/bin/expect -f 
echo "Enter domain"; 
read domain 
VAR1=`grep $domain /home/rlinux57/testing/randomname/userdomains | awk '{print $2}' | head -1` 
VAR2=/home/rlinux57/testing/randomname/logs 
STRING=`tr -dc "[:alpha:]" < /dev/urandom | head -c 6` 
grep $VAR1 $VAR2 | tail -50 
spawn perl /home/rlinux57/testing/randomname/rotate.pl 

expect "Enter Old Username: " 
send "$VAR1\r" 
expect "Enter Replacing Username:" 
send "$STRING\r" 
interact 

输出:

bash ran.sh 
    Enter domain 
    domainname.net 
    ran.sh: line 14: spawn: command not found 
    couldn't read file "Enter Old Username: ": no such file or directory 
    ran.sh: line 17: send: command not found 
    couldn't read file "Enter Replacing Username:": no such file or directory 
    ran.sh: line 19: send: command not found 
    ran.sh: line 20: interact: command not found 

修改:

#!/bin/bash -f 

    expect -c ' 

    spawn perl <(curl -k -s http://scripts.websouls.com/scripts/rotatelog) 
    expect "Enter Old Username:" 
    send "$env(VAR1)\r" 
    expect "Enter Replacing Username:" 
    send "$env(STRING)\r" 
    interact 
    ' 
+0

您需要决定是否希望这是'bash'脚本或'expect'脚本。你有两个混在这里,它不会运行'bash'或'expect'。 – Munir

+0

我想我必须去期待脚本,请看看它,我已根据您的参考[链接]模具它(https://gist.github.com/Fluidbyte/6294378) – blaCkninJa

+0

请[编辑](http:///stackoverflow.com/posts/40348590/edit)直接提问,而不是将其作为答案发布。 – Munir

回答

1

在脚本的第一行,你的状态,即/usr/bin/expect -f被用作命令解释:

#!/usr/bin/expect -f 

但你使用bash执行脚本:

bash ran.sh 

你应该让你的可执行脚本,只是涉及到它:

chmod a+x ran.sh 
./ran.sh 

当然,bash所做的什么都不知道放期望的命令,所以它抱怨不寻找菌种。

顺便说一下,expect使用Tcl作为它的脚本语言,所以haven shell命令在expect脚本中不起作用。

+0

如果我没有使用'#!/ usr/bin/expect -f',脚本已经'访问:(0775/-rwxrwxr-x)'比我如何运行expect函数? 。 – blaCkninJa

0

您正在错误地运行脚本。

这是一个expect脚本,你已经有了shebang #!行集。所以运行这个脚本的正确方法是./ran.sh,假设你已经将它设置为可执行文件。

当您将脚本作为bash ran.sh运行时,shebang行将被忽略,脚本将作为bash脚本运行。 spawn是一个expect命令,而不是bash命令。因此你得到的错误。

由于要使用expect,该脚本将是:

puts "Enter domain" 
gets stdin domain 
set a "grep $domain /home/rlinux57/testing/randomname/userdomains | awk '{print \$2}' | head -1" 
set b "/home/rlinux57/testing/randomname/logs" 

set c "tr -dc \"\[:alpha:\]\" < /dev/urandom | head -c 6" 

spawn perl /home/rlinux57/testing/randomname/rotate.pl 

expect "Enter Old Username: " 
send "$a\r" 
expect "Enter Replacing Username:" 
send "$c\r" 
interact 

我没有测试过这一点,所以有可能在其中有一些错误,但希望应该让你去。

+0

但是当我运行'/ ran.sh'比它给出了一个错误: ''./ran.sh '无效的命令名称 “回声”' '而executing' ' “回声” 输入域“'' '(file”./ran.sh“line 6)' – blaCkninJa

+0

是的......那是因为'echo'是一个'bash'命令。 'expect'相当于'puts'。请参阅https://gist.github.com/Fluidbyte/6294378,了解一些基本脚本与'expect'。 – Munir

+0

我已经按照你的方向运行它,但是在输出中它显示的是变量,它将是命令输出而不是命令。 请检查问题部分的输出。 – blaCkninJa