Use JSch sudo example and Channel.setPty for running sudo command on remote host

别来无恙 提交于 2019-11-27 08:59:39

I have similar code in a project I am working on, and was getting the same error. I resolved this using the setPty(true) as you did.

I think you're getting this error because you don't close out the streams in your code. If you are using Java 1.7, you can use a resource block as follows:

try( InputStream in=channel.getInputStream() ) {
    try( OutputStream out = channel.getOutputStream() ) {
    ...
    }
}

or the try...finally block pattern from past versions.

After setting

((ChannelExec) channel).setPty(true)

the reported problem have in my code got solved.

By default, SUDO is configured to require a TTY. That is, SUDO is expected to be run from a login shell.

That's probably because your /etc/sudoers file (or any file it includes) has:

Defaults requiretty

But the option -S in sudo will make it read from Standard input.

-S    The -S (stdin) option causes sudo to read the password from
      the standard input instead of the terminal device.  The pass-
      word must be followed by a newline character.

Jsch exploits the same and tries to send the password. If you want to Jsch to work without prompting the password , you need to disable the requiretty from the sudoers file...using visudo command as follows

Defaults !requiretty

or

#Defaults requiretty
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!