java java中的ssh(在另一台机器上运行命令)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15415822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ssh in java (run commands on another machine)
提问by Saad Attieh
I was wondering whether there was a simple way to do this as part of a java program.
我想知道是否有一种简单的方法可以作为 Java 程序的一部分来执行此操作。
I would like to be able to ssh into another machine and perform commands on that machine.
我希望能够通过 ssh 连接到另一台机器并在该机器上执行命令。
A simple example would be: runtime.exec("say hello world"); would (on a mac) have a text-to-speech engine speak hello world.
一个简单的例子是:runtime.exec("say hello world"); 会(在 mac 上)有一个文本到语音引擎说你好世界。
Is there a way to have java run this method on another machine?
有没有办法让java在另一台机器上运行这个方法?
Also, assuming the above is possible, is there a way to ssh into more than one machine at the same time?
另外,假设以上是可能的,有没有办法同时 ssh 进入多台机器?
Thanks
谢谢
回答by Vito Gentile
There are a lot of libraries to do this. I suggest Ganymed SSH-2, that is also mentioned in the official OpenSSH website. In the same site, you can also find other libraries that you can use for Java.
有很多图书馆可以做到这一点。我建议使用Ganymed SSH-2,OpenSSH 官方网站也提到了它。在同一站点中,您还可以找到可用于 Java 的其他库。
This is an example of ls -r
command executed via SSH, using Ganymed SSH-2:
这是ls -r
使用 Ganymed SSH-2 通过 SSH 执行的命令示例:
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
[...]
public static ArrayList<String> lsViaSSH(String hostname, String username, String password, String dir) {
ArrayList<String> ls = new ArrayList<String>();
try
{
Connection conn = new Connection(hostname);
conn.connect();
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated == false) {
return null;
}
Session sess = conn.openSession();
sess.execCommand("ls -r " + dir);
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true)
{
String line = br.readLine();
if (line == null)
break;
ls.add(line);
}
sess.close();
conn.close();
}
catch (IOException e)
{
return null;
}
if(StringUtils.isEmpty(ls.get(0)))
return null;
return ls;
}
This is not the only function needed in order to execute a command via SSH, but I hope it could be a good starting point for you.
这不是通过 SSH 执行命令所需的唯一功能,但我希望它可以成为您的一个很好的起点。
回答by rbedger
回答by Oleg Mikheev
given that you're on a system where ssh command is available and ssh keys are set upto avoid entering passwords the easiest would be just
鉴于您所在的系统可以使用 ssh 命令并且设置了 ssh 密钥以避免输入密码,最简单的方法就是
runtime.exec("ssh remote_comp 'say hello world'");
回答by BackSlash
I'd suggest you to take a look to the Apache MINA SSHD, it can be used to write both a client and a server with java
我建议你看看Apache MINA SSHD,它可以用来用 java 编写客户端和服务器