使用 SSH“exec"执行 sudoJSch 中的频道 [英] Executing sudo using SSH "exec" channel in JSch
问题描述
我正在使用我在其中传递以下命令的文件:
I am using file in which I passed below commands:
主机名
密码
pbrun su - fclaim
whoami
cd ..
密码
在下面添加 Java 代码:
Ad the Java code below:
for (String command1 : commands) {
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command1);
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.println(new String(tmp, 0, i));
}
if(channel.isClosed()){
break;
}
}
channel.setInputStream(null);
channel.disconnect();
}
但我得到了这个输出:
- 一些主机名
/home/imam
- 缺少输出
伊玛目
- 缺少输出
/home/imam
推荐答案
您的代码在隔离的环境中执行每个命令.所以你的第二个 whoami
并没有像你希望的那样在 pbrun su
中运行.
Your code executes each command in an isolated environment. So your second whoami
does not run within pbrun su
, as you probably hoped for.
pbrun su
执行一个新的 shell.
The pbrun su
executes a new shell.
要向 shell 提供命令,您可以:
To provide a command to the shell you either:
在
su
命令行上指定命令,例如 官方 JSchSudo.java
示例 显示:
specify the command on
su
command-line, like the official JSchSudo.java
example shows:
((ChannelExec)channel).setCommand("pbrun su - fclaim -c whoami");
或使用标准输入将命令提供给 shell:
or feed the command to the shell using its standard input:
OutputStream out = channel.getOutputStream();
out.write(("whoami
").getBytes());
另见:
在sudo登录后使用Java JSch程序执行多个bash命令和
sudo 登录后运行命令.
总的来说,我推荐第一种方法,因为它使用定义更好的 API(命令行参数).
In general, I recommend the first approach as it uses a better defined API (command-line argument).
这篇关于使用 SSH“exec"执行 sudoJSch 中的频道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!