【发布时间】: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在您的系统上可用吗?可能更容易使用。