Java ssh 访问windows/Linux


Java code运行在一台机器上,需要远程到linux的机器同时执行多种命令。原来采用的方法是直接调用ssh命令或者调用plink的命令。



Ganymed SSH2 for Java is a library which implements the SSH-2 protocol in pure Java.It allows one to connect to SSH servers from within Java programs. It supports SSH sessions(remote command execution and shell access),local and remote port forwarding, local stream forwarding, X11 forwarding, SCP and SFTP.There are no dependencies on any JCE provider, as all crypto functionality is included.

Ganymed SSH2 for Java was first developed for the Ganymed replication project and acouple of other projects at the IKS group at ETH Zurich.





Package ch.ethz.ssh2

Interface Summary
ChannelCondition Contains constants that can be used to specify what conditions to wait for on a SSH-2 channel (e.g., represented by aSession).
ConnectionMonitor A ConnectionMonitor is used to get notified when the underlying socket of a connection is closed.
InteractiveCallback An InteractiveCallback is used to respond to challenges sent by the server if authentication mode "keyboard-interactive" is selected.
ProxyData An abstract marker interface implemented by all proxy data implementations.
ServerHostKeyVerifier A callback interface used to implement a client specific method of checking server host keys.
Class Summary
Connection A Connection is used to establish an encrypted TCP/IP connection to a SSH-2 server.
ConnectionInfo In most cases you probably do not need the information contained in here.
DHGexParameters A DHGexParameters object can be used to specify parameters for the diffie-hellman group exchange.
HTTPProxyData A HTTPProxyData object is used to specify the needed connection data to connect through a HTTP proxy.
KnownHosts The KnownHosts class is a handy tool to verify received server hostkeys based on the information inknown_hosts files (the ones used by OpenSSH).
LocalPortForwarder A LocalPortForwarder forwards TCP/IP connections to a local port via the secure tunnel to another host (which may or may not be identical to the remote SSH-2 server).
LocalStreamForwarder A LocalStreamForwarder forwards an Input- and Outputstream pair via the secure tunnel to another host (which may or may not be identical to the remote SSH-2 server).
SCPClient A very basic SCPClient that can be used to copy files from/to the SSH-2 server.
Session A Session is a remote execution of a program.
SFTPv3Client A SFTPv3Client represents a SFTP (protocol version 3) client connection tunnelled over a SSH-2 connection.
SFTPv3DirectoryEntry A SFTPv3DirectoryEntry as returned by
SFTPv3FileAttributes A SFTPv3FileAttributes object represents detail information about a file on the server.
SFTPv3FileHandle A SFTPv3FileHandle.
StreamGobbler A StreamGobbler is an InputStream that uses an internal worker thread to constantly consume input from another InputStream.
Exception Summary
HTTPProxyException May be thrown upon connect() if a HTTP proxy is being used.
SFTPException Used in combination with the SFTPv3Client.


(1) SSH到Linux机器

package ssh;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.*;
public class Basic {
    public static void main(String[] args)
        String hostname ="";
        String username="root";
        String password="password";
            Connection conn= new Connection(hostname);
            System.out.println("set up connections");
            boolean isAuthenticated = conn.authenticateWithPassword(username, password);
            if(isAuthenticated ==false)
                throw new IOException("Authorication failed");
            Session sess = conn.openSession();
            System.out.println("Execute command:/usr/bin/perl /test/ /test/meps_linux.txt");
            sess.execCommand("/usr/bin/perl /test/ /test/meps_linux.txt");
            System.out.println("The execute command output is:");
            InputStream stdout = new StreamGobbler(sess.getStdout());
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
                String line = br.readLine();
                if(line==null) break;
            System.out.println("Exit code "+sess.getExitStatus());
            System.out.println("Connection closed");
        }catch(IOException e)
            System.out.println("can not access the remote machine");


(2) SSH到windows机器:

windows由于没有默认的ssh server,因此在允许ssh之前需要先安装ssh server。



Private keys should be created. Should I do it now?

Do you want to run FreeSSHd as a system service?




Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.



String hostname ="localhost";



set up connections
Begin execute remote commands
The execute command output is:
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.



sess.execCommand("cmd.exe /c \"perl -V\"");

cmd /c dir 是执行完dir命令后关闭命令窗口。

cmd /k dir 是执行完dir命令后不关闭命令窗口。

cmd /c start dir 会打开一个新窗口后执行dir指令,原窗口会关闭。

cmd /k start dir 会打开一个新窗口后执行dir指令,原窗口不会关闭。

可以用cmd /?查看帮助信息。