sudo登录后运行命令 [英] Running command after sudo login

查看:157
本文介绍了sudo登录后运行命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行下面的代码来执行 sudo 命令,但我不知道在 sudo login

I'm trying to execute below code to execute sudo commands but I do not know how execute commands after sudo login

String[] commands = {"sudo su - myname;","id"};
JSch jsch = new JSch();
String username = "myuser";
com.jcraft.jsch.Session session = 
        jsch.getSession(username,"hostname", 22);
session.setPassword("my@123");
session.connect();
Channel channel=session.openChannel("exec");
for(int a=0;a<=commands.length;a++){
    ((ChannelExec)channel).setCommand("sudo su - myname;");
    ((ChannelExec)channel).setErrStream(System.err);
    ((ChannelExec) channel).setPty(true);
    channel.connect();
    System.out.println("id *******");
    OutputStream out=channel.getOutputStream();
    out.write(("my@123\n").getBytes());
    out.flush();
    InputStream in=channel.getInputStream();
    byte[] tmp=new byte[1024];
    while(true){
        while(in.available()>0){
            int i=in.read(tmp, 0, 1024);
            if(i<0)break;
            System.out.print(new String(tmp, 0, i));
        }
        if(channel.isClosed()){
            System.out.println("exit-status: "+channel.getExitStatus());
            break;
        }
    }
}


推荐答案

sudo su 执行一个新shell。

The sudo su executes a new shell.

要向shell提供命令,您可以:

To provide a command to the shell you either:


  • su 命令行中指定命令,如< a href =http://www.jcraft.com/jsch/examples/Sudo.java.html\"rel =nofollow noreferrer>官方JSch Sudo.java 示例显示:

  • specify the command on su command-line, like the official JSch Sudo.java example shows:

((ChannelExec)channel).setCommand("sudo -S -p '' "+command);


  • 或使用标准输入将命令提供给shell,即提供的方式与提供的方式相同密码:

  • or feed the command to the shell using its standard input, i.e. the same way you provide the password:

    out.write(("command\n").getBytes());
    

    另见在sudo登录后使用Java JSch程序执行多个bash命令

    一般情况下,我建议第一种方法,因为它使用更好定义的API(命令行参数)。

    In general, I recommend the first approach as it uses a better defined API (command-line argument).

    这篇关于sudo登录后运行命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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