期望ssh脚本返回无效的命令名 [英] expect script to ssh returns invalid command name

查看:224
本文介绍了期望ssh脚本返回无效的命令名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个ssh脚本,该脚本将ssh到服务器中,发送sudo su,然后检查iptables状态并将输出放在服务器上的日志文件中.下面是脚本.

I am trying to write an expect script which would ssh into a server, send sudo su, then check the iptables status and put the output in a log file on the server. Below is the script.

1 #!/usr/bin/expect
  2 exp_internal 1
  3 log_user 0
  4 set timeout 10
  5 set password  "******"
  6 
  7 spawn /usr/bin/ssh -l subhasish *.*.*.* -p 10022
  8 
  9 expect {
 10      -re "password: " {send "$password\r"}
 11      -re "$ "  {send "sudo su\r"}
 12      -re "[sudo] password for subhasish:" {send "$password\r"}
 13      -re "# "  {send "service iptables status\r"}
 14        }
 15 set output $expect_out(buffer)
 16 send "exit\r"
 17 puts "$output\r\n" >> output.log

但是在调试模式下运行时,出现这样的错误;

But while run in debug mode, I am getting error like this;

expect -d testcase
expect version 5.44.1.15
argv[0] = expect  argv[1] = -d  argv[2] = testcase  
set argc 0
set argv0 "testcase"
set argv ""
executing commands from command file testcase
parent: waiting for sync byte
parent: telling child to go ahead
parent: now unsynchronized from child
spawn: returns {24105}
invalid command name "sudo"
    while executing
"sudo"
    invoked from within
"expect {
     -re "password: " {send "$password\r"}
     -re "$ "  {send "sudo su\r"}
     -re "[sudo] password for subhasish:" {send "$password\r"}
 ..."
    (file "testcase" line 9)

不确定我要去哪里.它说无效的命令名称"sudo",我想这是因为Expect无法理解这些命令.如何解决它.请帮忙.谢谢.

Not sure where I am going wrong. It says invalid command name "sudo", I guess this is because expect doesn;t understand these command. How to go around it. Please help. Thanks.

推荐答案

问题出在这一行

-re "[sudo] password for subhasish:" {send "$password\r"}

在Tcl中(因此在预期中),方括号是命令替换的语法(如shell中的反引号).因此,您需要转义括号或使用不同的引号来防止出现各种扩展情况:

In Tcl (and hence in expect) the square brackets are the syntax for command substitution (like backticks in the shell). So you either need to escape the brackets or use different quotes that prevent various expansions:

-re {[sudo] password for subhasish:} {send "$password\r"}

这带来了一个不同的问题:您是否希望看到这些确切的字符?因为您的指示期望将其视为正则表达式,并且正则表达式中的方括号表示字符类,所以它将匹配单个字符,即"s","u","d"或"o" '.因此,您可能需要的是这样:

That brings up a different issue: are you expecting to see these exact characters? Because you're instructing expect to treat that as a regular expression, and square brackets in a regular expression means a character class, so it will match a single character, either a 's', 'u', 'd' or 'o'. So what you probably need is this:

-re {\[sudo\] password for subhasish:} {send "$password\r"}

-ex {[sudo] password for subhasish:} {send "$password\r"}

这篇关于期望ssh脚本返回无效的命令名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆