1,这段JSch链接Linux的代码可以实现交互,即当输入su的时候,可以继续读下一行命令,将密码输入进去
2,想请问各位,如何记录linux的回显,谢谢各位了,想了很多办法没有找到方法
public class MyShell {
static String user = "xxxx";
static String host = "xxxx";
static int port = 22;
static String password = "xxxx";
static Session session;
static Channel shellChannel;
static PrintStream shellStream;
static InputStream in;
public static void main(String[] args) throws JSchException, IOException,
InterruptedException {
JSch jsch = new JSch();
jsch.removeAllIdentity();
session = jsch.getSession(user, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.setConfig("PubkeyAuthentication", "no");
System.out.println("Establishing Connection...");
session.setConfig("PreferredAuthentications",
"publickey,keyboard-interactive,password");
session.connect();
System.out.println("Connection established.");
System.out.println("Crating SFTP Channel.");
shellChannel = session.openChannel("shell");
shellChannel.connect();
((ChannelShell) shellChannel).setPty(true);
shellChannel.setInputStream(System.in);
in = shellChannel.getInputStream();
shellChannel.setOutputStream(System.out);
shellStream = new PrintStream(shellChannel.getOutputStream());
Thread.sleep(1000);
sendCommand("su - root");
Thread.sleep(1000);
sendCommand("QAZ2wsx@123!");
Thread.sleep(1000);
sendCommand("whoami");
Thread.sleep(1000);
sendCommand("exit");
session.disconnect();
}
public static void sendCommand(String c) throws IOException {
shellStream.print(c + "\n");
shellStream.flush();
}
}
想知道如何得到linux的回显
那句 in = shellChannel.getInputStream(); 就是
读这个输入流就可以读到了
JSch 有会话的这种概念,从楼主贴出的代码来看,前后发两次命令,本质上就是两个会话的内容的。
建议调整一下思路,用 StringBuffer 拼接成一个完整的命令后,再统一 sendCommand 执行命令,这样命令集之前的前后文关系才能保存。
如果不理解,我再补充一点:一次发一条命令时,后一条的命令就与前一条命令直接没有关系了,因为会话不同了。所以需要用分号拼接成一个长的命令串。