java 间断执行多条命令ssh连接,有缺陷

废话不说直接上代码:

package com.guoru;


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


import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;






public class ShellUtils {
/**
* 创建session
* @param host 主机名称/ip地址
* @param user 登陆用户名
* @param psw  密码
* @param port 端口
* @return
*/
public static Session getSession(String host,String user,String psw,int port){
JSch jsch=new JSch();
Session session=null;
try {
session = jsch.getSession(user, host, port);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(psw);
session.connect();
} catch (JSchException e) {
System.out.println("连接linux主机失败");
e.printStackTrace();
}
return session;

}
/**
* 得到可以执行命令的连接
* @param session 连接session
* @return 可以执行命令的ChannelExec
*/
public static ChannelExec getChanel(Session session){
ChannelExec openChannel=null;
try {
if(null !=session){
openChannel = (ChannelExec) session.openChannel("exec");
}
} catch (JSchException e) {
e.printStackTrace();
}
return openChannel;
}
/**

* @param openChannel
* @param command
* @return
*/
public static String getExcRes(ChannelExec openChannel,String command){
InputStream in =null;
BufferedReader reader=null;
StringBuffer result=new StringBuffer();
try {
try {
openChannel.setCommand(command);
int exitStatus = openChannel.getExitStatus();
System.out.println(exitStatus);
openChannel.connect();
in = openChannel.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));
String buf = null;
while ((buf = reader.readLine()) != null) {
result.append(new String(buf.getBytes("gbk"),"UTF-8")+"
\r\n");  
}
//reader.close();
} catch (JSchException e) {
result.append(e.getMessage());
e.printStackTrace();
}  
} catch (IOException e) {
result.append(e.getMessage());
e.printStackTrace();
}  finally {
/*try {
//reader.close();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}*/
}
return result.toString();

}
public static void disConnect(Session session,ChannelExec openChannel){
if(session!=null&&!openChannel.isClosed()){
openChannel.disconnect();
}
if(session!=null&&session.isConnected()){
session.disconnect();
}
}
public static void main(String[] args) {
Session session=getSession("192.168.230.129", "请叫我大哥", "root", 22);
ChannelExec chanel=getChanel(session);
String res=getExcRes(chanel, "cd /home;ls;");
System.out.println(res);
ChannelExec chanel2=getChanel(session);
String ss=getExcRes(chanel2, "ls;");
System.out.println(ss);
}

}

这段代码有缺陷,有时候连接不到服务器,而且执行速度太慢,继续去寻找更好的代码和方法!

你可能感兴趣的:(linux,ssh,java,opensuse,suse)