如何在Java代码中使用Jruby在Ruby脚本中调用方法
这是我的Ruby脚本(test.rb):
# coding=utf-8
require 'net/ssh'
def sshConnection (host, username, password)
Net::SSH.start(host.to_s, username.to_s, password: password.to_s) do |ssh|
result = ssh.exec!("command")
return result
end
end
因此,我如何使用Jruby在Java代码中调用此方法,我Hava试图搜索它,这是我的代码:
package com.example;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
public class JrubyDemo1 {
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("ruby");
try{
engine.eval(Files.newBufferedReader(Paths.get(".....\\test.rb"),StandardCharsets.UTF_8));
Invocable invocable = (Invocable) engine
Object o = invocable.invokeFunction("sshConnection", "xx.xx.xx.xx", "xxx", "xxx");
System.out.println(o);
}catch(Exception e){
//...
}
}
}
但是它不起作用,
here is my ruby script(test.rb):
# coding=utf-8
require 'net/ssh'
def sshConnection (host, username, password)
Net::SSH.start(host.to_s, username.to_s, password: password.to_s) do |ssh|
result = ssh.exec!("command")
return result
end
end
so, how can i use jruby to call this method in java code, i hava tried to search it and here is my code:
package com.example;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
public class JrubyDemo1 {
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("ruby");
try{
engine.eval(Files.newBufferedReader(Paths.get(".....\\test.rb"),StandardCharsets.UTF_8));
Invocable invocable = (Invocable) engine
Object o = invocable.invokeFunction("sshConnection", "xx.xx.xx.xx", "xxx", "xxx");
System.out.println(o);
}catch(Exception e){
//...
}
}
}
but it didn't work, error is as this picture shows:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论