1

In the following code snippet (meant to work in an init.d environment) I would like to execute test.ClassPath. However, I'm having trouble setting and passing the CLASSPATH environment variable as defined in the user's .bashrc.

Here is the source of my frustration:

  • When the below script is run in use mode, it prints out the CLASSPATH OK (from $HOME/.bashrc)
  • when I run it as root, it also displays CLASSPATH fine (I've set up /etc/bash.bashrc with CLASSPATH)
  • BUT when I do "sudo script.py" (to simulate what happens at init.d startup time), the CLASSPATH is missing !!

The CLASSPATH is quite large, so I'd like to read it from a file .. say $HOME/.classpath

#!/usr/bin/python import subprocess import os.path as osp import os user = "USERNAME" logDir = "/home/USERNAME/temp/" print os.environ["HOME"] if "CLASSPATH" in os.environ: print os.environ["CLASSPATH"] else: print "Missing CLASSPATH" procLog = open(osp.join(logDir, 'test.log'), 'w') cmdStr = 'sudo -u %s -i java test.ClassPath'%(user, ) # run in user proc = subprocess.Popen(cmdStr, shell=True, bufsize=0, stderr=procLog, stdout=procLog) procLog.close() 

2 Answers 2

4

sudo will not pass environment variables by default. From the man page:

 By default, the env_reset option is enabled. This causes commands to be executed with a minimal environment containing TERM, PATH, HOME, MAIL, SHELL, LOGNAME, USER and USERNAME in addition to variables from the invoking process permitted by the env_check and env_keep options. This is effectively a whitelist for environment variables. 

There are a few ways of addressing this.

  1. You can edit /etc/sudoers to explicitly pass the CLASSPATH variable using the env_keep configuration directive. That might look something like:

    Defaults env_keep += "CLASSPATH" 
  2. You can run your command using the env command, which lets you set the environment explicitly. A typical command line invocation might look like this:

    sudo env CLASSPATH=/path1:/path2 java test.ClassPath 

The obvious advantage to option (2) is that it doesn't require mucking about with the sudoers configuration.

Sign up to request clarification or add additional context in comments.

2 Comments

I sudo while calling the script to simulate what happens when init.d calls this script. So, how can I apply this idea at init.d time?
I'm not sure I understand your question. I've suggested how to make your existing script work using the env command. I think this will do what you want. If that doesn't meet your requirements, please update your question (rather than turning this into a giant comment thread) to indicate how the behavior you want differs from the behavior you get using this suggestion.
1

You could put source ~/.bashrc before starting your python script to get the environment variables set.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.