1. 程式人生 > >類 Fabric 主機管理程序開發

類 Fabric 主機管理程序開發

序列 tar true close input div conn add body

類 Fabric 主機管理程序開發:
1. 運行程序列出主機組或者主機列表
2. 選擇指定主機或主機組
3. 選擇讓主機或者主機組執行命令或者向其傳輸文件(上傳/下載
4. 充分使用多線程或多進程
5. 不同主機的用戶名密碼、端口可以不同

代碼如下:

#-*-coding:utf-8-*-

import threading
import queue,time,os,paramiko

#服務器連接信息獲取驗證
def auth_action():
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
try:
db_handle = BASE_DIR+"/db/host.json"

except Exception as a:
print ("The user is not exist! ",a)
print (db_handle)
f = open(db_handle)
for host_info in f:
q.put(host_info)
#print (q.qsize())
#獲取執行命令返回信息;
def get_info(hostname,port,username,password,command):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)

ssh.connect(hostname,port,username,password)
# 執行命令;
stdin, stdout, stderr = ssh.exec_command(command)
result = stdout.read()
print("*************", hostname,"*************")
print(result.decode())
ssh.close()
#上傳文件操作;
def put_file(hostname,port,username,password):
transport = paramiko.Transport((hostname,int(port)))

print (hostname,port)
transport.connect(username = username, password=password)

sftp = paramiko.SFTPClient.from_transport(transport)
sftp.put(‘oldboy.avi‘,‘/home/oracle/test_from_win‘)
sftp.close()
#獲取主機列表
def get_host_info():
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
try:
db_handle = BASE_DIR+"/db/host.json"
except Exception as a:
print ("The user is not exist! ",a)
#print (db_handle)
with open (db_handle) as f:
print (f.read())



if __name__ =="__main__":
q = queue.Queue()
msg ="""
1.顯示主機列表;
2.主機組執行命令;
3.向主機傳輸文件;
"""
while True:
print (msg)
msg_info = input("請選擇要執行的操作:")
if msg_info =="1":
get_host_info()
if msg_info=="2":
print (">>>>>")
command = input("請輸入執行命令!>>>")
auth_action()
#print (q.qsize())
tmp_list = []
for _ in range(q.qsize()):
host_list = q.get().split()
hostname, port, username, password = host_list[1], host_list[4], host_list[2], host_list[3]
t = threading.Thread(target=get_info, args=((hostname, port, username, password, command)))
tmp_list.append(t)
t.start()
for t in tmp_list:
t.join()
if msg_info =="3":
time_start = time.time()
#put_file(hostname, port, username, password)
auth_action()
tmp_list = []
for _ in range(q.qsize()):
host_list = q.get().split()
hostname, port, username, password = host_list[1], host_list[4], host_list[2], host_list[3]
t = threading.Thread(target=put_file, args=((hostname, port, username, password)))
tmp_list.append(t)
t.start()
for t in tmp_list:
t.join()
cost_time = time.time() - time_start
print ("上傳文件已完成,用時:%s" % cost_time)
if msg_info =="q":
print ("退出系統!")
break

類 Fabric 主機管理程序開發