Python,批量執行命令,批量分發。
阿新 • • 發佈:2019-01-29
#!/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 '\033[32;1m-----------%s-----------\033[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與它類似,可自行寫!