简体   繁体   English

从python作为sudo运行.sh脚本

[英]Run .sh script from python as sudo

I'm working on a project with python where I want to automate docker containers creation. 我正在使用python进行项目,我想自动创建docker容器。 I have the project folder already with includes all the files required to create the image. 我的项目文件夹已经包含创建映像所需的所有文件。

One of these is create_image.sh 其中之一是create_image.sh

docker build -t my_container:latest .

Currently I do: 目前,我正在:

sudo bash create_image.sh

But now I need to automate this process from python. 但是现在我需要从python自动化该过程。 I have tried: 我努力了:

import os
import subprocess
subprocess.check_call("bash -c '. create_image.sh'", shell=True)

But I get this error: 但是我得到这个错误:

CalledProcessError: Command 'bash -c '. create_image.sh'' returned non-zero exit status 1.

EDIT: 编辑:

The use case is to automate containers creation through an API, I have the code in flask and python until this point, where I got stuck in the images creation from the docker file. 用例是通过API自动进行容器创建,直到现在,我都将烧瓶和python中的代码保存在了其中,在这里我被困在docker文件中的映像创建中。 The rest is automated from templates. 其余的从模板自动执行。

You can try: 你可以试试:

subprocess.call(['sudo', 'bash', 'create_image.sh' ])

which is equivalent of 相当于

sudo bash create_image.sh

Note : Let me say that there are better ways of automating docker container creation - please check docker-compose which can build and start the container easily. 注意 :让我说有自动化docker容器创建的更好方法-请检查docker-compose可以轻松构建和启动容器。 If you can elaborate more on the use case, we could help you with an elegant solution for docker. 如果您可以详细说明用例,我们可以为您提供一个优雅的Docker解决方案。 It might not be a python problem 可能不是python问题

EDIT: Following the comments, it would be better to create a docker-compose and makefile is used to issue docker commands. 编辑:根据评论,最好创建一个docker-compose和makefile来发布docker命令。 Inspiration - https://medium.com/@daniel.carlier/how-to-build-a-simple-flask-restful-api-with-docker-compose-2d849d738137 灵感-https: //medium.com/@daniel.carlier/how-to-build-a-simple-flask-restful-api-with-docker-compose-2d849d738137

In case that's because your user can't run docker without sudo, probably it's better to grant him docker API access by including him to docker group: https://askubuntu.com/questions/477551/how-can-i-use-docker-without-sudo 万一这是因为您的用户无法在没有sudo的情况下运行docker,可能最好通过将他包括在docker组中来授予他docker API访问权限: https : //askubuntu.com/questions/477551/how-can-i-use-搬运工,无-须藤

Simply adding user to docker group: 只需将用户添加到docker组即可:

sudo gpasswd -a $USER docker

Also if You want to automate docker operations on python, I'd recommend to use python library for docker: How to build an Image using Docker API Python Client? 另外,如果您想在python上自动化docker操作,我建议对docker使用python库: 如何使用Docker API Python Client构建映像?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM