1

I'm trying to run commands via JSch. I can run standard commands such as ls. But if I need to run our commands let's say abc <param> it reruns me

ksh: abc: not found

I tried to use ((ChannelExec)channel).setPty(true);, but it still wouldn't work.

My channel set up looks like this:

Channel channel=session.openChannel("exec");
((ChannelExec)channel).setPty(true);

((ChannelExec)channel).setCommand(fullCommand);

channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);

InputStream in=channel.getInputStream();
channel.connect();
byte[] tmp=new byte[1024];
while(true){
    while(in.available()>0){
        int i=in.read(tmp, 0, 1024);
        if(i<0)break;
        System.out.print(new String(tmp, 0, i));
    }
    if(channel.isClosed()){
        System.out.println("exit-status: "+channel.getExitStatus());
        break;
    }
    try{Thread.sleep(1000);}catch(Exception ee){}
}

How can I make my custom commands and aliases work with JSch?

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Vladimir Zaguzin
  • 191
  • 5
  • 22

1 Answers1

2

The simplest way is to make your custom 'commands' scripts instead of aliases (or functions). Scripts work with all shell modes, and all shells, and also non-shell things like find xargs nohup nice.

If you must have an alias, and given you are using a pty, it should work to explicitly run ksh in interactive mode. For a (very) simple command as you showed, you can just use "ksh -i -c abc" as the command and make sure the alias is in ~/.kshrc. (ksh allows the nonlogin rc to be elsewhere using envvar ENV, but passing envvars through ssh is often prohibited or restricted for security.) However, if you need a more complex command with arguments, especially if they (need to) contain whitespace or special character(s) like quotes, dollar, backquote or backslash, figuring out what to use as the -c argument that results in ksh executing the correct command may become quite difficult, especially if you also need to express it in Java source as a string literal (i.e. not from a file or database or envvar etc).

dave_thompson_085
  • 34,712
  • 6
  • 50
  • 70