作业需求:
1:主机分组
2:登录后显示主机分组,选择分组后查看主机列表
3:可批量执行命令,发送文件,结果实时返回
4:主机用户名密码可以不同
由于本机没有创建多个虚拟机,在程序的实际上传下载过程并没有验证,且没有完成批量执行命令的功能,反正与上传下载类似
func.py
import paramiko
import pickle
class haproxy(object):
def __init__(self):
self.host = '10.33.4.208'
self.port = 22
self.username = 'root'
self.password = '123456'
self.trans = None
self.sftp = None
def connect(self):
self.trans = paramiko.Transport(self.host,self.port)
self.trans.connect(username = self.username, password= self.password)
self.sftp = paramiko.SFTPClient.from_transport(self.trans)
def sftp_put(self,location_file,remote_file):
self.sftp.put(location_file, remote_file)
def sftp_get(self,remote_file,location_file):
self.sftp.get(remote_file, location_file)
def close(self):
self.trans.close()
def run(self):
self.connect()
self.sftp_get('Public/love.txt', 'love.txt')
self.close()
class group_list(object):
def __init__(self):
self.listfile = r'user_list'
pass
def get_groupdict(self):
with open(self.listfile,'rb') as f:
date_dict = pickle.load(f)
return date_dict #list(date.keys())
def print_list(self,list):
for i in list:
print(i)
if __name__ == '__main__':
h1 = haproxy()
# h1.run()
# while True:
try:
# username = input("Please input your username:").strip()
# password = input("Please input your password:").strip()
username = 'root'
password = '123456'
if username == h1.username and password == h1.password:
print("****主机分组列表****")
u1 = group_list()
groupdict = u1.get_groupdict()
u1.print_list(list(groupdict.keys()))
#group = input("Please choose group:").strip()
group = 'group1'
print("****组",group,"列表****")
userlist = list(groupdict[group].keys())
u1.print_list(userlist)
h2 = haproxy()
for i in userlist:
print(groupdict[group][i]['IP'])
h2.host = groupdict[group][i]['IP']
h2.port = groupdict[group][i]['port']
h2.username = groupdict[group][i]['username']
h2.password = groupdict[group][i]['password']
h2.run()
else:
print("unvalid account")
except:
#break
pass
创建用户列表的文件createuser.py
'''
Created on 2018年6月26日
@author: hcl
'''
import json
import pickle
user_dict = {
'group1':{
'h1':{"IP":"10.33.4.208", "username":"root", "password":"123456", "port":22},
'h2':{"IP":"10.33.4.209", "username":"root", "password":"123456", "port":22},
'h3':{"IP":"10.33.4.210", "username":"root", "password":"123456", "port":22}
},
'group2':{
'h1':{"IP":"10.33.4.211", "username":"root", "password":"123456", "port":22},
'h2':{"IP":"10.33.4.212", "username":"root", "password":"123456", "port":22}
},
'group3':{
'h1':{"IP":"10.33.4.213", "username":"root", "password":"123456", "port":22}
}
}
file_name = r'user_list'
"""
生成主机列表
"""
with open(file_name,'wb') as f:
f.write(pickle.dumps(user_dict))
f.flush()
"""
载入主机列表
"""
with open(file_name,'rb') as f:
date = pickle.load(f)
print(list(date.keys()))