使用SSH"exec"执行sudo. JSch中的频道 [英] Executing sudo using SSH "exec" channel in JSch
问题描述
我使用的是我在其中传递以下命令的文件:
I am using file in which I passed below commands:
-
hostname
-
pwd
-
pbrun su - fclaim
-
whoami
-
cd ..
-
pwd
hostname
pwd
pbrun su - fclaim
whoami
cd ..
pwd
广告下面的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
- 缺少输出
-
imam
- 缺少输出
-
/home/imam
- some hostname
/home/imam
- missing output
imam
- missing output
/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.
要向外壳提供命令,您可以:
To provide a command to the shell you either:
-
在
su
命令行上指定命令,例如 JSch官方Sudo.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\n").getBytes());
另请参阅:
在sudo登录后使用Java JSch程序执行多个bash命令和
在sudo登录后运行命令.
See also:
Executing multiple bash commands using a Java JSch program after sudo login and
Running command after sudo login.
通常,我建议第一种方法,因为它使用了定义更好的API(命令行参数).
In general, I recommend the first approach as it uses a better defined API (command-line argument).
这篇关于使用SSH"exec"执行sudo. JSch中的频道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!