预计别名 [英] Expect in Alias

查看:176
本文介绍了预计别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是猛砸别名,让我为了缩短SSH命令我登录到我的路由器。相当微不足道,但一个节省时间!我现在想要做的是借此更进一步,完全自动化的路由器的日志项。

I am using a Bash alias that allows me to shorten the SSH command in order for me to log into my routers. Quite trivial, but a time saver! What I would now like to do is take this a step further and fully automate the logging-in of the routers.

例如在我的〜/ .bashrc中文件我有以下条目:

For example in my ~/.bashrc file I have the following entry:

sshFuncB()
{
    ssh -o StrictHostKeyChecking=no superuser@$1 - | /usr/bin/expect<<EOF  
    set timeout 5
    set send_human {.1 .3 1 .05 2}

    expect {
        "password: " { send -h "MYPASSWORD\r" }
        "No route to host" { exit 1 }
        timeout { exit 1 }
    }
    set timeout 2
    sleep 1
    expect { 
        "N]?" { send "y\r"; exp_continue }
        timeout { exit 1 }
    }
    expect eof
EOF
}

alias z=sshFunc

然而,当我键入 z来myrouterhostname 这并没有得到期望的输出。我必须找到一个方法来启动SSH连接,并具有自动希望控制返回给用户之前登录。

However, when I type z myrouterhostname this does not give the desired output. I must find a way to start the SSH connection and have expect automate logging in before returning control to user.

任何想法?

推荐答案

这是可以做到如下,

sshFuncB()
{
    expect -c "
    spawn ssh -o StrictHostKeyChecking=no superuser@$1   
    set timeout 5
    set send_human {.1 .3 1 .05 2}

    expect {
        \"password: \" { send -h \"MYPASSWORD\r\" }
        \"No route to host\" { exit 1 }
        timeout { exit 1 }
    }
    set timeout 2
    sleep 1
    expect { 
        \"N]?\" { send \"y\r\"; exp_continue }
        timeout { exit 1 }
    }
    expect eof
   "
}

alias z=sshFuncB

请注意,在使用 -c 标志期望您可以从<一个参考href=\"http://stackoverflow.com/questions/25880200/expect-script-error-argv-not-found/25883001#25883001\">here您有任何疑问。

Note the use of -c flag in expect which you can refer from here of you have any doubts.

如果我们使用双引号为期望 code。与 -c 标志,它将使bash的换人。如果使用单引号相同,则bash的替代将无法正常工作。 (您已经使用 @ 1 里面的期待,这就是为什么我用双引号)因为我已经使用双引号整个预期code,我们要躲避用反斜杠每个双引号里面的期待声明如下例所示,

If we use double quotes for the expect code with -c flag, it will allow the bash substitutions. If you use single quotes for the same, then bash substitutions won't work. (You have used @1 inside expect, which is why I used double quotes) Since I have used double quotes for the whole expect code, we have to escape the each double quotes with backslash inside the expect statement like as follows,

   expect {
        # Escaping the double quote with backslash
        \"password: \" {some_action_here}
   }

还有一个更新。由于这是有关连接到路由器,并做一些你手动操作的,那么最好是有交互结尾。

这篇关于预计别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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