def network_io(self, username, hostname, password): """ 统计当前节点服务器网络IO信息 :return: 网络IO信息 """ try: logger.info('connect <%s> from <%s>', hostname, username) child = CommandUtils().command_ssh_remote_password( username, hostname, password, "cat /proc/net/dev") logger.info('from <%s> by <%s> connected', hostname, username) temp = child.before.decode().strip().split('\n') nios = [] for line in temp[2:]: network_io = MonitorNetworkIO() line = line.split(":") network_io.name = line[0].strip() network_io.receive = round( float(line[1].split()[0]) / (1024.0 * 1024.0), 2) network_io.transmit = round( float(line[1].split()[8]) / (1024.0 * 1024.0), 2) nios.append(network_io) return nios except Exception as ex: logger.error('connect <%s> from <%s> failure, reason <%s>', hostname, username, ex) return None
def on_close(self): logger.info('socket closed from <%s> by <%s>', self.ssh.hostname, self.ssh.username) connection = self.build_connection() end_time = datetime.datetime.now() connection.end_time = end_time connection.elapsed_time = (end_time - self.start_connection_time).microseconds HostConnectionService().add(model=connection, user_id=self.user_id, host_id=self.host_id)
def __init__(self, hostname='localhost', port=22, username='******', password=None, private_key=None): self.hostname = hostname self.port = port self.username = username self.password = password self.private_key = private_key try: self._ssh = paramiko.SSHClient() self._ssh.load_system_host_keys() self._ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if StringUtils().is_empty( source=self.password) and StringUtils().is_empty( source=self.private_key): logger.info('connect <%s> from <%s> by open authorization', self.hostname, self.username) self._ssh.connect(hostname=self.hostname, port=self.port, username=self.username, password=None, pkey=None) elif StringUtils().is_not_empty( source=self.password) and StringUtils().is_empty( source=self.private_key): logger.info('connect <%s> from <%s> by password authorization', self.hostname, self.username) self._ssh.connect(hostname=self.hostname, port=self.port, username=self.username, password=self.password, pkey=None) else: logger.info( 'connect <%s> from <%s> by private key authorization', self.hostname, self.username) self.private_key_file = StringIO() self.private_key_file.write(self.private_key) self.private_key_file.seek(0) self.key_file = self.private_key_file and paramiko.RSAKey.from_private_key( self.private_key_file) or None self._ssh.connect(hostname=hostname, port=port, username=username, password=None, pkey=self.key_file) self._chanel = self._ssh.invoke_shell(term='xterm') self.connected = True logger.info('from <%s> by <%s> connected', self.hostname, self.username) except Exception as ex: logger.error('connect <%s> from <%s> Authentication failed') self.message = ex self.connected = False
def find_all_order_by_user_and_login_time_desc(self, user_id=int): try: logger.info('execute select %s starting primary key <%s>', logger_type, user_id) sql = 'select ll.id as id, ll.login_time as login_time, ll.position as position, ll.ip as ip, ' \ 'll.client as client, ll.status as status, ll.reason as reason, u.name as username from logging_login as ll ' \ 'left join user_logging_login_relation as ullr on ll.id = ullr.logging_login_id ' \ 'left join user as u on u.id = ullr.user_id ' \ 'where u.id = :user_id ' \ 'order by ll.login_time desc ' result = db.engine.execute(text(sql), {'user_id': user_id}) return [dict(row) for row in result] except Exception as ex: logger.info( 'execute select %s starting primary key <%s> error, reason <%s>', logger_type, user_id, ex) return None
def profile(user_id=int): form_profile = SettingsProfileForm() form_avatar = SettingsAvatarForm() user = UserService().find_one(id=current_user.id) if form_avatar.validate_on_submit(): avatar = request.files['avatar'] path = '{}/{}'.format(codes['config']['avatar'], current_user.id) if not os.path.exists(path): os.makedirs(path) avatar_path = os.path.join( codes['config']['avatar'], '{}/{}.png'.format(current_user.id, int(time.time()))) avatar.save(avatar_path) user.avatar = '{}/{}.png'.format(current_user.id, int(time.time())) if UserService().update_avatar(user=user): flash('数据更新成功!') return redirect(url_for('settings_view.profile', alert_type='success')) BuildModelToFrom(user, form_profile) if form_profile.validate_on_submit(): user = User() user.id = current_user.id user.name = request.form.get('username') user.website = request.form.get('website') user.position = request.form.get('position') user.description = request.form.get('description') user.email = request.form.get('email') if request.method == 'POST': logger.info('execute update operation type <%s> primary key <%s>', logger_type, user.id) if UserService().update_one(user=user): flash('数据更新成功!') return redirect( url_for('settings_view.profile', alert_type='success')) if request.args.get('alert_type') is None: alter_type = 'danger' else: alter_type = request.args.get('alert_type') return render_template('settings/settings-profile.html', user_id=user_id, title='个人资料', form_profile=form_profile, active_menu='profile', user=user, alert_type=alter_type, avatar_form=form_avatar)
def find_all_by_host_create_time_desc(self, host_id=int): try: logger.info('execute select %s starting primary key <%s>', logger_type, host_id) sql = 'select ce.id, ce.command, ce.final_state, ce.start_time, ce.end_time, ce.elapsed_time, ce.reason, h.hostname, h.username ' \ 'from command_execute as ce ' \ 'left join user_host_command_execute_relation as uhcer on ce.id = uhcer.command_execute_id ' \ 'left join user as u on uhcer.user_id = u.id ' \ 'left join host as h on uhcer.host_id = h.id ' \ 'where h.id = :host_id ' \ 'order by ce.create_time desc ' result = db.engine.execute(text(sql), {'host_id': host_id}) return [dict(row) for row in result] except Exception as ex: logger.info( 'execute select %s starting primary key <%s> error, reason <%s>', logger_type, host_id, ex) return None
def find_all_by_host_create_time_desc(self, host_id=int): try: logger.info('execute select %s starting primary key <%s>', logger_type, host_id) sql = 'select hc.id, hc.name, hc.type, hc.start_time, hc.end_time, hc.elapsed_time, hc.reason, h.hostname, h.username ' \ 'from host_connection as hc ' \ 'left join user_host_connection as uhc on hc.id = uhc.connection_id ' \ 'left join user as u on uhc.user_id = u.id ' \ 'left join host as h on uhc.host_id = h.id ' \ 'where h.id = :host_id ' \ 'order by hc.create_time desc ' result = db.engine.execute(text(sql), {'host_id': host_id}) return [dict(row) for row in result] except Exception as ex: logger.info( 'execute select %s starting primary key <%s> error, reason <%s>', logger_type, host_id, ex) return None
def update_one(self, user=User): try: logger.info('execute update %s starting primary key <%s>', logger_type, user.id) sql = 'update user set ' if user.name: sql += 'name = :name' if user.email: sql += ', email =:email' if user.position: sql += ', position = :position' if user.description: sql += ', description = :description' if user.website: sql += ', website = :website' sql += ' where id = :id' db.engine.execute( text(sql), { 'name': user.name, 'email': user.email, 'position': user.position, 'description': user.description, 'website': user.website, 'id': user.id }) logger.info('execute update %s starting primary key <%s> success', logger_type, user.id) return True except Exception as ex: logger.info( 'execute update %s starting primary key <%s> error, reason <%s>', logger_type, user.id, ex) flash('更新数据失败, 错误如下: \r\n{}'.format(ex)) return False
def update_one(self, host=Host): try: logger.info('execute update %s starting primary key <%s>', logger_type, host.id) sql = 'update `host` set hostname = :hostname, username = :username, password = :password, `key` = :key, ' \ 'server_name = :server_name, server_type = :server_type, server = :server, command = :command, ' \ 'command_start = :command_start, command_stop = :command_stop, command_restart = :command_restart,' \ 'message = :message, ssh_port = :ssh_port where id = :id' db.engine.execute( text(sql), { 'hostname': host.hostname, 'username': host.username, 'password': host.password, 'key': host.key, 'server_name': host.server_name, 'server_type': host.server_type, 'server': host.server, 'command': host.command, 'command_start': host.command_start, 'command_stop': host.command_stop, 'command_restart': host.command_restart, 'message': host.message, 'ssh_port': host.ssh_port, 'id': host.id }) logger.info('execute update %s starting primary key <%s> success', logger_type, host.id) return True except Exception as ex: logger.info( 'execute update %s starting primary key <%s> error, reason <%s>', logger_type, host.id, ex) flash('更新数据失败, 错误如下: \r\n{}'.format(ex)) return False
def open(self, *args, **kwargs): if args: server_id = int(args[0]) user_id = int(args[1]) self.host = HostService().find_one(id=server_id) self.command = '' self.persistence = False # self.user = UserService().find_one(id=user_id) self.user_id = user_id self.host_id = server_id self.end_time = datetime.datetime.now() self.start_time = datetime.datetime.now() self.reason = '' logger.info('connected from <%s> by <%s> start', self.host.hostname, self.host.username) self.ssh = Ssh(hostname=self.host.hostname, port=self.host.ssh_port, username=self.host.username, password=self.host.password, private_key=self.host.key) self.start_connection_time = datetime.datetime.now() t = threading.Thread(target=self._reading) t.setDaemon(True) t.start()
def update_avatar(self, user=User): try: logger.info('execute update %s starting primary key <%s>', logger_type, user.id) sql = 'update user set avatar = :avatar where id = :id' db.engine.execute(text(sql), { 'avatar': user.avatar, 'id': user.id }) logger.info('execute update %s starting primary key <%s> success', logger_type, user.id) return True except Exception as ex: logger.info( 'execute update %s starting primary key <%s> error, reason <%s>', logger_type, user.id, ex) flash('更新数据失败, 错误如下: \r\n{}'.format(ex)) return False
def update_last_login_time(self, user=User): try: logger.info('execute update %s starting primary key <%s>', logger_type, user.id) user.last_login_time = datetime.datetime.now() sql = 'update user set last_login_time = :last_login_time where id = :id' db.engine.execute(text(sql), { 'last_login_time': user.last_login_time, 'id': user.id }) logger.info('execute update %s starting primary key <%s> success', logger_type, user.id) return True except Exception as ex: logger.info( 'execute update %s starting primary key <%s> error, reason <%s>', logger_type, user.id, ex) return False
def add(self, model=LoginLogging, user_id=int): try: logger.info('execute update %s starting primary key <%s>', logger_type, user_id) db.session.add(model) db.session.flush() db.session.commit() sql = 'insert into user_logging_login_relation(user_id, logging_login_id) ' \ 'values(:user_id, :logging_login_id)' db.engine.execute(text(sql), { 'user_id': user_id, 'logging_login_id': model.id }) logger.info('execute update %s starting primary key <%s> success', logger_type, user_id) return True except Exception as ex: logger.info( 'execute update %s starting primary key <%s> error, reason <%s>', logger_type, user_id, ex) return False
def add(self, model=HostConnection, user_id=int, host_id=int): try: logger.info('execute update %s starting primary key <%s>', logger_type, user_id) db.session.add(model) db.session.commit() sql = 'insert into user_host_connection(host_id, user_id, connection_id) ' \ 'values(:host_id, :user_id, :connection_id)' db.engine.execute(text(sql), { 'host_id': host_id, 'user_id': user_id, 'connection_id': model.id }) logger.info('execute update %s starting primary key <%s> success', logger_type, user_id) return True except Exception as ex: logger.info( 'execute update %s starting primary key <%s> error, reason <%s>', logger_type, user_id, ex) return False
def initialize(self, *args, **kwargs): logger.info('Welcome To iMonitor Web Terminal') logger.info('login in params <%s>, kwargs <%s>', args, kwargs)
def create_modfiy_copy_delete(host_id=int): type = request.args.get('type') method = request.args.get('method') form = HostForm() host = HostService().find_one(id=host_id) if (host_id <= 0) or host is None: title = '新建主机' else: # 回显表单数据 BuildModelToFrom(host=host, form=form) if (host_id > 0 and type is None): title = '修改主机' else: title = '复制主机' if form.validate_on_submit(): host = Host() host.hostname = request.form.get('hostname') host.active = True host.username = request.form.get('username') host.password = request.form.get('security_password') host.command = request.form.get('command') host.command_start = request.form.get('command_start') host.command_stop = request.form.get('command_stop') host.command_restart = request.form.get('command_restart') host.server_name = request.form.get('server_name') host.server_type = request.form.get('server_type') host.server = request.form.get('server') host.users = [current_user] host.ssh_port = request.form.get('ssh_port') host.key = form.security_key.data if form.submit.data: if method == 'PUT': host.id = host_id if request.form.get('security') == '1': host.key = None else: host.password = None logger.info( 'execute update operation type <%s> primary key <%s>', logger_type, host_id) if HostService().update_one(host): return redirect(url_for('host_view.index')) elif request.method == 'POST': if HostService().add(host): return redirect(url_for('host_view.index')) if form.test_connection.data: ssh_connect = Ssh(hostname=host.hostname, port=host.ssh_port, username=host.username, password=host.password, private_key=host.key) if ssh_connect.check_connect() is False: flash('用户 <{}> 连接主机 <{}> 失败,错误如下:\r\n{}'.format( host.hostname, host.username, ssh_connect.get_message())) else: flash('用户 <{}> 连接主机 <{}> 成功!'.format(host.hostname, host.username)) if StringUtils().is_not_empty(method): return redirect( url_for('host_view.create_modfiy_copy_delete', host_id=host_id, method=method)) else: return redirect( url_for('host_view.create_modfiy_copy_delete', host_id=host_id)) return render_template('host/host.html', form=form, host=host, title=title, active_menu='host')