- 使用ChannelShell
(ChannelShell) session.openChannel("shell");
- 如果因为返回信息太多,返回的是more,没有返回全部,则发送一个空格过去即可;
if (s.indexOf("--More--") >= 0 ) {
os.write((" ").getBytes());
os.flush();
}
全部代码如下:
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public class JSchDemo {
Logger logger = null;
private String charset = "UTF-8"; //
private String user; //
private String passwd; //
private String host; //
private JSch jsch;
private Session session;
String path = null;
String retn = null;
public JSchDemo(String user, String passwd, String host) {
this.user = user;
this.passwd = passwd;
this.host = host;
this.path = getClass().getResource("/").getFile().toString();
PropertyConfigurator.configure(path + File.separator + "log4j.properties");
System.out.println("Init JSchDemo....");
this.logger = Logger.getLogger(JSchDemo.class);
}
public static void main(String[] args) throws Exception {
String host= args[0];
int port= Integer.valueOf(args[1]) ;
String user= args[2];
String password= args[3];
String command1="ls -ltr";
JSchDemo demo = new JSchDemo(user, password, host);
System.out.println(demo.path);
try{
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session=jsch.getSession(user, host, port);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected");
demo.logger.debug("Connected");
ChannelShell channel=(ChannelShell) session.openChannel("shell");
InputStream in = channel.getInputStream();
channel.setPty(true);
channel.connect();
OutputStream os = channel.getOutputStream();
os.write((command1 + "\r\n").getBytes());
os.flush();
byte[] tmp=new byte[1024];
while(true){
while(in.available()>0){
int i=in.read(tmp, 0, 1024);
if(i<0)break;
String s = new String(tmp, 0, i);
if (s.indexOf("--More--") >= 0 ) {
os.write((" ").getBytes());
os.flush();
}
System.out.print(s);
demo.logger.debug(s);
}
if(channel.isClosed()){
System.out.println("exit-status: "+channel.getExitStatus());
demo.logger.debug("exit-status: "+channel.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
os.close();
in.close();
channel.disconnect();
session.disconnect();
System.out.println("DONE");
demo.logger.debug("DONE");
}catch(Exception e){
e.printStackTrace();
}
}
}
附上ssh rfc地址:
ssh rfc