Parse only given values to command line via Python
<p>I'm sending I'm receiving a JSON message through MQTT in Python, and I would like to start a command line program with what the JSON gives as variables.</p>

<p>The problem with this is that I don't know what values are going to come through and thus this is where I have trouble.</p>

<p>The easiest would be if I knew all the variables that would come through and do something like this:</p>

<pre><code>data = json.loads(msg.payload)
os.system("'command +f ' + data[arg1] + ' +g ' + data[arg2]")
</code></pre>

<p>But as mentioned previously, I don't know if they are being passed through, and as such, how can I break it down so that the command line command is build up?</p>

<p>Maybe:</p>

<pre><code>    if 'arg1' in data:
            command = "+f " + data[arg1]
    else:
            pass
    if 'arg2' in data:
            command + "+g " + data[arg2]
    else:
            pass
</code></pre>

<p>Would this work? Is there a better idea?</p>

<p>Although you <em>could</em> do this as described it's not something you <em>should</em> do.  Running user-inputted commands is one of the most unsecure things a program can do.  Scrubbing the commands thoroughly is possible but quite difficult to do comprehensively.  The usual approach is to have a table of acceptable commands, match against the table, and then use the entries <em>from that table</em> to populate the command line.  Nothing typed by the user ever makes it into the command line with that method.  </p>

<p>If you do wish to take user input directly, be extremely careful about scrubbing <em>all</em> special characters, characters outside your preferred locale, double-byte characters, path delimiter characters, etc.  Perhaps you could start with the snippet Jeff provided and add a lot of data scrubbing code.</p>

<p>Also, be aware that the probability that whatever you do not code for will eventually be submitted for processing corresponds roughly to the risk of that command.  For example, if you fail to catch and remove <code>cat ~/.ssh/*</code> there's a moderately good chance one of your users will execute it or someone will break in and do so.  But if you do not catch and remove <code>rm -r /*</code> the chance someone will submit <em>that</em> command approaches certainty.</p>

python json mqtt