1

I need to create one text file with some content from Mac OS terminal after sudo using java code. I am trying some code like below, but it throws "Execute sudo cat: Too1234.txt: No such file or directory exit-status: 1 Sudo disconnect"

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");
   }
  • I have tried as mentioned in that post, which is not working for me. May be because I had to sudo user and create file. – sagar konam Apr 07 '20 at 06:01
  • I am getting error "bash: copy: command not found" , what i have to give in place of this channelExec.setCommand("copy run tftp : "); – sagar konam Apr 07 '20 at 06:19
  • I didn't tell you to do `channelExec.setCommand("copy run tftp : ");` – That's the code from the question, which obviously does not work (that's why the OP was asking the question). Check the answer. – And do not use `copy`. Use your commands. – Martin Prikryl Apr 07 '20 at 06:25

1 Answers1

-1

My issue is resolved by this post https://ispycode.com/Java/JCraft/JSch/ChannelShell-Example Here I have used (ChannelShell) session.openChannel("exec") instead of (ChannelShell) session.openChannel("shell");