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

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

问题描述

我正在尝试执行以下代码来执行 sudo 命令,但我不知道 sudo 登录后如何执行命令

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
").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:

  • 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
    ").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天全站免登陆