【发布时间】:2020-07-19 05:27:28
【问题描述】:
我需要在 sudo 使用 java 代码之后从 Mac OS 终端创建一个包含一些内容的文本文件。 我正在尝试一些类似下面的代码,但它会抛出“执行 sudo cat: Too1234.txt: 没有这样的文件或目录 退出状态:1 须藤断开”
public static void executeCommand() throws JSchException, IOException, Exception{
System.out.println("Execute sudo");
String sudo_pass = "pssword";
String line = "";
ChannelExec channel = (ChannelExec) session.openChannel("exec");
((ChannelExec)channel).setPty(true);
((ChannelExec) channel).setCommand("sudo -u username -i");
((ChannelExec)channel).setCommand("echo Hello world >Too1234.txt");
((ChannelExec) channel).setCommand("cat Too1234.txt");
InputStream in = channel.getInputStream();
OutputStream out = channel.getOutputStream();
((ChannelExec) channel).setErrStream(System.err);
channel.connect();
out.write((sudo_pass + "\n").getBytes());
out.flush();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0)
break;
line = new String(tmp, 0, i);
System.out.print(line);
}
if (channel.isClosed()) {
System.out.println("exit-status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
System.out.println(ee);
}
}
channel.disconnect();
System.out.println("Sudo disconnect");
}
【问题讨论】:
-
我已经尝试过该帖子中提到的,这对我不起作用。可能是因为我必须 sudo 用户并创建文件。
-
我收到错误 "bash: copy: command not found" ,我必须给出什么来代替这个 channelExec.setCommand("copy run tftp : ");
-
我没有告诉你这样做
channelExec.setCommand("copy run tftp : ");- 这是问题中的代码,显然不起作用(这就是 OP 问这个问题的原因)。检查答案。 – 并且不要使用copy。使用你的命令。