`
csyqbtlsz
  • 浏览: 23767 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

使用SSH连接LINUX

    博客分类:
  • Java
阅读更多

最近项目上决定使用华为的NAS,不得不说,华为的NAS照NetApp比起来,差距还是挺大的,至少NetApp提供了非常全面的各种语言实现的API,而且文档也非常的全面,可以非常容易的嵌入我们的系统中。而华为只有可怜的N8000命令行,并没有提供任何语言实现的API,这无疑给开发带来了很大的麻烦。最后商议决定,程序通过SSH协议远程执行华为的命令行。上网上简单看了一下,比较出名的第三方开源框架是JSCH,虽然网上已经有很多文章说明此框架的用法,但是在开发过程中仍然有一些小细节需要注意,特此Share一下,代码如下:

 

 

JSch jsch = new JSch();
String command = "storage pool free";
String host = "10.121.43.7";
String name = "master";
int port = 22;
String password = "!Q@W#E$R%T";
Session session = jsch.getSession(name,host, port);
Properties config = new Properties(); 
//设置不做检查
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
//设置密码
session.setPassword(password);
session.connect();
ChannelExec shell = (ChannelExec)session.openChannel("exec");
shell.setEnv("SFS_OUTPUT","xml");
shell.setCommand(command);
shell.connect();
InputStream inputStream = shell.getInputStream();
int index = -1;
byte[] buffer = new byte[1024];
ByteArrayOutputStream out = new ByteArrayOutputStream();
while(!shell.isClosed()){
	while((index = inputStream.read(buffer, 0, buffer.length))!=-1){
		out.write(buffer, 0, index);
	}
	try {
            Thread.sleep(500);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
}
out.flush();
out.close();
inputStream.close();
shell.disconnect();
session.disconnect();
String resultXml = new String(out.toByteArray());
System.out.println(resultXml);

 需要注意的是代码的第十六行,此参数用于设置SSH协议的环境,华为的存储这点就比较恶心,如果不设置这个变量,那么默认给你返回的是文本,而不是XML,当初在这个位置上卡了好久,希望日后能方便众人。

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics