Search code examples
pythonlinuximaplsos.system

Using os.system() in python to execute linux command


I use script in python to fetching mails from Postfix server. This script fetches mails, removes headers and leaves only body of email. Then it uses this body to execute linux command by os.system(). For example I'm sending email with mkdir folder and script creates this.

Problem was when I was sending ls by mail. I've got response : not found ls

Second problem is with mkdir cause it adds ^M to name from email. For example I sent mkdir folder and it created "folder?".

Do you have any ideas ?


Solution

  • You've already identified the problem: the emails have ^M characters in them that you're not expecting. (CR LF is a common line ending convention; Unix usually does not like the CR).

    Try removing "\r" from your command: command = command.translate(None, "\r").

    I also urge you to carefully consider the security implications of running whatever commands are delivered by email. There is likely a much safer way to do what you're trying to accomplish.