sudo and LD_LIBRARY_PATH … never the twain shall meet

While writing something for our operations support team to use when running a particular process, I found that sudo does not recognize a previously exported value for LD_LIBRARY_PATH. It also won’t use what is in the .bashrc or .profile for the user that owns the script being sudo’d. You also can’t use os.environ in python to set it, as that only affects processes spawned in python after startup, but not the parent process itself.

It looks like this is due to a security setting in sudo that strips LD_LIBRARY_PATH out of the environment.

Unless you want to set it system wide as in /etc/profile, or change /etc/ld.so.conf, you can write a here document for the python code inside a shell script that exports LD_LIBRARY_PATH first. This is what I did.

While not enormously inconvenient, the process of discovering this took me a couple of hours to track down.

Below is an example that will fail in sudo…

1
2
3
#!/home/oracle/local/bin
 
import cx_Oracle

…and one that will work…

1
2
3
4
5
6
#!/bin/sh
 
. /home/oracle/.bashrc #which contains an LD_LIBRARY_PATH export
/home/oracle/local/bin/python <<HERE
import cx_Oracle
HERE