lop*_*ael 4 java shell android jsch
我尝试使用库JSch - Java安全通道在我的Android应用程序中建立一个ssh连接,它的工作原理.
现在我想执行一个命令并检索结果.
我尝试了几种效果最好的方法.但是,这种方法只能部分工作,因为由于某些原因我无法解释,我的程序在我的while循环结束时停止,但我是我日志中出现的命令的结果.
这是我的代码:
public static String executeRemoteCommand(String username, String password, String hostname, int port) throws Exception {
JSch jsch = new JSch();
Session session = jsch.getSession(username, hostname, port);
session.setPassword(password);
// Avoid asking for key confirmation
Properties prop = new Properties();
prop.put("StrictHostKeyChecking", "no");
session.setConfig(prop);
session.connect();
Channel channel = session.openChannel("shell");
channel.connect();
DataInputStream dataIn = new DataInputStream(channel.getInputStream());
DataOutputStream dataOut = new DataOutputStream(channel.getOutputStream());
// send ls command to the server
dataOut.writeBytes("ls\r\n");
dataOut.flush();
// and print the response
String line = dataIn.readLine();
String result = line + "\n";
while ((line = dataIn.readLine()) != null) {
result += line + "\n";
Log.i("TAG", "Line: "+line);
}
dataIn.close();
dataOut.close();
channel.disconnect();
session.disconnect();
return result;
}
Run Code Online (Sandbox Code Playgroud)
有没有其他人有更好的方法来使用JSch运行命令剪切?
先感谢您 !
您的方法在循环中停止(而不是完成它),因为远程shell不会关闭输出流.它没有理由这样做,因为你可以发送更多的命令.
如果您只想执行单个命令(或之前已知的一系列命令),则不应使用Shell通道,而应使用"exec"通道.
这样,远程shell(执行命令)将在命令完成后完成,然后服务器将关闭流.所以你的循环将完成,然后你可以关闭流.
如果你认为你需要一个shell通道(例如,如果你需要在同一个上下文中启动多个命令,并在决定下一个输出之前对一个输出作出反应),你需要一些方法来知道命令完成(例如通过识别提示),然后发送下一个.要退出,要么关闭输出流,要么发送"logout"或"exit"命令(两者都可以使用任何标准的unix shell,其他shell可能需要不同的命令),那么远程站点也应该关闭另一个流.
顺便说一句,虽然禁用严格的主机密钥检查很方便,但它也会打开与中间人攻击的连接,并且在密码验证的情况下,攻击者可以获取您的密码.执行此操作的正确方法是设置正确初始化的主机密钥存储库以识别远程主机的密钥.