首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我需要创建一个文本文件与一些内容从Mac OS终端与java代码

我需要创建一个文本文件与一些内容从Mac OS终端与java代码
EN

Stack Overflow用户
提问于 2020-04-07 12:40:28
回答 1查看 47关注 0票数 1

我需要创建一个文本文件与一些内容从Mac OS终端后sudo使用java代码。我正在尝试一些类似下面的代码,但它抛出"Execute sudo cat: Too1234.txt: No throws file or directory exit-status: 1 Sudo disconnect“

代码语言:javascript
复制
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");
   }
EN

回答 1

Stack Overflow用户

发布于 2020-04-14 15:53:02

我的问题在这篇文章中得到了解决,这里我使用了(ChannelShell) session.openChannel("exec")而不是(ChannelShell) session.openChannel(“session.openChannel”);

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61072949

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档