您的位置:首页 > 编程语言 > Java开发

Ganymed SSH-2 for Java

2011-12-02 12:32 435 查看
在java程序中执行shell命令的时候,比较常用的是Ganymed(http://www.cleondris.ch/opensource/ssh2/)的包。

有了这个功能后我们就可以实现在网页上面操作一堆命令的工作了。直接去网站下载最新版本。服务器必须是SSH servers。官方介绍如下:

Ganymed SSH-2 for Java is an open source library which implements the SSH-2 protocol in pure Java(tested on J2SE 1.4.2 and 5.0). It allows one to connect to SSH servers from withinJava 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.

Originally, Ganymed SSH-2 for Java was developed for the Ganymed replication projectat ETH Zurich (Switzerland).

下面看一个简单的例子:

package com.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.HTTPProxyData;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class BasicWithHTTPProxy
{
public static void main(String[] args)
{
String hostname = "my-ssh-server";
String username = "joe";
String password = "joespass";

String proxyHost = "192.168.1.1";
int proxyPort = 3128; // default port used by squid

try
{
/* Create a connection instance */

Connection conn = new Connection(hostname);

/* We want to connect through a HTTP proxy */

conn.setProxyData(new HTTPProxyData(proxyHost, proxyPort));

// if the proxy requires basic authentication:
// conn.setProxyData(new HTTPProxyData(proxyHost, proxyPort, "username", "secret"));

/* Now connect (through the proxy) */

conn.connect();

/* Authenticate.
* If you get an IOException saying something like
* "Authentication method password not supported by the server at this stage."
* then please check the FAQ.
*/

boolean isAuthenticated = conn.authenticateWithPassword(username, password);

if (isAuthenticated == false)
throw new IOException("Authentication failed.");

/* Create a session */

Session sess = conn.openSession();

sess.execCommand("uname -a && date && uptime && who");

System.out.println("Here is some information about the remote host:");

/*
* This basic example does not handle stderr, which is sometimes dangerous
* (please read the FAQ).
*/

InputStream stdout = new StreamGobbler(sess.getStdout());

BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

while (true)
{
String line = br.readLine();
if (line == null)
break;
System.out.println(line);
}

/* Show exit status, if available (otherwise "null") */

System.out.println("ExitCode: " + sess.getExitStatus());

/* Close this session */

sess.close();

/* Close the connection */

conn.close();

}
catch (IOException e)
{
e.printStackTrace(System.err);
System.exit(2);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息