Zabbix 2.2.2
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket sock = socket.socket() sock.connect(('localhost', 9090)) sock.send('/usr/bin/konsole -e mc') sock.close()
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket import subprocess sock = socket.socket() sock.bind(('localhost', 9090)) sock.listen(1) while True: conn, addr = sock.accept() data = conn.recv(1024) if not data: break subprocess.call(data, shell=True) conn.close()
-e mc
parameter indicates that the midnight commander file manager should be started in the console. #!/usr/bin/env python # -*- coding: utf-8 -*- import socket import sys sock = socket.socket() sock.connect(('localhost', 9090)) sock.send('/usr/bin/konsole -e ssh root@'+ sys.argv[1]) sock.close()
root
. ssh -f -N -R 9090:127.0.0.1:9090 zabbix
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket import sys sock = socket.socket() sock.connect(('localhost', 9090)) os = sock.recv(64) if os == "Windows": sock.send('C:\\apps\\putty.exe -ssh root@' + sys.argv[1]) elif os == "Linux": sock.send('/usr/bin/konsole -e ssh root@'+ sys.argv[1]) sock.close()
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket import subprocess OS = "Linux" sock = socket.socket() sock.bind(('127.0.0.1', 9090)) sock.listen(1) while True: conn, addr = sock.accept() conn.sendall(OS) data = conn.recv(1024) print data if not data: break subprocess.call(data, shell=True) conn.close()
\\
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket import sys if sys.argv[2] == 'Admin': PORT=9090 elif sys.argv[2] == 'Admin1': PORT=9091 sock = socket.socket() sock.connect(('localhost', PORT)) os = sock.recv(64) if os == "Windows": sock.send('C:\\apps\\putty.exe -ssh root@' + sys.argv[1]) elif os == "Linux": sock.send('/usr/bin/konsole -e ssh root@'+ sys.argv[1]) sock.close()
<?php /* ** Zabbix ** Copyright (C) 2001-2014 Zabbix SIA ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **/ require_once dirname(__FILE__).'/include/config.inc.php'; $page['title'] = _('Scripts'); $page['file'] = 'scripts_exec.php'; define('ZBX_PAGE_NO_MENU', 1); require_once dirname(__FILE__).'/include/page_header.php'; $NewCommand4Run = '/usr/local/bin/client_ssh.py {HOST.IP} '. CWebUser::$data['alias']; // VAR TYPE OPTIONAL FLAGS VALIDATION EXCEPTION $fields = array( 'hostid' => array(T_ZBX_INT, O_OPT, P_ACT, DB_ID, null), 'scriptid' => array(T_ZBX_INT, O_OPT, null, DB_ID, null) ); check_fields($fields); ob_flush(); flush(); $scriptId = getRequest('scriptid'); $hostId = getRequest('hostid'); $data = array( 'message' => '', 'info' => DBfetch(DBselect('SELECT s.name FROM scripts s WHERE s.scriptid='.zbx_dbstr($scriptId))) ); if ($scriptId == 5) { DBexecute('update zabbix.scripts set command='."'".$NewCommand4Run."'".' where scriptid=5;'); } $result = API::Script()->execute(array( 'hostid' => $hostId, 'scriptid' => $scriptId )); $isErrorExist = false; if (!$result) { $isErrorExist = true; } elseif ($result['response'] == 'failed') { error($result['value']); $isErrorExist = true; } else { $data['message'] = $result['value']; } if ($isErrorExist) { show_error_message( _('Cannot connect to the trapper port of zabbix server daemon, but it should be available to run the script.') ); } // render view $scriptView = new CView('general.script.execute', $data); $scriptView->render(); $scriptView->show(); require_once dirname(__FILE__).'/include/page_footer.php';
$NewCommand4Run = '/usr/local/bin/client.py {HOST.IP} '. CWebUser::$data['alias'];
if ($scriptId == 5) { DBexecute('update zabbix.scripts set command='."'".$NewCommand4Run."'".' where scriptid=5;'); }
-rwxr-xr-x 1 root staff 429 Mar 17 03:06 client_ssh.py -rwxr-xr-x 1 root staff 418 Mar 17 04:58 client_telnet.py -rwxr-xr-x 1 root staff 412 Mar 17 05:00 client_vnc.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket import sys if sys.argv[2] == 'Admin': PORT=9090 elif sys.argv[2] == 'Admin1': PORT=9091 sock = socket.socket() sock.connect(('localhost', PORT)) os = sock.recv(64) if os == "Windows": sock.send('C:\\apps\\putty.exe -ssh root@' + sys.argv[1]) elif os == "Linux": sock.send('/usr/bin/konsole -e ssh root@'+ sys.argv[1]) sock.close()
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket import sys if sys.argv[2] == 'Admin': PORT=9090 elif sys.argv[2] == 'Admin1': PORT=9091 sock = socket.socket() sock.connect(('localhost', PORT)) os = sock.recv(64) if os == "Windows": sock.send('c:\\apps\\vnc.exe ' + sys.argv[1]) elif os == "Linux": sock.send('/usr/bin/X11/gvncviewer '+ sys.argv[1]) sock.close()
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket import sys if sys.argv[2] == 'Admin': PORT=9090 elif sys.argv[2] == 'Admin1': PORT=9091 sock = socket.socket() sock.connect(('localhost', PORT)) os = sock.recv(64) if os == "Windows": sock.send('C:\\apps\\putty.exe -telnet ' + sys.argv[1]) elif os == "Linux": sock.send('/usr/bin/konsole -e telnet '+ sys.argv[1]) sock.close()
c:\apps\
<?php /* ** Zabbix ** Copyright (C) 2001-2014 Zabbix SIA ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. **/ require_once dirname(__FILE__).'/include/config.inc.php'; $page['title'] = _('Scripts'); $page['file'] = 'scripts_exec.php'; define('ZBX_PAGE_NO_MENU', 1); require_once dirname(__FILE__).'/include/page_header.php'; $NewCommand4RunSSH = '/usr/local/bin/client_ssh.py {HOST.IP} '. CWebUser::$data['alias']; $NewCommand4RunVNC = '/usr/local/bin/client_vnc.py {HOST.IP} '. CWebUser::$data['alias']; $NewCommand4RunTELNET = '/usr/local/bin/client_telnet.py {HOST.IP} '. CWebUser::$data['alias']; // VAR TYPE OPTIONAL FLAGS VALIDATION EXCEPTION $fields = array( 'hostid' => array(T_ZBX_INT, O_OPT, P_ACT, DB_ID, null), 'scriptid' => array(T_ZBX_INT, O_OPT, null, DB_ID, null) ); check_fields($fields); ob_flush(); flush(); $scriptId = getRequest('scriptid'); $hostId = getRequest('hostid'); $data = array( 'message' => '', 'info' => DBfetch(DBselect('SELECT s.name FROM scripts s WHERE s.scriptid='.zbx_dbstr($scriptId))) ); if ($scriptId == 5) { DBexecute('update zabbix.scripts set command='."'".$NewCommand4RunSSH."'".' where scriptid=5;'); } if ($scriptId == 6) { DBexecute('update zabbix.scripts set command='."'".$NewCommand4RunVNC."'".' where scriptid=6;'); } if ($scriptId == 7) { DBexecute('update zabbix.scripts set command='."'".$NewCommand4RunTELNET."'".' where scriptid=7;'); } $result = API::Script()->execute(array( 'hostid' => $hostId, 'scriptid' => $scriptId )); $isErrorExist = false; if (!$result) { $isErrorExist = true; } elseif ($result['response'] == 'failed') { error($result['value']); $isErrorExist = true; } else { $data['message'] = $result['value']; } if ($isErrorExist) { show_error_message( _('Cannot connect to the trapper port of zabbix server daemon, but it should be available to run the script.') ); } // render view $scriptView = new CView('general.script.execute', $data); $scriptView->render(); $scriptView->show(); require_once dirname(__FILE__).'/include/page_footer.php';
fessae@workbook:~/sh/python > pwd /home/fessae/sh/python fessae@workbook:~/sh/python > ll total 12 -rwxr-xr-x 1 fessae fessae 2880 Feb 28 02:56 daemon.py* -rwxr-xr-x 1 fessae fessae 710 Mar 17 03:36 server.py* -rwxr-xr-x 1 fessae fessae 1122 Mar 13 04:59 ZabbixTeams.py*
#!/usr/bin/env python import sys, os, time, atexit from signal import SIGTERM class Daemon: """ A generic daemon class. Usage: subclass the Daemon class and override the run() method """ def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'): self.stdin = stdin self.stdout = stdout self.stderr = stderr self.pidfile = pidfile def daemonize(self): """ do the UNIX double-fork magic, see Stevens' "Advanced Programming in the UNIX Environment" for details (ISBN 0201563177) http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16 """ try: pid = os.fork() if pid > 0: # exit first parent sys.exit(0) except OSError, e: sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror)) sys.exit(1) # decouple from parent environment os.chdir("/") os.setsid() os.umask(0) # do second fork try: pid = os.fork() if pid > 0: # exit from second parent sys.exit(0) except OSError, e: sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror)) sys.exit(1) # redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() si = file(self.stdin, 'r') so = file(self.stdout, 'a+') se = file(self.stderr, 'a+', 0) os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) # write pidfile atexit.register(self.delpid) pid = str(os.getpid()) file(self.pidfile,'w+').write("%s\n" % pid) def delpid(self): os.remove(self.pidfile) def start(self): """ Start the daemon """ # Check for a pidfile to see if the daemon already runs try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None if pid: message = "pidfile %s already exist. Daemon already running?\n" sys.stderr.write(message % self.pidfile) sys.exit(1) # Start the daemon self.daemonize() self.run() def stop(self): """ Stop the daemon """ # Get the pid from the pidfile try: pf = file(self.pidfile,'r') pid = int(pf.read().strip()) pf.close() except IOError: pid = None if not pid: message = "pidfile %s does not exist. Daemon not running?\n" sys.stderr.write(message % self.pidfile) return # not an error in a restart # Try killing the daemon process try: while 1: os.kill(pid, SIGTERM) time.sleep(0.1) except OSError, err: err = str(err) if err.find("No such process") > 0: if os.path.exists(self.pidfile): os.remove(self.pidfile) else: print str(err) sys.exit(1) def restart(self): """ Restart the daemon """ self.stop() self.start() def run(self): """ You should override this method when you subclass Daemon. It will be called after the process has been daemonized by start() or restart(). """
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket import subprocess import sys OS = "Linux" def main(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Socket created' try: sock.bind(('127.0.0.1', 9090)) except socket.error , msg: print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() print 'Socket bind complete' sock.listen(1) print 'Socket now listening' while True: conn, addr = sock.accept() conn.sendall(OS) data = conn.recv(1024) print 'Connected with ' + addr[0] + ':' + str(addr[1]) print data if not data: break subprocess.call(data, shell=True) conn.close() if __name__ == "__main__": main()
#/usr/bin/env python #-*- coding: utf-8 -*- import sys sys.path.append("/home/fessae/sh/python") from daemon import Daemon import server class ZabbixTeams(Daemon): def run(self): while True: server.main() if __name__ == "__main__": daemon = ZabbixTeams('/tmp/zabbixteams.pid',stdout='/tmp/zabbixteams.log',stderr='/tmp/zabbixteamserr.log') if len(sys.argv) == 2: if 'start' == sys.argv[1]: daemon.start() elif 'stop' == sys.argv[1]: daemon.stop() elif 'restart' == sys.argv[1]: daemon.restart() else: print "Unknown command" sys.exit(2) sys.exit(0) else: print "usage: %s start|stop|restart" % sys.argv[0] sys.exit(2)
python ZabbixTeams.py start
python ZabbixTeams.py stop
sys.path.append("/home/fessae/sh/python")
c:\Python27\python.exe C:\Users\FessAectan\PycharmProjects\ZabbixTeams\daemon.py
import sys import subprocess CREATE_NO_WINDOW = 0x8000000 subprocess.Popen(["c:\Python27\python.exe", "-O","C:\Users\FessAectan\PycharmProjects\ZabbixTeams\server.py"], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags = CREATE_NO_WINDOW)
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket import subprocess OS = "Windows" def main(): sock = socket.socket() print "Socket created" try: sock.bind(('127.0.0.1', 9091)) except socket.error , msg: print "Bind failed. Error Code : " + str(msg[0]) + " Message " + msg[1] sys.exit() print "Socket bind complete" sock.listen(1) print "Socket now listening" while True: conn, addr = sock.accept() conn.sendall(OS) data = conn.recv(1024) print "Connected with " + addr[0] + ":" + str(addr[1]) if not data: break subprocess.Popen(data, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags = 0x00000008) conn.close() if __name__ == "__main__": main()
Source: https://habr.com/ru/post/217161/
All Articles