最近刚学习python,用paramiko和multiprocessing模块写的一个批量命令和文件的管理程序,详见如下,有需要的小伙伴可以看看,欢迎指出不足,谢谢~
批量命令执行:
批量文件下发:
单个文件获取:
程序内容如下:
#! /usr/bin/python
#-*- coding: utf-8 -*-
import paramiko
import sys
import os
import re
import multiprocessing
''' 本程序需要一个iplist.txt文件,每行一个IP地址,并和此程序放同一目录下,还需要登陆机器的key文件,地址参数pkey_file可以修改成你需要的 '''
username = "root"
port = 22
pkey_file = '/root/key-1.pem'
key = paramiko.RSAKey.from_private_key_file(pkey_file)
def ssh2(ip,cmd):
''' 批量执行shell命令 '''
s = paramiko.SSHClient()
s.load_system_host_keys()
try:
s.connect(ip,port,username,pkey=key,timeout=5)
stdin,stdout,stderr = s.exec_command(cmd)
print "\033[32;2m",
print ip,":"
print stdout.read(),stderr.read(),
print "\033[0m"
s.close()
except:
print "\033[31;2m"
print ip,":"
print "出现连接问题",
print "\033[0m"
def sftp_put(localpath,ip,remotepath):
''' 传送本机文件到其他服务器支持一台或多台 '''
try:
t = paramiko.Transport((ip,int(port)))
t.connect(username=username,pkey=key)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put(localpath,remotepath)
print "\033[32;2m",
print ip,":"
print "success! file saved to %s"% remotepath
print "\033[0m"
t.close()
except:
print "\033[31;2m"
print ip,":"
print "出现连接问题",
print "\033[0m"
def sftp_get(remote_ip_path,localpath):
''' 从其他服务器获取文件,目前只针对单台 '''
ips = remote_ip_path.split(":")[0]
remotepath = remote_ip_path.split(":")[1]
file = os.getcwd()+"/iplist.txt"
f = open(file).read()
p = re.compile(ips)
iplist = re.findall(p,f)
for ip in iplist:
try:
t = paramiko.Transport((ip,int(port)))
t.connect(username=username,pkey=key)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.get(remotepath,localpath)
print "\033[32;2m",
print ip,":"
print "success! file saved to localhost %s"%localpath
print "\033[0m"
t.close()
except:
print "\033[31;2m"
print ip,":"
print "出现连接问题",
print "\033[0m"
if __name__ == '__main__':
if sys.argv[1] == "-c":
ips = sys.argv[2]
cmd = sys.argv[3]
pool = multiprocessing.Pool(processes=10)
file = os.getcwd()+"/iplist.txt"
f = open(file).read()
p = re.compile(ips)
iplist = re.findall(p,f)
for ip in iplist:
pool.apply_async(ssh2,(ip,cmd,))
pool.close()
pool.join()
elif sys.argv[1] == "-fp":
localpath = sys.argv[2]
remote_ip_path = sys.argv[3]
ips = remote_ip_path.split(":")[0]
remotepath = remote_ip_path.split(":")[1]
file = os.getcwd()+"/iplist.txt"
f = open(file).read()
p = re.compile(ips)
iplist = re.findall(p,f)
pool = multiprocessing.Pool(processes=10)
for ip in iplist:
pool.apply_async(sftp_put,(localpath,ip,remotepath,))
pool.close()
pool.join()
elif sys.argv[1] == "-fg":
localpath = sys.argv[3]
remote_ip_path = sys.argv[2]
sftp_get(remote_ip_path,localpath)
elif sys.argv[1] == "-h" or sys.argv[1] == "--help":
print "Usage: %s -c [targeip] [cmd] to run shell"% sys.argv[0]
print " %s -fp [localpath] [remoteip:path] to put file to remote host"% sys.argv[0]
print " %s -fg [remoteip:path] [localpath] to get file from remote host"% sys.argv[0]