简体   繁体   中英

ssh in java (run commands on another machine)

I was wondering whether there was a simple way to do this as part of a java program.

I would like to be able to ssh into another machine and perform commands on that machine.

A simple example would be: runtime.exec("say hello world"); would (on a mac) have a text-to-speech engine speak hello world.

Is there a way to have java run this method on another machine?

Also, assuming the above is possible, is there a way to ssh into more than one machine at the same time?

Thanks

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.

Have a look at JSch

As far as executing at the exact same time? Not really unless you intend to spawn multiple threads to deal with your list of remote machines.

鉴于您所在的系统中ssh命令可用,并且设置了ssh密钥以避免输入密码,最简单的只是

runtime.exec("ssh remote_comp 'say hello world'");

我建议你看一下Apache MINA SSHD ,它可以用java写一个客户端和一个服务器

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM