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

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

问题描述

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

I am using file in which I passed below commands:

  1. hostname
  2. pwd
  3. pbrun su - fclaim
  4. whoami
  5. cd ..
  6. pwd
  1. hostname
  2. pwd
  3. pbrun su - fclaim
  4. whoami
  5. cd ..
  6. 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();
}

但是我得到以下输出:

  1. 某些主机名
  2. /home/imam
  3. 缺少输出
  4. imam
  5. 缺少输出
  6. /home/imam
  1. some hostname
  2. /home/imam
  3. missing output
  4. imam
  5. missing output
  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.

要向外壳提供命令,您可以:

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\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屋!

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