使用Groovy读取远程Linux文件特定条目报错,请求代码正确性验证
Hey there! Let's break down why your code is throwing that error and get you sorted out quickly.
The Exact Issue
That error message latest.groovy: 50: expecting EOF, found 'in' is crystal clear: you’re using a reserved Groovy keyword as a variable name.
in is a built-in keyword in Groovy (and Java) — it’s used for iteration loops like for (item in collection). Reserved keywords can’t be used as variable names, which is why the compiler is rejecting this line:
DataInputStream in = new DataInputStream(io)
Quick Fix
Just rename the variable to any valid, non-reserved identifier. Pick something descriptive or concise, like:
// Descriptive option DataInputStream inputStream = new DataInputStream(io) // Shorter alternative DataInputStream dataIn = new DataInputStream(io)
Bonus: Simpler Remote File Reading
Handling raw input streams for remote files can get cumbersome. Here’s a more straightforward approach using Groovy’s built-in process execution to run SSH commands:
// Configure your remote server details def remoteUser = "your-username" def remoteServer = "your-server-ip-or-hostname" def remoteFilePath = "/path/to/your/target/file" // Fetch file content via SSH def process = "ssh ${remoteUser}@${remoteServer} 'cat ${remoteFilePath}'".execute() process.waitFor() // Extract specific entries (adjust the matching logic to your needs) def fileContent = process.in.text def targetEntries = fileContent.split("\n").findAll { line -> line.contains("your-keyword-or-pattern") } targetEntries.each { println it }
Note: This works best if you’ve set up SSH key-based authentication (so you don’t need to enter a password manually). For password-protected connections, consider using a library like JSch for more controlled SSH handling.
内容的提问来源于stack exchange,提问作者DevOops

