我想知道是否有一种简单的方法可以作为 java 程序的一部分来执行此操作。
我希望能够 ssh 进入另一台机器并在该机器上执行命令。
一个简单的例子是:runtime.exec("say hello world"); (在 Mac 上)会有一个文本到语音引擎说你好世界。
有没有办法让java在另一台机器上运行这个方法?
另外,假设上述情况是可能的,有没有办法同时 ssh 进入多台机器?
谢谢
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.
This is an example of ls -r
command executed via SSH, using Ganymed SSH-2:
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.
看看JSC
至于在同一时间执行?除非您打算生成多个线程来处理您的远程计算机列表,否则不是真的。
假设您所在的系统可以使用 ssh 命令并且设置了 ssh 密钥以避免输入密码,那么最简单的方法就是
runtime.exec("ssh remote_comp 'say hello world'");
我建议你看看Apache MINA SSHD,它可以用来用 java 编写客户端和服务器