使用python或bash自动安装Docker和镜像

我试图自动化安装docker-engine的过程,然后询问用户是否想要拉rhel / suse / centos映像。

使用python是我的第一个想法,但我已经添加bash脚本来使事情变得更容易,python似乎不太友好,运行cli命令。

现在,我打算扩展function和shell脚本不会扩展。 如何将此脚本转换为Python? 许多常见的命令行操作,比如“yum install”等等,都不容易使用额外的python导入。

如果您有更简单的build议,请咨询

谢谢!

这是bash脚本仍在工作中…

#!/bin/sh if [ "$(id -u)" != "0" ]; then echo "This script must be run as root" 1>&2 exit 1 fi echo echo " - Installing packages" echo if [[ -e /usr/bin/yum ]]; then #Verify packages are up to date yum update #Install Docker yum install docker-engine else echo "No yum, lets try apt-get" sudo apt-get update #sudo apt-get -y upgrade #sudo apt-get install linux-image-extra-`uname -r` #sudo apt-get install docker-engine fi if [ $? -eq 0 ]; then echo success else echo failed exit fi #start Docker echo "Would you like to start Docker and pull Images? Select 1 or 2" select y1 in "Yes" "No"; do case $y1 in Yes ) service docker start; docker pull "rhel:7.2" ;docker pull "mstormo/suse" ;break;; No ) exit;; esac echo " - Complete!" echo done 

好的,所以我能够使它在Python中工作。 我会在这里留下代码,以防万一需要。

干杯! 罗希特

 from subprocess import Popen, PIPE uid = Popen(['id', '-u'], stdin=PIPE, stdout=PIPE, stderr=PIPE) uid_get = uid.stdout.read(1) if uid_get != '0': print "This script needs to be run as root" print " - Installing packages " check1 = Popen(['/usr/bin/yum'], stdin=PIPE, stdout=PIPE, stderr=PIPE) check_yum = check1.stdout.read() if check_yum == ' ': print "Yum is not found, trying apt-get" proc = Popen('apt-get update', shell=True, stdin=None, executable="/bin/bash") proc.wait() proc = Popen('apt-get upgrade', shell=True, stdin=None, executable="/bin/bash") proc.wait() proc = Popen('apt-get install', shell=True, stdin=None, executable="/bin/bash") proc.wait() proc = Popen('apt-get install docker-engine', shell=True, stdin=None, executable="/bin/bash") proc.wait() else: print "Running yum install" proc = Popen('yum update', shell=True, stdin=None, executable="/bin/bash") proc.wait() proc = Popen('yum install docker-engine', shell=True, stdin=None, executable="/bin/bash") proc.wait() print "Would you like to start Docker and pull images - RHEL and SUSE? -> y or n ?" y="yes" n="no" choice = raw_input().lower() if choice in y: print "Pulling RHEL and SUSE images" proc = Popen('service docker start; docker pull "rhel:7.2" ;docker pull "mstormo/suse" ; docker run rhel sh -c "cat /etc/*release"; docker run "mstormo/suse" sh -c "cat /etc/*release"', shell=True, stdin=None, executable="/bin/bash") proc.wait() elif choice in n: print "Thank you, exiting...." else: print " Invalid selection" print " - Complete! " 

我会build议尝试sh模块:

 from sh import docker for line in docker('build', '-t', some_tag, '.', _iter=True): sys.stdout.write(str(line)) 

这是一个长时间运行的命令,所以很好地显示其逐行输出。 这是for loop_iter所做的。