复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/bin/env python
#!coding=utf-8
import paramiko,sys,os ##导入模块
from multiprocessing import Process,Pool
username='root' ##设置该脚本的验证用户
pd='westos' ##验证密码
def list_ssh(host_info,cmd): ##定义批量执行函数
s=paramiko.SSHClient() ##绑定实例
s.load_system_host_keys() ##加载本机HOST文件
s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ##解决第一次登陆时的yes问题
host,user,password=host_info ##host_info为元组,元组在下边代码
s.connect(host,22,user,password,timeout=2) ##创建连接
stdin,stdout,stderr=s.exec_command(cmd) ##执行这个命令,并返回结果
cmd_result=stdout.read(),stderr.read() ##读取结果
for line in cmd_result:
print '33[32;1m-----------%s-----------33[0m'%host,user
return line ##将结果返回
s.close()
def send(host_info,send_file,weizhi): ##定义发送文件函数
host,user,word=host_info ##同上
t=paramiko.Transport((host,22)) ##设定要连接的对象
t.connect(username=user,password=word) ##设定要登陆的用户
sftp=paramiko.SFTPClient.from_transport(t) ##打开FTP
sftp.put(send_file,weizhi) ##设定发送的文件,位置。
t.close()
def get(host_info,get_file,weizhi):
host,user,word=host_info
t=paramiko.Transport((host,22))
t.connect(username=user,password=word)
sftp=paramiko.SFTPClient.from_transport(t)
sftp.get(get_file,weizhi)
t.close()
def hosts():
list1=(
("192.168.137.101",'root','westos'),
("192.168.137.104",'root','westos')
) ##定义不同的组,分别对应不同的批量机器,以及登陆用户
list2=(
("192.168.137.101",'root','westos'),
("192.168.137.103",'kiosk','kiosk')
)
print """
=================
1.list1
2.list2
=================
"""
choose=raw_input('input you choose:')
p=Pool(processes=2) ##设定进程池,最大一次同时执行两个进程
result_list=[]
if choose == "list1":
print """
==============
1.发文件
2.收文件
3.批量命令
==============
"""
n=input("input you choose:")
if n == 3:
cmd=raw_input('input cmd:')
for I in list1:
result_list.append(p.apply_async(list_ssh,args=[I,cmd])) ##apply_async代表用来同步执行进程,允许多个进程同时进入池子。
for res in result_list:
print res.get() ##取出结果
elif n == 1:
send_file=raw_input('send_file:')
weizhi=raw_input('weizhi:')
for I in list1:
send(I,send_file,weizhi)
elif n == 2:
get_file=raw_input('get_file:')
weizhi=raw_input('weizhi:')
for I in list1:
count=I[0]
get(I,get_file,"%s_%s"%(weizhi,count))
else:
for I in list2:
result_list.append(p.apply_async(list2,[I,cmd]))
def check():
user=raw_input('input username:')
passwd=raw_input('input password:')
if user == username and pd == passwd:
hosts()
else:
print 'Error:user or password is wrong!'
check()
本代码之写了list1,list2与它类似,可自行写!
最后
以上就是还单身白开水最近收集整理的关于Python,批量执行命令,批量分发。的全部内容,更多相关Python内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复