【问题标题】:Pass command line arguments to expect command将命令行参数传递给期望命令
【发布时间】:2019-11-29 11:45:07
【问题描述】:

我正在尝试编写一个将用户名作为命令行参数的 bash 脚本。它应该使用提供的用户名登录系统并执行命令。

expect -c 'spawn su - other_user_name -c my_bash_command; expect "Password :"; send my_password\n; interact'

如果我提供所需的变量,它应该是:

expect -c 'spawn su - $1 -c ps ax | grep java | cut -f2 -d " " - | xargs kill -9; expect "Password :"; send Temp/123\n; interact'

其中$1 是传递的用户名,ps ax | grep java | cut -f2 -d " " - | xargs kill -9 是该用户执行的命令。如果我传递参数,它会说没有这样的变量。如果我在脚本顶部写#!/usr/bin/expect,它就不起作用。我需要修复它。

【问题讨论】:

  • $1 是 shell 语法,Tcl 不支持。 Expect 的 spawn 不支持 | 在 shell 中。用expect -c 编写复杂的Expect 脚本并不容易,因为字符串引用会很乱。我建议您编写一个独立的foo.exp 并将其调用为expect foo.exp ...
  • 看看sexpect (Expect for Shells),您可以使用它来编写仅使用shell代码Expect脚本。
  • pkill 在您的系统上可用吗?可能更容易使用。

标签: linux bash shell expect


【解决方案1】:

解决 pynexj 的有效问题,并将用户名传递给期望通过环境(并添加换行符以提高可读性):

env user="other_user_name" expect -c '
    spawn sh -c "su - $env(user) -c ps ax | grep java | cut -f2 -d \" \" - | xargs kill -9"
    expect "Password :"
    send Temp/123\n
    interact
'

【讨论】:

    猜你喜欢
    • 2015-06-09
    • 2017-10-22
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多