使用expect输入命令

下面是我正在反弹的线程: 在命令中输入输入?

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

但是,在运行该命令后,我需要输入任何内容[只需按下输入] 10次,然后按两次y键。 最后一个线程上的用户建议我使用除外,但是我无法使用它。 以下是它提出的问题:

 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 [iceware@programmer.net]: 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:'iceware@programmer.net' 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次[以保持默认输入],然后再输入2次以跳过可选命令。 然后,我需要按两次y。 我该如何自动化? 我需要在一个命令中完成这一切。 有什么建议? 提前致谢。

这是一个quick’n’dirty expect脚本,你可以尝试(我不能自己测试,因为我没有在任何地方使用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/n]问题时它基本上发送y ,只要它看到任何其他结束方括号时只是一个换行符,直到它用完了输入。

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

 ./whatever usernametest 

我发现了一个更简单的选择

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