python中commands模块,结合linux ssh命令。
如给远程主机批量安装yum包:
#-*- coding: UTF-8 -*-
import subprocess
import sys
import commands
class client(object):
def __init__(self):
self.linux_list = ['root@10.101.108.100', 'root@10.125.8.60', 'root@10.125.7.133', 'root@10.101.104.59', 'root@10.125.14.139', 'root@11.239.191.229','root@11.239.191.239','root@100.81.144.40']
def make_commands(self, command, role):
commands = []
for i in role:
cmd = 'ssh %s "%s"' % (i, command)
commands.append(cmd)
return commands
def install_yum(self):
install_command = "yum -y install lrzsz -b test"
commands=self.make_commands(install_command, self.linux_list)
for i in commands:
print i
self.do_command(i)
def do_command(self, command):
if not isinstance(command, list):
command = [command]
p = subprocess.Popen(command,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE, shell=True)
stdout, stderr = p.communicate()
return stdout, stderr
client().install_yum()