Thursday, April 30, 2015

Impersonating a process on Linux

That's a short tip, but I would like to came across with it in the past earlier. It would avoid me having to put a lot of effort to do the same thing.

Sometimes, for a reason or another, you want to execute a program on Linux with a different set of environment variables set. This program might be using complex and/or hidden configurations that will you need to find and reproduce in order to execute the program properly.

The thing is, if you already have a instance of this program already running, /proc will do that for you easily. This is one of the possible implementations, with a good help from xargs:

xargs --null --max-args=1 echo export < /proc/${PID}/environ > "${temp_file}"
source "$temp_file"
rm -v "$temp_file"

In this Bash script, I setup a temporary file to hold the environment configuration.

Then the script reads /proc/${PID}/environ, where ${PID} is the variable holding the process id that you're interested with.

This directory of /proc will hold every environment variable set for that process, separated by the NUL character. xargs will happily parse every entry in a loop, generating a single export <variable> for each item retrieved. And everything goes redirected to that temporary file.

That's it! No need to search around configuration files and/or debugging shell scripts to setup those variables. If the configuration is working for the program, it will certainly work for you too.

No comments:

Post a Comment