需要从Mac OS终端使用Java代码创建一个包含某些内容的文本文件

问题描述 投票:1回答:1

我需要使用Java代码在sudo之后从Mac OS终端创建一个包含某些内容的文本文件。我正在尝试以下类似的代码,但是会抛出“ Execute sudocat: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");
   }
java terminal jsch
1个回答
0
投票

此问题已解决我的问题https://ispycode.com/Java/JCraft/JSch/ChannelShell-Example在这里,我使用(ChannelShell)session.openChannel(“ exec”)而不是(ChannelShell)session.openChannel(“ shell”);

© www.soinside.com 2019 - 2024. All rights reserved.