码迷,mamicode.com
首页 > 编程语言 > 详细

java 远程调用 shell

时间:2016-09-07 14:36:25      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:

import java.io.BufferedReader;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Properties;
import java.util.Scanner;
import java.util.Vector;

import org.apache.log4j.Logger;

import com.ecSolutions.ssm.persistence.SshConfiguration;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;

/**
* @author hadoop
*
*/
public class VersouSshUtil {

private ChannelSftp channelSftp;

private ChannelExec channelExec;

private Session session = null;

private int timeout = 60000;

private static final Logger LOG = Logger.getLogger(VersouSshUtil.class);

public VersouSshUtil(SshConfiguration conf) throws Exception
{
LOG.info("尝试连接到....host:" + conf.getHost() + ",username:" + conf.getUsername() + ",password:" + conf.getPassword() + ",port:" + conf.getPort());
JSch jsch = new JSch(); // 创建JSch对象
session = jsch.getSession(conf.getUsername(), conf.getHost(), conf.getPort()); // 根据用户名,主机ip,端口获取一个Session对象
session.setPassword(conf.getPassword()); // 设置密码
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config); // 为Session对象设置properties
session.setTimeout(timeout); // 设置timeout时间
session.connect(); // 通过Session建立链接
}
//远程调用shell
public ArrayList<String> runcommand(String command) {
File tmpfile = new File(System.getProperty("java.io.tmpdir")+"_cli_output_.log");
tmpfile.deleteOnExit();
ArrayList<String> results = new ArrayList<String>();
try {
Channel channel=session.openChannel("shell");
channel.setInputStream(new ByteArrayInputStream(command.getBytes()));
channel.setOutputStream(new FileOutputStream(tmpfile));
channel.connect();
Thread.sleep(10000);
channel.disconnect();
session.disconnect();
Scanner readtmpfile = new Scanner(tmpfile);
String rtnline;
while(readtmpfile.hasNext()) {
rtnline = readtmpfile.nextLine();
results.add(rtnline);
System.out.println(rtnline);
}
} catch (Exception e) {
e.printStackTrace();
}
return results ;
}

public void runCmd(String cmd, String charset)
{
Channel channel = null;
try {
//创建sftp通信通道
channel = (Channel) session.openChannel("shell");
channel.connect(1000);
//获取输入流和输出流
InputStream instream = channel.getInputStream();
OutputStream outstream = channel.getOutputStream();
//发送需要执行的SHELL命令,需要用\n结尾,表示回车
String shellCommand = cmd;
// shellCommand="ls \n";
shellCommand=cmd+" \n";
outstream.write(shellCommand.getBytes());
outstream.flush();
Thread.sleep(1000);
//获取命令执行的结果
if (instream.available() > 0) {
byte[] data = new byte[instream.available()];
int nLen = instream.read(data);
if (nLen < 0) {
throw new Exception("network error.");
}
//转换输出结果并打印出来
String temp = new String(data, 0, nLen,charset);
System.out.println(temp);
}
outstream.close();
instream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
session.disconnect();
channel.disconnect();
}
}

public void runCmd_old(String cmd, String charset , String filepath) throws Exception
{
ChannelSftp channelSftp = (ChannelSftp)session.openChannel( "sftp" );
Channel channel = (Channel) session.openChannel("shell");
channelSftp.connect();
channelSftp.setFilenameEncoding( charset );

UserInfo uInfo= new localUserInfo();
session.setUserInfo(uInfo);
channelExec = (ChannelExec)session.openChannel("exec");
channelExec.setInputStream(null);
channelExec.setErrStream(System.err);
channelExec.setCommand(cmd);
//channelExec.run();
channelExec.connect();
InputStream in = channelExec.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName(charset)));
String buf = null;
while ((buf = reader.readLine()) != null)
{
System.out.println(buf);
}
reader.close();
channelExec.disconnect();
channelSftp.disconnect();
}

public void close()
{
session.disconnect();
}

public class localUserInfo implements UserInfo {
String passwd;

public String getPassword() {
return passwd;
}

public boolean promptYesNo(String str) {
return true;
}

public String getPassphrase() {
return null;
}

public boolean promptPassphrase(String message) {
return true;
}

public boolean promptPassword(String message) {
return true;
}

public void showMessage(String message) {

}
}
}

java 远程调用 shell

标签:

原文地址:http://www.cnblogs.com/leiyf/p/5849185.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!