您的位置:首页 > 运维架构 > Linux

【JAVA笔记】使用ganymed-ssh2-build210.jar访问Linux虚拟主机获取数据

2014-01-03 10:31 711 查看
这次的任务是,要我使用SSH2协议连接本地机与远程主机,并获取相应的数据。

因为不能拿真的主机做实验,所以我用Liunx虚拟机代替一下,主要还是学习怎么使用这个东西。

zip里给了几个example,看一下最基础的Basic就能大概清楚工作流程了。

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)
{
String hostname = "127.0.0.1";
String username = "joe";
String password = "joespass";

try
{
/* Create a connection instance */

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 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);
}
}
}


考虑到任务需要连续执行多条指令,所以每次都“连接 —— 开connection —— 开SESSION —— 关”就觉得很麻烦,而且判断能否与主机连接一次就够了。所以改了一下

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.log4j.Logger;

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

/**
* <p>
* Title: CommandRunner.java
* </p>
*
* @author wang.yd
* @version 1.0 创建时间:2013-12-31 上午09:55:11
*/
public class CommandRunner
{

private static final Logger LOGGER = Logger.getLogger(CommandRunner.class);

// ///////////// PROPERTIES ///////////////

private String hostname;
private String user;
private String password;
private Connection conn;
private Session session = null;

// ///////////// METHODS ///////////////

public boolean connect()
{

try
{
conn = new Connection(hostname);
conn.connect();

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

if (isAuthenticated == false)
{
throw new IOException("Authentication failed.");
}
else
{
System.out.println("Login success");
return true;
}

}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}

public InputStream command(String command, boolean print)
// command:输入的指令 print:是否控制台打印结果
{

try
{

session = conn.openSession();

session.execCommand(command);// execute command

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

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

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

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

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

return stdout;

}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace(System.err);
System.exit(2);
}
finally
{
session.close();
}
return null;
}

public void close()
{
if (conn != null)
{
conn.close();
}
}

/////////////// GETER & SETER ///////////////

......

}
 

问题:比如,执行cd ..指令之后再执行一条ls指令

可以写成:cd ..\nls

但不能连续两次分别执行。比如:command("cd ..",false);command("ls",false);

*******************************************************************************************

候鸟飞多远,也想念着南方。旅人的天涯,到尽头还是家。
下一站,还感觉不来是冷还是暖。天一亮,我又离开。
如果我回来,有没有人等待。如果我孤单,会不会谁明白。
想象着,再见面却怕自己不勇敢。想拥抱,在你胸怀。 
时光隧道,传来回音。请你听一听,那是我们当时,幸福约定。 

有些人,在心底从来没忘记。有些事,有些梦,还找不到谜底。
有些话,越欲言又止,就越是动听。让我们靠近,想悄悄告诉你,多爱你。 
那颗心,还一直守候没离去。走遍了全世界,还是你最亲密。
记得吗,你最爱的歌,让我再唱起。让我们相遇,要悄悄告诉你,多爱你。

*******************************************************************************************
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java ssh2 ganymed
相关文章推荐