使用 expect 输入命令

使用 expect 输入命令

以下是我所讨论的话题:在命令中输入输入?

所以我尝试运行这个命令:cd /etc/openvpn/easy-rsa; . ./vars; ./build-key username

但是,运行该命令后,我需要输入 10 次(只需按 Enter 键)并且按两次 y。上一个线程中的用户建议我使用 except,但我无法让它工作。以下是它提出的问题:

root@suffice-vpn:/etc/openvpn/easy-rsa# ./build-key usernamtest
Generating a 2048 bit RSA private key
..................+++
........+++
writing new private key to 'usernamtest.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [US]:
State or Province Name (full name) [NY]:
Locality Name (eg, city) [Merrick]:
Organization Name (eg, company) [IceWare]:
Organizational Unit Name (eg, section) [IceWare]:
Common Name (eg, your name or your server's hostname) [usernamtest]:
Name [server]:
Email Address [[email protected]]:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
Using configuration from /etc/openvpn/easy-rsa/openssl-1.0.0.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows
countryName           :PRINTABLE:'US'
stateOrProvinceName   :PRINTABLE:'NY'
localityName          :PRINTABLE:'Merrick'
organizationName      :PRINTABLE:'IceWare'
organizationalUnitName:PRINTABLE:'IceWare'
commonName            :PRINTABLE:'usernamtest'
name                  :PRINTABLE:'server'
emailAddress          :IA5STRING:'[email protected]'
Certificate is to be certified until Jan 14 18:27:48 2026 GMT (3650 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y

如您所见,我最初按了 8 次 Enter 键 [以保留默认输入],然后再按 2 次 Enter 键以跳过可选命令。然后,我需要按 y 键两次。我该如何自动执行此操作?我需要在一个命令中完成所有这些操作。有什么建议吗?提前致谢。

答案1

这是一个您可以尝试的 quick'n'dirty 预期脚本(我无法自己测试它,因为我没有在任何地方使用 openvpn):

#!/usr/bin/expect

set timeout 20
set username [lindex $argv 0]

spawn ./build-key $username

while 1 { 
  expect { 
    "y/n]" { send "y\r" }
    "]:" { send "\r" }
    eof { break } 
  } 
}

基本上,y只要它看到一个y/n]问题,它就会发送,而只要它看到任何其他右方括号,它就会发送一个换行符],直到输入完毕。

您可以将其另存为whatever,使其可执行,然后执行

./whatever usernametest

答案2

我找到了一个更简单的选择:

cd /etc/openvpn/easy-rsa; . ./vars; ./build-key --batch username

相关内容