Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #52285

Re: Using sudo to write to a file as root from a script

From Dennis Lee Bieber <wlfraed@ix.netcom.com>
Subject Re: Using sudo to write to a file as root from a script
Date 2013-08-09 19:47 -0400
Organization IISS Elusive Unicorn
References <CA+mfgz3N9++VxoxkPMakMCw7tcYbhPDgpXVtX1mnm5sZy5_xTg@mail.gmail.com> <CAMPXz=pw+DBreoxe5NgHYpoFPHTJJYNE4uaisizj_LOT6hQYtw@mail.gmail.com> <CA+mfgz1CZzUXc3DKmCwNECPLJe1GBrxqkU+WX=sN34p-z7Q_1A@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.413.1376092036.1251.python-list@python.org> (permalink)

Show all headers | View raw


On Fri, 9 Aug 2013 08:21:22 -0500, Adam Mercer <ramercer@gmail.com>
declaimed the following:

>On Thu, Aug 8, 2013 at 11:47 PM, David <bouncingcats@gmail.com> wrote:

>import subprocess
>import sys
>
>channel='stable'
>config_file='/opt/ldg/etc/channel.conf'
>command="echo -n %s | sudo tee %s > /dev/null" % (channel, config_file)
>
>try:
>  retcode = subprocess.call(command, shell=True)
>  if retcode < 0:
>    sys.exit('Error: Failed to set channel.conf')
>except OSError as e:
>  sys.exit('Error: Execution failed "%s"' % e)
>
>But I was under the impression that Popen was the preferred approach
>to running external processes?
>

	It is... But you have to consider that you are attempting to run two
processes with one invocation...

	You need two subprocess calls, one for the sudo and one for the echo,
and you need to take the output of the echo process and feed it to the
input of the sudo process.

	Something like (UNTESTED):

sudo = subprocess.Popen("sudo tee %s" % config_file, 
							stdin=subprocess.PIPE,
							stdout=subprocess.PIPE)
echo = subprocess.Popen("echo -n %s" % channel,
							stdin=None,
							stdout=subprocess.PIPE)

sudo.communicate(echo.communicate[0])


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
    wlfraed@ix.netcom.com    HTTP://wlfraed.home.netcom.com/

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Using sudo to write to a file as root from a script Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2013-08-09 19:47 -0400

csiph-web