def load_sshusers(self, hid): """ 获取当前登录用户选择的主机对象下的ssh用户信息 :param hid: :return: """ try: ssh_user_list = [] self.mysql.connect() # 获取主机对应的所有SSH用户e.g:ssh_user1, ssh_user2 sshuser_all_host = self.mysql.session.query(SSH_User).filter( SSH_User.hid == hid).all() # 获取当前用户可以使用的所有SSH用户 e.g:ssh_user1, ssh_user3 curr_userobj = self.mysql.session.query(Login_User).filter( Login_User.username == self.username).first() sshuser_all_user = curr_userobj.sshusers # 获取当前选择的主机中用户可以使用的用户, 过滤后得到e.g :ssh_user1 tmplist = [] for obj in sshuser_all_user: if obj in sshuser_all_host: tmplist.append(obj) # 返回一个选择的用户对象字典列表 for _tmpuser in tmplist: sshuser = dict(username=_tmpuser.auth_user, auth_type=_tmpuser.auth_type, passwd=_tmpuser.auth_key) ssh_user_list.append(sshuser) self.mysql.close() return ssh_user_list except Exception as e: common.write_log("[bll.login_user.load_sshsers] {0}".format(e), "error")
def login(self): try: # 建立连接 self.mysql.connect() search_result = self.mysql.session.query(Login_User).filter(Login_User.username == self.username). \ filter(Login_User.password == self.password). \ filter(Login_User.expired > datetime.now()). \ filter(Login_User.isdel == False).first() # 执行完关闭连接 self.mysql.close() # 登录失败 if not search_result: self.exists = False else: # 登录成功 self.id = search_result.id self.exists = True self.name = search_result.name self.role = search_result.role self.username = search_result.username self.expired = search_result.expired # print(search_result) # 写操作日志记录 self.__write_login_log() except Exception as e: common.write_log("[bll.login_user.login] {0}".format(e), "ERROR")
def run(userobj, sqlhelper, ipaddr, port, sshuser, sshauth, sshkey): try: client = paramiko.SSHClient() #client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if sshauth == 1: client.connect(hostname=ipaddr, port=port, username=sshuser, password=sshkey) else: pkey = paramiko.RSAKey.from_private_key_file( os.path.join(settings.RSAKEY_PATH, sshkey)) client.connect(hostname=ipaddr, port=port, username=sshuser, pkey=pkey) chan = client.invoke_shell() print("...正在连接.....") shell(userobj, sqlhelper, ipaddr, chan) except Exception as e: client.close() common.write_log("[module.interactive.run] {0}".format(e), "error")
def load_hosts_by_uid(self): """ 获取登录用户管理的所有主机列表 :return: """ try: host_list = [] self.mysql.connect() # 获取登录用户所属组列表 userobj = self.mysql.session.query(Login_User).filter( Login_User.username == self.username).first() groups = userobj.groups # 获取所有组下的主机信息 for group in groups: hosts = group.hostlist # 遍历主机下的所有用户 for host in hosts: host_info = dict(hostid=host.id, hostname=host.hostname, ipaddr=host.ipaddr, port=host.sshport, groupname=group.groupname) host_list.append(host_info) self.mysql.close() return host_list except Exception as e: common.write_log( "[bll.login_user.load_hosts_by_uid] {0}".format(e), "error")
def load_sshusers(self, hid): """ 获取当前登录用户选择的主机对象下的ssh用户信息 :param hid: :return: """ try: ssh_user_list = [] self.mysql.connect() # 获取主机对应的所有SSH用户e.g:ssh_user1, ssh_user2 sshuser_all_host = self.mysql.session.query(SSH_User).filter(SSH_User.hid == hid).all() # 获取当前用户可以使用的所有SSH用户 e.g:ssh_user1, ssh_user3 curr_userobj = self.mysql.session.query(Login_User).filter(Login_User.username == self.username).first() sshuser_all_user = curr_userobj.sshusers # 获取当前选择的主机中用户可以使用的用户, 过滤后得到e.g :ssh_user1 tmplist = [] for obj in sshuser_all_user: if obj in sshuser_all_host: tmplist.append(obj) # 返回一个选择的用户对象字典列表 for _tmpuser in tmplist: sshuser = dict(username=_tmpuser.auth_user, auth_type=_tmpuser.auth_type, passwd=_tmpuser.auth_key) ssh_user_list.append(sshuser) self.mysql.close() return ssh_user_list except Exception as e: common.write_log("[bll.login_user.load_sshsers] {0}".format(e), "error")
def load_hosts_by_uid(self): """ 获取登录用户管理的所有主机列表 :return: """ try: host_list = [] self.mysql.connect() # 获取登录用户所属组列表 userobj = self.mysql.session.query(Login_User).filter(Login_User.username == self.username).first() groups = userobj.groups # 获取所有组下的主机信息 for group in groups: hosts = group.hostlist # 遍历主机下的所有用户 for host in hosts: host_info = dict(hostid=host.id, hostname=host.hostname, ipaddr= host.ipaddr, port=host.sshport, groupname=group.groupname) host_list.append(host_info) self.mysql.close() return host_list except Exception as e: common.write_log("[bll.login_user.load_hosts_by_uid] {0}".format(e), "error")
def login(self): try: # 建立连接 self.mysql.connect() search_result = self.mysql.session.query(Login_User).filter(Login_User.username == self.username). \ filter(Login_User.password == self.password). \ filter(Login_User.expired > datetime.now()). \ filter(Login_User.isdel == False).first() # 执行完关闭连接 self.mysql.close() # 登录失败 if not search_result: self.exists = False else: # 登录成功 self.id = search_result.id self.exists = True self.name = search_result.name self.role = search_result.role self.username = search_result.username self.expired = search_result.expired # print(search_result) # 写操作日志记录 self.__write_login_log() except Exception as e: common.write_log("[bll.login_user.login] {0}".format(e), "ERROR")
def load_group_all(self): try: self.mysql.connect() grouplist = self.mysql.session.query(Groups).all() self.mysql.close() return grouplist except Exception as e: common.write_log("[bll.groups.load_group_all {0}".format(e))
def last_login_date(self): """ 获取用户上一次登录的时间 """ try: self.mysql.connect() op_rec = self.mysql.session.query(Op_Logs).filter( Op_Logs.uid == self.opuser.id).order_by( Op_Logs.opdate.desc()).first() self.mysql.close() return op_rec.opdate except Exception as e: write_log("[bll.op_log.last_login_date] {0}".format(e))
def insert(self): try: self.mysql.connect() ssh_user = SSH_User(auth_key = self.auth_key, auth_type = self.auth_type, auth_user = self.auth_name) ssh_user.hid = self.host.id self.mysql.session.add(ssh_user) self.mysql.session.commit() self.mysql.close() except Exception as e: write_log("[bll.ssh_user.insert] {0}".format(e))
def load_users_by_host(self): """ 通过主机获取该主机下的所有ssh用户信息,是多对一的关系查询 :return: """ try: self.mysql.connect() # 根据关联关系从主机得到主机下的所有用户 ssh_user_list = self.mysql.session.query(SSH_User).filter(SSH_User.hid == self.host.id).all() self.mysql.close() return ssh_user_list except Exception as e: write_log("[bll.ssh_user.load_user_by_host] {0}".format(e), "ERROR")
def load_group_by_name(self): """ 通过组名返回一个组对象,用来获取组信息或检测组是否存在 :return: 组对象 """ try: self.mysql.connect() group = self.mysql.session.query(Groups).filter( Groups.groupname == self.groupname).first() self.mysql.close() return group except Exception as e: common.write_log("[bll.groups.load_group_by_name] {0}".format(e), "ERROR")
def insert_ssh_user(self, id_list): """ 给添加的登录用户分配ssh登录用户 :param id_list: :return: """ try: self.mysql.connect() ssh_user_obj_list = self.mysql.session.query(SSH_User).filter(SSH_User.id.in_(id_list)).all() login_user_obj = self.mysql.session.query(Login_User).filter(Login_User.username == self.username).first() login_user_obj.sshusers = ssh_user_obj_list self.mysql.session.commit() self.mysql.close() except Exception as e: common.write_log("[bll.login_user.insert_ssh_user] {0}".format(e), "error")
def user_exists(self): """ 检测用户是否已经存在 :return: """ try: self.mysql.connect() user = self.mysql.session.query(Login_User).filter(Login_User.username == self.username).first() if not user: self.exists = False else: self.exists = True self.mysql.close() return self.exists except Exception as e: common.write_log("[bll.login_user.user_exists] {0}".format(e), "error")
def insert(self, grouplist): """ 信添加一个登录账户 :return: """ try: self.mysql.connect() new_user = Login_User(self.username, self.name, self.role, 0, self.expired, self.password) new_user.groups = grouplist self.mysql.session.add(new_user) self.mysql.session.commit() self.mysql.close() return new_user except Exception as e: common.write_log("[bll.login_user.insert] {0}".format(e), "error")
def insert(self, groupsobj_list): """ 添加主机信息表,并同时添加关联表 :param groups: 用户选择的主机所属主机组对象列表 :return: """ try: self.mysql.connect() host = Hosts(self.hostname, self.ipaddr, self.sshport) host.groups = groupsobj_list self.mysql.session.add(host) self.mysql.session.commit() # 关闭连接 self.mysql.close() except Exception as e: write_log("[bll.hosts.insert] {0}".format(e), "error")
def load_hosts_by_group(self, groupobj): """ 通过选择的主机组获取该组下所有的主机信息 :param groupobj: 主机组对象 :return: """ try: self.mysql.connect() group = self.mysql.session.query(Groups).filter( Groups.id == groupobj.id).first() print(group) host_list = group.hostlist print(host_list) self.mysql.close() return host_list except Exception as e: write_log("[bll.hosts.load_hosts_by_group] {0}".format(e), "error")
def add_group(sqlhelper): """ 添加主机组 :param sqlhelper: 数据库连接对象 :return: """ try: groupname = common.input_msg("请输入主机组名称: ") groupobj = BLL_Host_Group(sqlhelper) groupobj.groupname = groupname if not groupobj.load_group_by_name(): groupobj.insert() common.show_message("主机组添加成功", "INFORMATION") else: common.show_message("该组已经存在!", "NOTICE") except Exception as e: common.write_log("[module.admin.add_group] {0}".format(e))
def user_exists(self): """ 检测用户是否已经存在 :return: """ try: self.mysql.connect() user = self.mysql.session.query(Login_User).filter( Login_User.username == self.username).first() if not user: self.exists = False else: self.exists = True self.mysql.close() return self.exists except Exception as e: common.write_log("[bll.login_user.user_exists] {0}".format(e), "error")
def insert(self): """ 插入一条组记录 :return: """ try: # 链接数据库 self.mysql.connect() group = Groups(self.groupname) self.mysql.session.add(group) self.mysql.session.commit() # close self.mysql.close() except Exception as e: common.write_log("[bll.groups.insert] {0}".format(e), "ERROR")
def run(userobj, sqlhelper, ipaddr, port, sshuser, sshauth, sshkey): try: client = paramiko.SSHClient() #client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if sshauth == 1: client.connect(hostname=ipaddr, port=port, username=sshuser,password=sshkey) else: pkey = paramiko.RSAKey.from_private_key_file(os.path.join(settings.RSAKEY_PATH, sshkey)) client.connect(hostname=ipaddr, port=port, username=sshuser, pkey=pkey) chan = client.invoke_shell() print("...正在连接.....") shell(userobj, sqlhelper, ipaddr, chan) except Exception as e: client.close() common.write_log("[module.interactive.run] {0}".format(e), "error")
def insert_ssh_user(self, id_list): """ 给添加的登录用户分配ssh登录用户 :param id_list: :return: """ try: self.mysql.connect() ssh_user_obj_list = self.mysql.session.query(SSH_User).filter( SSH_User.id.in_(id_list)).all() login_user_obj = self.mysql.session.query(Login_User).filter( Login_User.username == self.username).first() login_user_obj.sshusers = ssh_user_obj_list self.mysql.session.commit() self.mysql.close() except Exception as e: common.write_log("[bll.login_user.insert_ssh_user] {0}".format(e), "error")
def save_log(self, opmsglist, optype): """ 将操作日志写入数据库 :param opmsg:要写入的消息记录 :param optype: 日志类型 login / exec_cmd """ try: # 连接数据库 self.mysql.connect() for msg in opmsglist: newrecord = Op_Logs(uid=self.opuser.id, optype=optype, opdate=datetime.now(), opmsg=msg) self.mysql.session.add(newrecord) self.mysql.session.commit() # 执行完关闭数据库 self.mysql.close() except Exception as e: write_log("[bll.op_log.save_log] {0}".format(e))
def insert(self, grouplist): """ 信添加一个登录账户 :return: """ try: self.mysql.connect() new_user = Login_User(self.username, self.name, self.role, 0, self.expired, self.password) new_user.groups = grouplist self.mysql.session.add(new_user) self.mysql.session.commit() self.mysql.close() return new_user except Exception as e: common.write_log("[bll.login_user.insert] {0}".format(e), "error")
def add_host(sqlhelper): """ 添加主机信息 :param sqlhelper: :return: """ try: hostname = common.input_msg(" 请输入主机名: ") hostip = common.input_msg(" 请输入IP地址: ") sshport = common.input_msg(" 请输入SSH端口(default:22): ", int=True) choose_group = load_host_groups(sqlhelper) # 生成主机对象并执行sql写入 hostobj = BLL_Hosts(sqlhelper) hostobj.hostname = hostname hostobj.ipaddr = hostip hostobj.sshport = sshport hostobj.insert(choose_group) common.show_message("主机添加成功!", "INFORMATION") except Exception as e: common.write_log("[module.admin.add_host] {0}".format(e))
def __write_login_log(self): try: if not self.exists: op_msg = ("用户{user}登录系统失败!".format(user=self.username),) else: op_msg = ("用户{user}登录系统成功!".format(user=self.username),) op_type = "login" op_log = BLL_Op_Logs(self, self.mysql) # 获取当前上次登录的时间 op_date = op_log.last_login_date() if op_date: self.last_login_date = op_date # 写日志 op_log.save_log(op_msg, op_type) # 执行完在内存中删除此对象 del op_log except Exception as e: common.write_log("[bll.login_user.__write_log_log] {0}".format(e), "ERROR")
def init_run(): """ 数据库初始化模块,检测数据库是否已经创建,如果未创建数据库就生成表 """ if os.path.exists(settings.DB_INIT_LCK): pass else: confirm = common.input_msg("尚未创建数据表,是否现在初始化数据表?(y/n): ", ("y", "n")) # 开始创建数据表 if confirm == "y": try: common.show_message("开始创建数据表......", "INFORMATION") base = tables.Base mysql = MySqlHelper() base.metadata.create_all(mysql.engine) common.show_message("数据表创建完成!", "INFORMATION") # 创建完成数据表后生成标识文件 fb = open(settings.DB_INIT_LCK, 'wb') fb.close() # 创建一个管理员 common.show_message("开始初始化用户........", "INFORMATION") user_admin = tables.Login_User(username='******', password=common.encry('admin'), name='管理员', role='admin', isdel=0, expired=datetime.now() + timedelta(days=+999) ) mysql.connect() mysql.session.add(user_admin) mysql.session.commit() common.show_message("初始化用户完成,请用admin / admin 登录", "INFORMATION") # 关闭连接 mysql.close() except Exception as e: common.write_log(e, "error") sys.exit(-1)
def __write_login_log(self): try: if not self.exists: op_msg = ("用户{user}登录系统失败!".format(user=self.username), ) else: op_msg = ("用户{user}登录系统成功!".format(user=self.username), ) op_type = "login" op_log = BLL_Op_Logs(self, self.mysql) # 获取当前上次登录的时间 op_date = op_log.last_login_date() if op_date: self.last_login_date = op_date # 写日志 op_log.save_log(op_msg, op_type) # 执行完在内存中删除此对象 del op_log except Exception as e: common.write_log("[bll.login_user.__write_log_log] {0}".format(e), "ERROR")
def _ssh_exec_cmd(commandstr, **host): """ paramiko 执行命令方法 :param hostlist: 主机列表{ip:[{user: , key: , auth_type: }]} :param commandstr: 执行的命令 :return: """ ip = list(host.keys())[0] host_item = host[ip] port = int(host_item["port"]) user = host_item["user"] key = host_item["key"] try: # 开始登录服务器并执行命令 transport = paramiko.Transport(ip, port) if host_item["auth_type"] == 1: transport.connect(username=user, password=key) else: pkey = paramiko.RSAKey.from_private_key_file(os.path.join(settings.RSAKEY, "id_rsa"), password=key) transport.connect(username=user, pkey=pkey) ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh._transport = transport stdin, stdout, stderr = ssh.exec_command(command=commandstr) print("\033[1;31m IP -> {0} : \033[0m \n".format(ip)) err_result = stderr.read().decode() out_result = stdout.read().decode() if len(err_result) > 0: print(err_result) if len(out_result) > 0: print(out_result) transport.close() except Exception as e: print(e) write_log(e, "error")
def _sftp_put(source, distinct, sftp_method, **host): """ 执行文件传输, :param source:源文件 :param distinct: 目标文件 :param sftp_method: sftp方式 上传 put / 下载 get :param host: 远程访问的主机信息 :return: """ try: ip = list(host.keys())[0] host_item = host[ip] port = int(host_item["port"]) user = host_item["user"] key = host_item["key"] #print(ip,port,user,key) transport = paramiko.Transport(ip, port) if host_item['auth_type'] == 1: transport.connect(username=user, password=key) else: pkey = paramiko.RSAKey.from_private_key_file(os.path.join(settings.RSAKEY, key)) transport.connect(username=user, pkey=pkey) ssh_sftp = paramiko.SFTPClient.from_transport(transport) if sftp_method == "put": ssh_sftp.put(source, distinct) print("\033[1;31m\n local[ {0} ] >>>>> upload to >>>>>> {1}[ {2} ] finished \033[0m".format(source, ip, distinct)) else: #print(source, distinct) ssh_sftp.get(source, distinct) print("\033[1;34m\n local[ {0} ] <<<<<< download from <<<<<<< {1}[ {2} ] finished \033[0m".format(distinct, ip, source)) transport.close() except Exception as e: write_log(e, "error")
def user_run(user, sqlhelper): """ 普通用户登录操作模块 :param user: :return: """ try: op_log = BLL_Op_Logs(user, sqlhelper) exit_flag = False while not exit_flag: tmpi = 0 tmpflag = False # 打印标题 print(title_menu(user)) common.show_message("<-- 请选择要操作的主机 -->", "INFORMATION") # 获取用户所属组列表 host_list = user.load_hosts_by_uid() # 打印主机列表 for host in host_list: print("\033[1;32m [{0}] 主机名:{1} IP:{2} 所属组:{3}\033[0m".format(str(tmpi + 1), host['hostname'], host['ipaddr'], host['groupname'] )) tmpi += 1 # 选择一个要登录的主机 while not tmpflag: exit_flag = False choose_id = common.input_msg("\n请选择要登录的主机编号(exit 退出): ") if choose_id == "exit": exit_flag = True break if int(choose_id) > len(host_list): common.show_message("主机编号不存在!", "ERROR") continue else: choose_host = host_list[int(choose_id) - 1] break # 是否要退出 if exit_flag == True: continue # 要登录的主机IP ssh_host_ip = choose_host['ipaddr'] ssh_host_port = choose_host['port'] ssh_host_hostname = choose_host['hostname'] # 获取选择的主机中用户可以使用的ssh用户列表 ssh_users = user.load_sshusers(choose_host['hostid']) if len(ssh_users) == 0: # 未找到可以使用的账户 common.show_message("\n未配置登录用户,请联系系统管理员!", "ERROR") continue elif len(ssh_users) == 1: # 如果当前主机只有一个用户可以操作 ssh_user = ssh_users[0] else: # 有多个用户,需要选择一个 tmpi = 0 for sshuser in ssh_users: print(" [{0}] {1}".format(str(tmpi + 1), sshuser['username'])) tmpi += 1 choose = common.input_msg("请选择要使用的SSH用户编号:", int=True) ssh_user = ssh_users[int(choose) - 1] # 记录一条op日志 op_log.save_log(("用户[{0}]使用SSH用户[{1}]登录主机[{2}](IP:{3}).".format(user.username, ssh_user['username'], ssh_host_hostname, ssh_host_ip),), "ssh") # 调用paramiko进行登录 # print(ssh_host_ip, ssh_host_port, ssh_user['username'], ssh_user['auth_type'], ssh_user['passwd']) interactive.run(user, sqlhelper, ssh_host_ip, ssh_host_port, ssh_user['username'], ssh_user['auth_type'], ssh_user['passwd']) op_log.save_log(("用户[{0}]使用SSH用户[{1}]登出主机[{2}](IP:{3}).".format(user.username, ssh_user['username'], ssh_host_hostname, ssh_host_ip),), "ssh") # 释放对象 del op_log except Exception as e: common.write_log("[bin.main.user_run] {0}".format(e), "error")
def shell(userobj, sqlhelper, ipaddr, chan): """ 执行终端操作 :param userobj: 当前用户对象 :param sqlhelper: 数据库访问对象 :param ipaddr: 当前登录的主机IP :param chan: 登录的终端通道 :return: """ import select cmd = '' full_cmd_list = [] input_tab_flag = False op_log = BLL_Op_Logs(userobj, sqlhelper) oldtty = termios.tcgetattr(sys.stdin) try: tty.setraw(sys.stdin.fileno()) tty.setcbreak(sys.stdin.fileno()) chan.settimeout(0.0) while True: r, w, e = select.select([chan, sys.stdin], [], []) if chan in r: try: x = u(chan.recv(1024)) if input_tab_flag: cmd += x input_tab_flag = False if len(x) == 0: # 如果用户exit退出系统,则将剩下的不够5条的记录也入库 if len(full_cmd_list) > 0: op_log.save_log(tuple(full_cmd_list), "command") #sys.stdout.write('\r\n*** EOF\r\n') break sys.stdout.write(x) sys.stdout.flush() except socket.timeout: pass if sys.stdin in r: x = sys.stdin.read(1) if ord(x) == 9: # 用户输入tab键则记录一个标识,并不记录到命令字符中,在接收字符补全 input_tab_flag = True elif ord(x) == 127: # 用户输入backspace键,删除一个字符 cmd = cmd[0:-1] else: cmd += x.strip() # 如果输入回车 if str(x) in ['\r', '\n', '\r\n']: full_cmd_list.append("用户[{0}]在服务器[{1}]上执行 {2} 命令".format( userobj.username, ipaddr, cmd.strip())) # 每输入5条进行一次入库 if len(full_cmd_list) == 5: op_log.save_log(tuple(full_cmd_list), "command") full_cmd_list.clear() cmd = '' if len(x) == 0: break chan.send(x) except Exception as e: common.write_log("[module.interactive.shell] {0}".format(e), "error") finally: termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
def add_login_user(sqlhelper): """ 添加登录堡垒及的账户信息 :param sqlhelper: :return: """ try: back_flag = False while not back_flag: # 初始化输入 login_user = BLL_Login_User(sqlhelper) while True: username = common.input_msg("用户名(q 返回): ") if username == "q": back_flag = True break # 判断用户是否存在 login_user.username = username if login_user.user_exists: common.show_message("该用户名已经存在,请重新输入!", "ERROR") continue else: break if not back_flag: password = common.input_msg("密 码: ", password=True) name = common.input_msg("姓 名: ") role = common.input_msg("权限(1:普通用户 / 2:管理员): ", limit_value=('1', '2')) expired_days = common.input_msg("有效期(天): ", int=True) expired = datetime.now() + timedelta(days=int(expired_days)) if role == "1": role = "user" else: role = "admin" # 给用户划分组 group_list = load_host_groups(sqlhelper) # group_list对象在数据库操作中关闭链接后就没了,不知到为什么,copy一份 group_list_bak = copy.deepcopy(group_list) # 开始新建一个用户 login_user.password = common.encry(password) login_user.name = name login_user.role = role login_user.expired = expired login_user.insert(group_list) common.show_message("用户[{0}]创建成功!".format(username), "INFORMATION") # 给用户分配所属组下的主机登录用户,主机包含多个登录用户,给用户分配一个用户 choose = common.input_msg( "需要现在给[{0}]分配各主机的管理用户吗?(y/n)".format(username), limit_value=('y', 'n')) if choose == "y": hostobj = BLL_Hosts(sqlhelper) sshuserobj = BLL_SSH_User(sqlhelper, hostobj) # 保存所有主机登录用户的id,用于去重 ssh_user_set = [] for usergroup in group_list_bak: # 根据用户的所属组获取各组下的所有主机 hostobj_list = hostobj.load_hosts_by_group(usergroup) # 从主机列表遍历获取所有ssh用户信息 for host in hostobj_list: sshuserobj.host = host # 获取主机下的所有用户信息 sshuser_list = sshuserobj.load_users_by_host() # 将这些信息添加到集合中,单条记录为字典格式 for sshuser in sshuser_list: sshuser_info = dict(sid=sshuser.id, username=sshuser.auth_user, host=host.hostname, group=usergroup.groupname) ssh_user_set.append(sshuser_info) # 全部遍历完成后的集合中存放的就是该用户可以使用的登录主机用户信息,下面用来选择 common.show_message("<--可以使用的用户列表-->", "INFORMATION") for user in ssh_user_set: print( "用户ID: {0} 用户名: {1} 所属主机: {2} 所属组: {3}".format( str(user['sid']).ljust(3, ' '), user['username'].ljust(10, ' '), user['host'].ljust(8, ' '), user['group'].ljust(8, ' '))) ssh_user_id_list = common.input_msg("请选择SSH用户ID(多个用,分隔): ") # 当前处理的登录用户对象 curr_user = BLL_Login_User(sqlhelper) curr_user.username = login_user.username curr_user.insert_ssh_user(ssh_user_id_list) common.show_message("分配成功!".format(username), "INFORMATION") else: pass except Exception as e: common.write_log("[module.admin.add_login_user] {0}".format(e), "ERROR")
args = sys.argv[1:] #args = ['web_server', 'ftp.cuu', 'mysql'] #print(args) try: exec_module = args[1] # 如果参数cmd.run语法错误,直接抛异常 if exec_module.count(".") == 0: raise IndexError # 获取执行的模块名称cmd or ftp modulename = exec_module.split(".")[0] funcname = exec_module.split(".")[1] # 导入模块 modobj = __import__("script.{0}".format(modulename)) modobj = getattr(modobj,modulename) funcobj = getattr(modobj, funcname) funcobj(*args) except (ImportError,IndexError): common.write_log("Import module error", "error") print("\033[33;1m no module {0} found \033[0m".format(exec_module)) except Exception as e: common.write_log(e, "error") print("\033[33;1m system run Error,check logs\033[0m")
def shell(userobj, sqlhelper, ipaddr, chan): """ 执行终端操作 :param userobj: 当前用户对象 :param sqlhelper: 数据库访问对象 :param ipaddr: 当前登录的主机IP :param chan: 登录的终端通道 :return: """ import select cmd = '' full_cmd_list = [] input_tab_flag = False op_log = BLL_Op_Logs(userobj,sqlhelper) oldtty = termios.tcgetattr(sys.stdin) try: tty.setraw(sys.stdin.fileno()) tty.setcbreak(sys.stdin.fileno()) chan.settimeout(0.0) while True: r, w, e = select.select([chan, sys.stdin], [], []) if chan in r: try: x = u(chan.recv(1024)) if input_tab_flag: cmd += x input_tab_flag = False if len(x) == 0: # 如果用户exit退出系统,则将剩下的不够5条的记录也入库 if len(full_cmd_list) > 0: op_log.save_log(tuple(full_cmd_list), "command") #sys.stdout.write('\r\n*** EOF\r\n') break sys.stdout.write(x) sys.stdout.flush() except socket.timeout: pass if sys.stdin in r: x = sys.stdin.read(1) if ord(x) == 9: # 用户输入tab键则记录一个标识,并不记录到命令字符中,在接收字符补全 input_tab_flag = True elif ord(x) == 127: # 用户输入backspace键,删除一个字符 cmd = cmd[0:-1] else: cmd += x.strip() # 如果输入回车 if str(x) in ['\r', '\n', '\r\n']: full_cmd_list.append("用户[{0}]在服务器[{1}]上执行 {2} 命令".format(userobj.username, ipaddr, cmd.strip())) # 每输入5条进行一次入库 if len(full_cmd_list) == 5: op_log.save_log(tuple(full_cmd_list), "command") full_cmd_list.clear() cmd = '' if len(x) == 0: break chan.send(x) except Exception as e: common.write_log("[module.interactive.shell] {0}".format(e), "error") finally: termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
def add_host_user(sqlhelper): """ 添加主机用户信息 :param sqlhelper: :return: """ try: group_list = load_host_groups(sqlhelper) while len(group_list) > 1: print("添加主机用户时一次只能选择一台主机,请选择一个主机组!") group_list = load_host_groups(sqlhelper) # 显示选择组下的所有主机信息 tmpi = 0 #print(choose_group,type(choose_group)) choose_group = group_list[0] hostobj = BLL_Hosts(sqlhelper) host_list = hostobj.load_hosts_by_group(choose_group) print("\n\033[1;30m <--- 主机组 [{0}] 包含如下主机,请选择主机编号 --->\033[0m".format( choose_group.groupname)) while tmpi < len(host_list): print(" [{0}] 主机名:{1} IP:{2}".format( tmpi + 1, host_list[tmpi].hostname.ljust(10, " "), host_list[tmpi].ipaddr)) tmpi += 1 # 选择主机编号 while True: host_id = common.input_msg("选择主机编号(q 返回): ") if host_id == "q": break else: host_id = int(host_id) # 判断选择的组编号是否越界 if host_id > len(host_list): common.show_message("选择编号错误,请重新选择!", "ERROR") continue else: break choose_host = host_list[host_id - 1] # 对选择的主机添加用户 choose_flag = False ssh_user = BLL_SSH_User(sqlhelper, choose_host) while not choose_flag: auth_user = common.input_msg("登录用户名: ") auth_type = common.input_msg("登录验证类型[1:密码 / 2:密钥]: ", limit_value=('1', '2')) auth_key = common.input_msg("登录密码/密钥文件: ") # 新增用户 ssh_user.auth_key = auth_key ssh_user.auth_name = auth_user ssh_user.auth_type = int(auth_type) ssh_user.insert() # 继续添加 common.show_message("添加成功!", "INFORMATION") goon = common.input_msg("是否继续添加用户(y/n)? :", limit_value=('y', 'n')) if goon == "y": continue else: choose_flag = True except Exception as e: common.write_log("[module.admin.add_host_user] {0}".format(e))