gpt4 book ai didi

java - 使用 ChannelExec 的命令未执行 - Jsch

转载 作者:行者123 更新时间:2023-12-02 11:56:51 31 4
gpt4 key购买 nike

我正在使用 Jsch 在服务器中创建一个文件并执行一些命令。对于文件创建,它工作正常,但是对于命令执行,则不然。它保持状态-1(仍在处理它)并永远保持该状态。这种情况发生在 shell 执行或我尝试成为 root 时。请按照以下方法操作:

public void upload(String localPath) throws IOException {
Session session = connectToServer();
System.out.println("In upload");
ChannelSftp channelSftp = getChannelToSftpServer(session);

//Creating file in temporary location
File f = new File(localPath);
FileInputStream fi = new FileInputStream(f);

// Creating file on server and setting the permissions to the user (chmod 777)

if (channelSftp != null) {
try {
System.out.println("Change working in temp directory");
changeWorkingDirectory(channelSftp, TEMP_PATH);

ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
//THE PROBLEM ALSO HAPPENS WHEN EXECUTING A SHELL WITH THIS COMMAND INSIDE
channelExec.setCommand(
"root command (using pbrun) <command is here, confidential> ");
InputStream commandOutput = channelExec.getInputStream();
channelExec.connect();

StringBuilder outputBuffer = new StringBuilder();
int readByte = commandOutput.read();

while(readByte != 0xffffffff)
{
outputBuffer.append((char)readByte);
readByte = commandOutput.read();
System.out.println(outputBuffer);
}
System.out.println("Root connected.");
channelExec.disconnect();

channelSftp.put(fi, f.getName());
channelSftp.chmod(0777, localPath);
channelSftp.chown(123, localPath);
channelSftp.chgrp(123, localPath);

System.out.println("File configurations changed.");

//Copying to the official path
channelExec = (ChannelExec) session.openChannel("exec");
channelExec.setCommand("mv /tmp/"+f.getName()+" "+path);
channelExec.connect();
System.out.println("File is completed and ready!");

while (channelExec.getExitStatus() == -1) {
Thread.sleep(1000);

}
channelExec.disconnect();

} catch (SftpException e) {
e.printStackTrace();
throw new IOException(e.getStackTrace() + "");
} catch (JSchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
disconnectChanneltoSftpServer(channelSftp);
session.disconnect();
fi.close();
// Deletes the local File.
f.delete();
}
}
}

我做错了什么?预先感谢您。

最佳答案

在调用 connect() 之前,您必须先调用 getInputStream()

实际上,您最好阅读 stderr 和 stdout 来获取错误。
为此,请参阅我对 How to read JSch command output? 的回答

关于java - 使用 ChannelExec 的命令未执行 - Jsch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47539582/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com