简体   繁体   English

执行需要来自Java(NetBeans)的root权限的bash脚本

[英]Execute bash script that need root permission from java(netbeans)

My new problem is execute bash shell script that ask for sudo permission in java. 我的新问题是执行Java中要求sudo权限的bash shell脚本。 What i want to do i exporting ds-389 database into ldif format using command line this is done with ns-slapd db2ldif command. 我要执行的操作是使用ns-slapd db2ldif命令将ds-389数据库导出为ldif格式。 Here is my java simple code in main for doing this: 这是我这样做的主要Java简单代码:

ProcessBuilder p = new ProcessBuilder("/bin/bash", "example.sh");
final Process process = p.start();

where example.sh is located in project dir and there is no problem with accessing it. 其中example.sh位于项目目录中,对其进行访问没有问题。 I also add permission to script to execute with chmod 777 to be sure. 我还为脚本添加了权限,以确保可以使用chmod 777执行。 Example.sh have only this: Example.sh仅具有:

#!/bin/bash
ns-slapd db2ldif -D /etc/dirsrv/slapd-localhost -n userRoot -s "ou=Group,dc=localdomain" -a /tmp/file.ldif

What i try so far is adding with visudo this lines: 我到目前为止尝试的是使用visudo添加以下行:

nobody ALL=(ALL) NOPASSWD: /usr/sbin/ns-slapd
myUSER ALL=(ALL) NOPASSWD: /usr/sbin/ns-slapd
root ALL=(ALL) NOPASSWD: /usr/sbin/ns-slapd 
bin ALL=(ALL) NOPASSWD: /usr/sbin/ns-slapd 
myUSER ALL = NOPASSWD: /usr/bin/java 
root ALL= NOPASSWD: /usr/bin/java 
nobody ALL= NOPASSWD: /usr/bin/java 
bin ALL= NOPASSWD: /usr/bin/java

but there is no result.. and yes this change allow me to execute example.sh without asking me password, but in command line. 但是没有结果..是的,此更改使我可以在不询问密码的情况下在命令行中执行example.sh。 When i try this from java it doesn't work and there is no created file.ldif in /tmp. 当我从Java尝试此操作时,它不起作用,并且/ tmp中没有创建的file.ldif。 Every help is welcomed. 欢迎每一个帮助。 Thanks for your time :) 谢谢你的时间 :)

Try to use sudo -S -p . 尝试使用sudo -S -p

other way I used JSch class located in jsch-0.1.38.jar . 以其他方式,我使用了位于jsch-0.1.38.jar JSch类。

The idea is to redirect sudo input from console to java code. 这个想法是将sudo输入从控制台重定向到Java代码。

SudoExec class SudoExec类

public abstract class SudoExec {

private String mHost;
private static String passwd;
private SSHObserverItf mObserver = null;
protected boolean isForceStop = false;
protected boolean isAsIs = false;
protected Timer mTimer = null;



//default constructor
public SudoExec(String hostName,String userName,String password){
    setHost(userName+"@"+hostName);
    setPassword(password);
}

public void init(int timeToWait) {

    mTimer = new Timer();


    new Thread(){       
        public  void run(){
            execCMD();
        }           
    }.start();

    mTimer.doWait(timeToWait);

    isForceStop = true;
}


private void execCMD (){

    isForceStop = false;        

    try{
        JSch jsch=new JSch();  

        String host=getHost();


        String user=host.substring(0, host.indexOf('@'));
        host=host.substring(host.indexOf('@')+1);

        Session session=jsch.getSession(user, host, 22);



        // username and password will be given via UserInfo interface.
        UserInfo ui=new MyUserInfo();
        session.setUserInfo(ui);
        session.connect();

        String command=getCmd();

        Channel channel=session.openChannel("exec");

        ((ChannelExec)channel).setPty(true);

        if(isAsIs == true){
            ((ChannelExec)channel).setCommand(command);
            }
        else{
            ((ChannelExec)channel).setCommand("sudo -S -p '' " + command);
        }

        InputStream in=channel.getInputStream();
          OutputStream out=channel.getOutputStream();
          ((ChannelExec)channel).setErrStream(System.err);

          channel.connect();

          out.write((passwd+"\n").getBytes());
          out.flush();

        byte[] tmp=new byte[1024];
        while(true && isForceStop == false){                
            while(in.available()>0 ){
                int i=in.read(tmp, 0, 1024);
                if(i<0)break;

                mObserver.onResponse((new String(tmp, 0, i)));

            }
            if(channel.isClosed()){
                mObserver.onResponse("exit-status: "+channel.getExitStatus());
                mTimer.doNotify();
                break;
            }


            try{Thread.sleep(100);}catch(Exception ee){}
        }

        mObserver.onResponse("close channel ... ");         
        channel.disconnect();
        mObserver.onResponse("close session ... ");
        session.disconnect();
    }
    catch(Exception e){
        System.out.println(e);
        mObserver.onErrorResponse(e.getMessage());
    }



}



public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
    public String getPassword(){
        return passwd;
    }

    public boolean promptYesNo(String str){
        return true;
    }



    public String getPassphrase(){ return null; }
    public boolean promptPassphrase(String message){ return true; }
    public boolean promptPassword(String message){
        return true;
    }

    public void showMessage(String message){
    }

    @Override
    public String[] promptKeyboardInteractive(String arg0, String arg1,
            String arg2, String[] arg3, boolean[] arg4) {
        return null;
    }
}

public void setPassword(String password){
    passwd=password;
}

public void setHost(String hostname){
    mHost=hostname;
}

public String getPassword(){
    return passwd;
}


public String getHost(){
    return mHost;
}

protected abstract String getCmd();

public void setObserver(SSHObserverItf observer) {
    mObserver = observer;
}   
} 

SSHObserverItf interface SSHObserverItf接口

public interface SSHObserverItf {
public void onResponse(String line);
public void onErrorResponse(String line);
}

SomeTask SomeTask

public class SomeTask extends SudoExec implements SSHObserverItf{

private static String command = "";
private static String hostname = "";
private static String user = "";
private static String pass = "";
private static Boolean isError=false;

private static String wait = "300";



static public void main(String args[]) throws IOException, ParseException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {


    new SomeTask(hostname,user,pass);

    if (isError == true){
        System.out.println("Test failed");
    }   
    else{
        System.out.println("\nSucceeded to invoke command : " + command);
    }   

}



public CopyPeriodMergeToExternal(String hostName, String userName, String password) throws IOException, ParseException {

    super(hostName, userName, password);

    SSHObserverItf observer = this;

    super.setObserver(observer);

    super.init(Integer.parseInt(wait) * 1000);

}




@Override
protected String getCmd() {

    isAsIs = true;


    command="rm -f somescript.sh";


    System.out.println("Run followed command : " + command);

    return command;
}

@Override
public void onResponse(String line) {
    System.out.println(line);       
}

@Override
public void onErrorResponse(String line) {
    System.out.println(line);
    System.out.println("Error has occured");        
    isError = true;
}
}

The main part in SudoExec class is: SudoExec类的主要部分是:

public static class MyUserInfo implements UserInfo, UIKeyboardInteractive{
    public String getPassword(){ //     <---
        return passwd;
    }

    public boolean promptYesNo(String str){
        return true;  //     <---
    }

Hope it will solve your problem 希望它能解决您的问题

I solve problem with commenting line 我用评论线解决问题

Default requiretty 默认要求

using visudo. 使用visudo。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM