Ganymed ssh小使用

Ganymed SSH

目录
1 SSH简介 1
2 JAVA实现SSH的项目 1
3 GANYMED SSH 1
3.1 依赖说明 1
3.2 实现简单命令 1
3.2 实现SCP命令

1 SSH简介
SSH协议的简介可见: http://xmong.iteye.com/blog/1698124

2 Java实现SSH的项目
Java 实现SSH协议的项目有很多,如JFTP,trilead SSH,JSCH,ganymed SSH等
下面我们主要说的是关于ganymed SSH的一些小使用。
Ganymed SSH-2 for Java是用纯Java实现SSH-2协议的一个项目。可以通过它直接在Java程序中连接SSH服务器,实现基于SSH协议的服务访问。 如远程命令执行和shell访问,本地和远程端口转发,本地数据流转发,X11转发,SCP,SFTP等功能。

3 Ganymed SSH
3.1 依赖说明
Ganymed SSH地址: http://www.ganymed.ethz.ch/ssh2/,下载ganymed-ssh2-build210.zip包,解压后可见src(源代码),ganymed-ssh2-build210.jar (jar包),javadoc(常用api文档),examples(简单使用案例)。可以通过简单使用案例学习ganymed ssh的使用。

使用方法:将 ganymed-ssh2-build210.jar 加入到java项目的lib中即可使用。

3.2 实现简单命令

package com.example;

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.Session;
import ch.ethz.ssh2.StreamGobbler;

public class Basic
{
	public static void main(String[] args)
	{
                //服务器ip
		String hostname = "172.30.5.162";
                //用户名
		String username = "xmong";
                //密码
		String password = "xmong";

		try
		{
			/* Create a connection instance */
            //构造一个连接器,传入一个需要登陆的ip地址,连接服务
			Connection conn = new Connection(hostname);

			/* Now connect */
			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,执行linux命令
			Session sess = conn.openSession();
			
			
			sess.execCommand("pwd");
			
			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") */
			//得到脚本运行成功与否的标志 :0-成功 非0-失败
			System.out.println("ExitCode: " + sess.getExitStatus());

			/* Close this session */
			//关闭session和connection 
			sess.close();

			/* Close the connection */

			conn.close();

		}
		catch (IOException e)
		{
			e.printStackTrace(System.err);
			System.exit(2);
		}
	}
}



输出结果:

Here is some information about the remote host:
/home/xmong
ExitCode: null



3.2 实现SCP命令

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.SCPClient;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class TestScp {
	
	
	public static void main(String[] args)
	{
		String hostname = "172.30.5.162";
		String username = "xmong";
		String password = "xmong";

		try
		{
			/* Create a connection instance */
            //构造一个连接器,传入一个需要登陆的ip地址,连接服务
			Connection conn = new Connection(hostname);
			conn.connect();

			//用户验证,传入用户名和密码
			boolean isAuthenticated = conn.authenticateWithPassword(username, password);

			if (isAuthenticated == false)
				throw new IOException("Authentication failed.");
			
			//创建一个copy文件客户端
			SCPClient scpClient = conn.createSCPClient();
			scpClient.put("D:/test.txt ", "./");//从本地复制文件到远程目录   
			scpClient.get("./test.txt", "E:/");//从远程获取文件

 			/**
			 * 通过SFTP远程读取文件内容
			 * test.txt文件内容为sftp---test
			 */
			SFTPv3Client sftpClient = new SFTPv3Client(conn);
			SFTPv3FileHandle sftpHandle = sftpClient.openFileRW("./test.txt");
			byte[] bs = new byte[11];
			int i = 0;
			long offset = 0;
			while(i!=-1){
				i = sftpClient.read(sftpHandle, offset, bs, 0, bs.length);
				offset += i;
			}
			System.out.println(new String(bs));
			
			//打开一个会话session,执行linux命令
			Session sess = conn.openSession();
			sess.execCommand("ls");
			System.out.println("Here is some information about the remote host:");

			//接收目标服务器上的控制台返回结果,输出结果。
			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);
			}

			//得到脚本运行成功与否的标志 :0-成功 非0-失败
			System.out.println("ExitCode: " + sess.getExitStatus());

			//关闭session和connection 
			sess.close();
			conn.close();

		}
		catch (IOException e)
		{
			e.printStackTrace(System.err);
			System.exit(2);
		}
	}

}



输出结果:
sftp---test
Here is some information about the remote host:
test.txt
ExitCode: 0



猜你喜欢

转载自xmong.iteye.com/blog/1698407
今日推荐