我从我的 groovy 脚本运行一些外部命令
我从我的 groovy 脚本打印外部命令结果:
println "stdout: ${proc.in.text}" )
.
我的完整 groovy 脚本
path='C:/Program Files/Systems/VPN/vpnclient.exe'
NAME = "JGSVGVGBGVG"
PASS = "JHBYGTGFBV"
USER = "HBTFTNI"
def command = """ $path connect user $USER pwd $PASS "$NAME" """
def proc = command.execute()
proc.waitFor()
// Obtain status and output
println "return code: ${ proc.exitValue()}"
println "stderr: ${proc.err.text}"
println "stdout: ${proc.in.text}"
groovy 脚本打印以下输出:
.
.
.
Authenticating user.
Negotiating security policies.
Securing communication channel.
Your VPN connection is secure.
到目前为止一切正常
现在我想匹配结果中的“您的 VPN 连接是安全的”行
因此,我在 groovy 中创建以下代码,并将此代码添加到我原来的 groovy 脚本中:(为了匹配该行),
line= 'Your VPN connection is secure.'
def matcher = ${proc.in.text}.matcher(line)
def count = matcher.getCount()
println "Matches = ${count}"
我得到“异常”,我对 groovy 很陌生,我不明白我的代码有什么问题 以及需要修复什么才能匹配该行 - 您的 VPN 连接是安全的
请帮忙
最佳答案
您有一个 GString 美元语法,该语法应位于双引号之间,但在本例中不需要。您可以只使用字符串匹配运算符,=~
。
我编写了一个小模拟(使用 proc=[in:[text:
))只是为了使断言起作用,您的脚本中不需要它:
proc=[in:[text:
'''
Authenticating user.
Negotiating security policies.
Securing communication channel.
Your VPN connection is secure.
'''
]]
line= 'Your VPN connection is secure.'
def matcher = proc.in.text =~ line
def count = matcher.getCount()
assert count == 1
<小时/>
更新:你不能使用proc.in.text
两次,你需要将其结果存储在一个变量中,然后重新读取该变量:
path='C:/Program Files/Systems/VPN/vpnclient.exe'
NAME = "JGSVGVGBGVG"
PASS = "JHBYGTGFBV"
USER = "HBTFTNI"
def command = """ $path connect user $USER pwd $PASS "$NAME" """
def proc = command.execute()
proc.waitFor()
def output = proc.in.text
// Obtain status and output
println "return code: ${ proc.exitValue()}"
println "stderr: ${proc.err.text}"
println "stdout: ${output}"
def matcher = (output =~ 'Your VPN connection is secure.')
def count = matcher.count
关于java - groovy + 如何匹配参数中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24387848/