使用 SSH“exec"执行 sudoJSch 中的频道 [英] Executing sudo using SSH "exec" channel in JSch

查看:17
本文介绍了使用 SSH“exec"执行 sudoJSch 中的频道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用我在其中传递以下命令的文件:

I am using file in which I passed below commands:

  1. 主机名
  2. 密码
  3. pbrun su - fclaim
  4. whoami
  5. cd ..
  6. 密码

在下面添加 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();
}

但我得到了这个输出:

  1. 一些主机名
  2. /home/imam
  3. 缺少输出
  4. 伊玛目
  5. 缺少输出
  6. /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:

  • specify the command on su command-line, like the official JSch Sudo.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屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆