【问题标题】:expect command is not passing env variable in ubuntu focal期望命令未在 ubuntu 焦点中传递 env 变量
【发布时间】:2021-07-09 15:10:05
【问题描述】:

我正在使用 expect (v5.45.4-2build1) 在 ubuntu 焦点中使用 easy-rsa 自动生成客户端证书。 根据 easy-rsa,要自定义证书有效性,我们需要传递 EASYRSA_CERT_EXPIRE 变量。 但由于某种原因,我的期望脚本无法获取此变量。 下面是 script.exp 的代码:

#!/usr/bin/expect -f

set timeout -1
#exp_internal 1

set MY_PASSPHRASE [lindex $argv 0];
set USERNAME [lindex $argv 1];
set ttl [lindex $argv 2];

send "export EASYRSA_CERT_EXPIRE=$ttl\r"
spawn /bin/bash

set MSG "Executing script.exp for $USERNAME and $ttl";
send "echo 'INFO $MSG'>> /var/log/app/my_app.log\r"

send "cd /etc/openvpn/easy-rsa\r"

send "export EASYRSA_CERT_EXPIRE=$ttl\r"

send "./easyrsa gen-req $USERNAME\r"
expect "*Enter PEM pass phrase:"
send -- "$MY_PASSPHRASE\r"
expect "*Verifying - Enter PEM pass phrase:"
send -- "$MY_PASSPHRASE\r"
expect "*Common Name *$USERNAME*"
send -- "\r"
expect "*Keypair and certificate request completed*"
send -- "\r"
exit 0

奇怪的是,如果我通过 expect script.exp 运行脚本,这会正常工作。 但我想在我的 perl 脚本中使用它,但它不适用于 perl 脚本。

这就是我调用期望脚本的方式:

my $cmd_out_csr = system("expect script.exp $my_passphrase $username $ttl");

刚刚运行,来自 cmd 的 expect script.exp $my_passphrase $username $ttl 工作正常。 任何帮助表示赞赏。 谢谢。

【问题讨论】:

  • 这个怎么样 - my $cmd_out_csr = `expect script.exp $my_passphrase $username $ttl`;
  • @vkk05 我不想要输出,只想要状态。问题是当我从我的 perl 脚本调用它时,没有考虑我的环境变量 EASYRSA_CERT_EXPIRE 。
  • 你能粘贴你的整个期望脚本代码吗?我看不到你在哪里收集论据。类似set username [lindex $argv 0]; ..
  • @GhanshyamGupta:你能在期望提示符中打印$my_passphrase、$username 和$ttl 的值吗?
  • my $cmd_out_csr = system('expect', 'script.exp', $my_passphrase, $username, 365); $ttl 是 365

标签: linux bash perl expect ubuntu-20.04


【解决方案1】:
  1. 使用带有参数列表的 perl system 命令:

    system('expect', 'script.exp', $my_passphrase, $username, $ttl);
    
  2. 在远程 shell 中创建变量时,在值周围发送引号:

    send "export EASYRSA_CERT_EXPIRE=\"$ttl\"\r"
    

如果$ttl 包含空格,这两件事将保护它的值。


另一个想法:期望(通过 Tcl)可以cd 并设置环境变量。直接生成easyrsa,而不是生成bash shell:

#!/usr/bin/expect -f

set timeout -1
#exp_internal 1

lassign $argv MY_PASSPHRASE USERNAME ttl

set f [open /var/log/app/my_app.log a]
puts $f "INFO Executing [info script] for $USERNAME and $ttl"
close $f

cd /etc/openvpn/easy-rsa
set env(EASYRSA_CERT_EXPIRE) $ttl

spawn ./easyrsa gen-req $USERNAME

expect "*Enter PEM pass phrase:"
send -- "$MY_PASSPHRASE\r"
expect "*Verifying - Enter PEM pass phrase:"
send -- "$MY_PASSPHRASE\r"
expect "*Common Name *$USERNAME*"
send -- "\r"
expect "*Keypair and certificate request completed*"
send -- "\r"
expect eof

puts "Done."

【讨论】:

    猜你喜欢
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-26
    • 2011-03-19
    相关资源
    最近更新 更多