├── README.md
├── cmdb-api.py
├── dodb.py
├── dsear.py
├── gameops.py
├── get_local_wip.py
├── ldap.py
├── monitor_log.py
├── opsmod.py
├── psf.py
├── scan_web_banner.py
├── ssh_cmd.py
├── ssh_excel.py
├── unix_time_format.py
├── zabbix-api.py
└── zabbix_update_pj-api.py
/README.md:
--------------------------------------------------------------------------------
1 | ### 运维通用python脚本框架
2 |
3 |
4 | * 日常运维:
5 | [*opsmod.py*](https://github.com/honglongwei/python-scripts/blob/master/opsmod.py)
6 |
7 | * python操作mysql的原生sql:
8 | [*dodb.py*](https://github.com/honglongwei/python-scripts/blob/master/dodb.py)
9 |
10 | * zabbix修改可见名称API:
11 | [*zabbix_update_pj-api.py*](https://github.com/honglongwei/python-scripts/blob/master/zabbix_update_pj-api.py)
12 |
13 | * zabbix通用API:
14 | [*zabbix-api.py*](https://github.com/honglongwei/python-scripts/blob/master/zabbix-api.py)
15 |
16 | * CMDB通用API:
17 | [*cmdb-api.py*](https://github.com/honglongwei/python-scripts/blob/master/cmdb-api.py)
18 |
19 | * 递归检索:
20 | [*dsear.py*](https://github.com/honglongwei/python-scripts/blob/master/dsear.py)
21 |
22 | * Python八大排序算法的实现:
23 | [*psf.py*](https://github.com/honglongwei/python-scripts/blob/master/psf.py)
24 |
25 | * 远程执行命令、远程添加信任、远程自动分区挂盘:
26 | [*ssh_cmd.py*](https://github.com/honglongwei/python-scripts/blob/master/ssh_cmd.py)
27 |
28 | * 基于saltstack的nested输出的运维脚本:
29 | [*gameops.py*](https://github.com/honglongwei/python-scripts/blob/master/gameops.py)
30 |
31 | * 游戏日志监控脚本:
32 | [*monitor_log.py*](https://github.com/honglongwei/python-scripts/blob/master/monitor_log.py)
33 |
34 | * 扫描服务器生成Excel报表:
35 | [*ssh_excel.py*](https://github.com/honglongwei/python-scripts/blob/master/ssh_excel.py)
36 |
37 | * Web扫描:
38 | [*scan_web_banner.py*](https://github.com/honglongwei/python-scripts/blob/master/scan_web_banner.py)
39 |
40 | * Unix时间戳转换:
41 | [*unix_time_format.py*](https://github.com/honglongwei/python-scripts/blob/master/unix_time_format.py)
42 |
43 | * LDAP认证:
44 | [*ldap.py*](https://github.com/honglongwei/python-scripts/blob/master/ldap.py)
45 |
46 | * 获取本机公网出口IP:
47 | [*get_local_wip.py*](https://github.com/honglongwei/python-scripts/blob/master/get_local_wip.py)
48 |
--------------------------------------------------------------------------------
/cmdb-api.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | import urllib
5 | import urllib2
6 | import json
7 |
8 |
9 | def hostname(IP):
10 | url = 'http://www.baidu.com/restful/getAssetByIpAddress'
11 | user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
12 | values = {'ipAddress': IP}
13 | headers = {'User-Agent': user_agent}
14 | data = urllib.urlencode(values)
15 | req = urllib2.Request(url, data, headers)
16 | response = urllib2.urlopen(req)
17 | res = response.read()
18 | data = json.loads(res)
19 | return data
20 |
--------------------------------------------------------------------------------
/dodb.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | #_*_ coding:utf-8 _*_
3 |
4 | import MySQLdb
5 |
6 |
7 | with open('/var/logs/install.log') as f:
8 | a = f.read().strip().split('\n')
9 | hostl = []
10 | for i in a:
11 | b = i.split('\t')
12 | if b[3] == 'stop':
13 | hostl.append(b[1])
14 | else:
15 | pass
16 | for host in list(set(hostl)):
17 | conn= MySQLdb.connect(
18 | host='localhost',
19 | port = 3306,
20 | user='root',
21 | passwd='111111',
22 | db ='pj_install',
23 | )
24 | try:
25 | #select
26 | sql = "select * from automsg where HostName='{0}'".format(host)
27 | cur = conn.cursor()
28 | cur.execute(sql)
29 | ret = cur.fetchone()
30 |
31 | #update
32 | update_sql = "update installretmsg set status=2, msg=u'安装成功!' where id={0}".format(int(ret[0]))
33 | cur.execute(update_sql)
34 |
35 | cur.close()
36 | conn.commit()
37 | conn.close()
38 | except:
39 | pass
40 |
--------------------------------------------------------------------------------
/dsear.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf8 -*-
3 |
4 | import os
5 | import sys
6 | import time
7 | import re
8 | import zipfile
9 | import datetime
10 | from subprocess import Popen
11 |
12 | #groupid
13 | gid = ''
14 | #src update package path
15 | src_path = 'D:\\update'
16 | #des update package path
17 | des_path = 'D:\\'
18 | #process list
19 | pro_lt = ''
20 | #src backup package path
21 | bsrc_path_lt = ['D:\\bin', 'D:\\conf', 'D:\\tdata']
22 | #des backup package path
23 | bdes_path = 'D:\\backup'
24 |
25 |
26 | def check_start():
27 | filelist = os.listdir('D:{0}\\Log'.format(gid))
28 | fls = []
29 | for filename in filelist:
30 | log_list = ['', '', '', '', '']
31 | for file_log in log_list:
32 | log_s = file_log + '_' + datetime.datetime.now().strftime('%Y%m%d%H')
33 | if filename.startswith(log_s) and filename.endswith('.txt'):
34 | fl_nm = os.path.join('D:{0}\\Log'.format(gid), filename)
35 | with open(fl_nm) as f:
36 | if 'Server initialize end server started!' in f.read():
37 | ret = '{0} - Ok!'.format(filename)
38 | fls.append(ret)
39 | else:
40 | ret = '{0} - Failed!'.format(filename)
41 | fls.append(ret)
42 | else:
43 | pass
44 | rtfl = []
45 | for srnm in ['', '', '', '', '']:
46 | retls = []
47 | for dnm in fls:
48 | if re.match(srnm, dnm):
49 | retls.append(dnm)
50 | else:
51 | pass
52 | rtfl.append(retls[-1])
53 | if 'Failed!' in ''.join(rtfl):
54 | print ''.join(rtfl).replace('!', '\n')
55 | sys.exit(1)
56 | else:
57 | return ''.join(rtfl).replace('!', '\n')
58 |
59 | print check_start()
60 |
--------------------------------------------------------------------------------
/gameops.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf8 -*-
3 |
4 | __author__ = 'honglongwei'
5 |
6 | import os
7 | import sys
8 | import time
9 | import zipfile
10 | import datetime
11 | import subprocess
12 | import salt.client
13 | from salt.output.nested import NestDisplay
14 | from salt.utils import get_colors
15 |
16 | #script path
17 | sct_lt = {'start': '/home/game/startup.sh',
18 | 'stop': '/home/game/shutdown.sh'
19 | }
20 | #pid path
21 | ser_pid = '/home/game/game.pid'
22 | #src update package path
23 | src_path = '/home/update'
24 | #des update package path
25 | des_path = '/home'
26 | #src backup package path
27 | bsrc_path_lt = ['/home/game/config',
28 | '/home/game/data',
29 | '/home/game/hibernate']
30 | #des backup package path
31 | bdes_path = '/home/backup'
32 |
33 |
34 | # call salt output class
35 | class NestPut(NestDisplay):
36 | def __init__(self):
37 | self.colors = get_colors(True)
38 | self.__dict__.update(get_colors(True))
39 | self.strip_colors = True
40 |
41 | def Prest(data):
42 | '''
43 | Display ret data
44 | '''
45 | nest = NestPut()
46 | print '\n'.join(nest.display(data, 0, '', []))
47 |
48 |
49 | def start():
50 | '''
51 | Define func start server
52 | '''
53 | if os.path.exists(ser_pid):
54 | return Prest('GameServer is already running !!!')
55 | else:
56 | cmd = sct_lt['start']
57 | proc = subprocess.Popen(cmd, shell=True)
58 | return Prest('Start GameServer is successful !!!')
59 |
60 |
61 | def stop():
62 | '''
63 | Define func stop server
64 | '''
65 | if os.path.exists(ser_pid):
66 | cmd = sct_lt['stop']
67 | proc = subprocess.Popen(cmd, shell=True)
68 | return Prest('Stop GameServer is successful !!!')
69 | else:
70 | return Prest('GameServer is already stopped !!!')
71 |
72 |
73 | def status():
74 | '''
75 | Define func status server
76 | '''
77 | if os.path.exists(ser_pid):
78 | return Prest('GameServer is not running !!!')
79 | else:
80 | cmd = 'ps -ef|grep \'{0}\'|grep -v grep'.format('server')
81 | proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
82 | ret = proc.stdout.read()
83 | return Prest(ret)
84 |
85 |
86 | def backup():
87 | '''
88 | Define func backup server
89 | '''
90 | bakname = 'gs_' + datetime.datetime.now().strftime('%Y%m%d%H%M%S') + '.zip'
91 | zipname = os.path.join(bdes_path, bakname)
92 | f = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED)
93 | for bsrc_path in bsrc_path_lt:
94 | bac_path = os.path.dirname(bsrc_path)
95 | ls_path = bac_path + '/'
96 | zg_path = bsrc_path.split(ls_path)[1]
97 | os.chdir(bac_path)
98 | for dirpath, dirnames, filenames in os.walk(zg_path):
99 | for filename in filenames:
100 | f.write(os.path.join(dirpath, filename))
101 | f.close()
102 | return 'Backup is successful !'
103 |
104 |
105 | def update(pkg):
106 | '''
107 | Define func update server
108 | '''
109 | if pkg:
110 | fl = os.path.join(src_path, pkg)
111 | try:
112 | zfile = zipfile.ZipFile(fl,'r')
113 | for filename in zfile.namelist():
114 | zfile.extract(filename, des_path)
115 | return 'Update is successful !'
116 | except IOError:
117 | return 'The package is invalid !!!'
118 | else:
119 | return 'The package is invalid !!!'
120 |
121 |
122 |
123 | if __name__== "__main__":
124 | # check arguments
125 | opts = sys.argv
126 | if len(opts) < 2:
127 | print 'start|stop|status|backup|update'
128 | sys.exit(0)
129 | elif len(opts) == 2:
130 | if opts[1]=='start':
131 | start()
132 | elif opts[1]=='stop':
133 | stop()
134 | elif opts[1]=='status':
135 | status()
136 | elif opts[1]=='backup':
137 | backup()
138 | else:
139 | print 'Script Parameter Error !!!'
140 | elif len(opts) == 3:
141 | if opts[1]=='update':
142 | update(opts[2])
143 | else:
144 | print 'Script Parameter Error !!!'
145 | else:
146 | print 'Script Parameter Error !!!'
147 |
--------------------------------------------------------------------------------
/get_local_wip.py:
--------------------------------------------------------------------------------
1 | #coding:utf-8
2 |
3 | import os
4 | import Queue
5 | import codecs
6 | import requests
7 | import threading, subprocess
8 | from time import ctime, sleep, time
9 | from bs4 import BeautifulSoup
10 |
11 | def get_out_ip(url):
12 | req = requests.get(url)
13 |
14 | if req.encoding == 'ISO-8859-1':
15 | encodings = requests.utils.get_encodings_from_content(req.text)
16 | if encodings:
17 | encoding = encodings[0]
18 | else:
19 | encoding = req.apparent_encoding
20 | global encode_content
21 | encode_content = req.content.decode(encoding, 'replace')
22 |
23 | return encode_content[encode_content.find("
") + 1: encode_content.find("")].replace("center>", "")
24 |
25 | def get_real_url(url=r'http://www.ip138.com/'):
26 | r = requests.get(url)
27 | txt = r.text
28 | soup = BeautifulSoup(txt,"html.parser").iframe
29 | return soup["src"]
30 |
31 | class ThreadUrl(threading.Thread):
32 | def __init__(self,queue):
33 | threading.Thread.__init__(self)
34 | self.queue = queue
35 |
36 | def run(self):
37 | while True:
38 | host = self.queue.get()
39 | ret = subprocess.Popen('ping -n 600 '+ host, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
40 | with open('iflytek/{0}.log'.format(host), 'a') as f:
41 | print >>f, ret.stdout.read()
42 | self.queue.task_done()
43 |
44 | def startPing():
45 | for i in range(100):
46 | t=ThreadUrl(queue)
47 | t.setDaemon(True)
48 | t.start()
49 | for host in ['140.143.0.175', '39.107.78.159', '120.92.31.91', '117.121.21.146', '117.121.21.146', '42.62.116.34', '42.62.42.10', '121.201.83.170', '59.107.24.5']:
50 | queue.put(host)
51 | queue.join()
52 |
53 | if __name__ == '__main__':
54 | print '*'*40
55 | print '*' + u' 欢迎使用网络质量检测工具 ' + '*'
56 | print '*' + ' ' + '*'
57 | print '*' + u' 程序运行过程中,请不要关闭程序窗口! ' + '*'
58 | print '*'*40
59 | if not os.path.exists('iflytek'):
60 | os.makedirs('iflytek')
61 | ip = get_out_ip(get_real_url())
62 | f = codecs.open('iflytek/ISP.log', 'w', 'utf-8')
63 | f.write(ip)
64 | queue = Queue.Queue()
65 | ret = startPing()
66 |
67 |
68 | #pip install pyinstaller
69 | #pyinstaller -F get_local_wip.py >> dist/get_local_wip.exe
70 |
--------------------------------------------------------------------------------
/ldap.py:
--------------------------------------------------------------------------------
1 | #!usr/bin/env python
2 | #coding: utf-8
3 |
4 | import os
5 | import sys
6 | import ldap
7 |
8 | def login_ldap(username, password):
9 | try:
10 | # print("开始执行")
11 | Server = "ldap://8.8.8.8:389"
12 | baseDN = "dc=baidu,dc=com"
13 | searchScope = ldap.SCOPE_SUBTREE
14 | # 设置过滤属性,这里只显示cn=test的信息
15 | searchFilter = "sAMAccountName=" + username
16 | # 为用户名加上域名
17 | username = 'baidu\\' + username
18 |
19 |
20 | # None表示搜索所有属性,['cn']表示只搜索cn属性
21 | retrieveAttributes = None
22 |
23 | conn = ldap.initialize(Server)
24 | #非常重要
25 | conn.set_option(ldap.OPT_REFERRALS, 0)
26 | conn.protocol_version = ldap.VERSION3
27 | # 这里用户名是域账号的全名例如domain/name
28 | #print conn.simple_bind_s(username, password)
29 | conn.simple_bind_s(username, password)
30 | # print 'ldap connect successfully'
31 |
32 |
33 | #调用search方法返回结果id
34 | ldap_result_id = conn.search(baseDN, searchScope, searchFilter, retrieveAttributes)
35 | result_set = []
36 | #print ldap_result_id
37 |
38 | #print("****************")
39 | while 1:
40 | result_type, result_data = conn.result(ldap_result_id, 0)
41 | if(result_data == []):
42 | break
43 | else:
44 | if result_type == ldap.RES_SEARCH_ENTRY:
45 | result_set.append(result_data)
46 |
47 | #print result_set
48 | Name,Attrs = result_set[0][0]
49 | if hasattr(Attrs, 'has_key') and Attrs.has_key('name'):
50 | ret = {}
51 | #distinguishedName = Attrs['mail'][0]
52 | #distinguishedName = Attrs['name'][0]
53 | #distinguishedName = Attrs['displayName'][0]
54 | #distinguishedName = Attrs['mail'][0]
55 | #distinguishedName = Attrs['memberOf'][0]
56 | #distinguishedName = Attrs['mailNickname'][0]
57 | #distinguishedName = Attrs['sAMAccountName'][0]
58 | #distinguishedName = Attrs['distinguishedName'][0]
59 | #distinguishedName = Attrs['title'][0]
60 | #distinguishedName = Attrs['department'][0]
61 | #distinguishedName = Attrs['manager'][0]
62 | # print "Login Info for user : %s" % distinguishedName
63 |
64 | ret['mail'] = Attrs['mail'][0]
65 | ret['username'] = Attrs['name'][0]
66 | ret['nickname'] = Attrs['displayName'][0]
67 | ret['sAMAccountName'] = Attrs['sAMAccountName'][0]
68 | ret['memberOf'] = Attrs['memberOf'][0]
69 | ret['distinguishedName'] = Attrs['distinguishedName'][0]
70 | ret['code'] = 200010
71 | # print Attrs['memberOf'][0]
72 | #print Attrs['sAMAccountName'][0]
73 |
74 | # print Attrs['title'][0]
75 | # print Attrs['department'][0]
76 |
77 |
78 |
79 | return ret
80 |
81 | else:
82 | return {'code': 400011, 'msg': u'认证失败'}
83 | except ldap.LDAPError, e:
84 | return {'code': 400012, 'msg': u'认证失败'}
85 |
86 | if __name__ == "__main__":
87 | username = "" # ldap中用户名
88 | password = "" # ldap中密码
89 |
90 | print login_ldap(username, password)
91 |
--------------------------------------------------------------------------------
/monitor_log.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf8 -*-
3 |
4 | import os
5 | import time
6 | import datetime
7 |
8 |
9 | def GetLog(num):
10 | fls = []
11 | for dirpath, dirnames, filenames in os.walk('/opt/logbak'):
12 | for filename in filenames:
13 | fn = os.path.join(dirpath, filename)
14 | now_time = datetime.datetime.now()
15 | last_time = now_time + datetime.timedelta(days=-num)
16 | tg_time = last_time.strftime('%Y-%m-%d')
17 | endf = tg_time + '.tgz'
18 | if filename.startswith('xxx_') and filename.endswith(endf):
19 | if os.path.exists(fn):
20 | fls.append(fn)
21 | else:
22 | pass
23 | else:
24 | pass
25 |
26 | xlog = []
27 | for a in fls:
28 | xlog.append(a[13:17])
29 | xlog.sort()
30 | return xlog
31 |
32 |
33 | blog = GetLog(2)
34 | alog = GetLog(1)
35 | '''
36 | 交集:list(set(a).intersection(set(b)))
37 | 并集:list(set(a).union(set(b)))
38 | 差集:list(set(b).difference(set(a))) // b中有而a中没有的
39 | '''
40 | jdata = set(blog).intersection(set(alog)) #交集
41 | mor = list(set(alog).difference(jdata)) #新增
42 | les = list(set(blog).difference(jdata)) #减少
43 | if len(mor) == 0 and len(les) == 0:
44 | print 0
45 | elif len(mor) == 0 and len(les) != 0:
46 | print '-: {0}'.format(','.join(les))
47 | elif len(mor) != 0 and len(les) == 0:
48 | print '+: {0}'.format(','.join(mor))
49 | else:
50 | print '+: {jia}\n-: {shao}'.format(jia=','.join(mor), shao=','.join(les))
51 |
--------------------------------------------------------------------------------
/opsmod.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | __author__ = 'honglongwei'
5 |
6 | import os
7 | import sys
8 | import time
9 | import zipfile
10 | import datetime
11 | import getpass
12 | import logging
13 | import subprocess
14 | from subprocess import Popen
15 |
16 |
17 | #src update package path
18 | src_path = '/home/mrdTomcat/update'
19 |
20 | #des update package path
21 | des_path = {'webap': '/home/app/webap/tomcat/webapps',
22 | 'apache': '/usr/local/apache',
23 | 'websocket': '/home/app/websocket/webapps',
24 | 'batch': '/home/app/tomcat/webapps',
25 | 'memcache': '/home/app/memcached',
26 | 'sdk': '/home/app/sdk/tomcat/webapps'}
27 |
28 | #src backup package path
29 | bsrc_path_lt = {'tomcat': ['/tmp/2', '/tmp/1'],
30 | 'apache': ['/usr/local/apache2/conf'],
31 | 'websocket': ['/tmp']}
32 |
33 | #des backup package path
34 | bdes_path = '/home/mrdTomcat/version_bak'
35 |
36 | #service name and server start bin
37 | srv_up = {'webap': '/home/app/webap/tomcat/bin/startup.sh',
38 | 'apache': '/usr/local/apache/bin/apachectl start',
39 | 'websocket': '/home/app/websocket/bin/jetty.sh start',
40 | 'batch': '/home/app/tomcat/bin/startup.sh',
41 | 'memcache': '/home/app/memcached/bin/start.sh',
42 | 'sdk': '/home/app/tomcat/bin/startup.sh'}
43 |
44 | #service name and server stop bin
45 | srv_down = {'webap': '/home/app/tomcat/bin/shutdown.sh',
46 | 'apache': '/usr/local/apache/bin/apachectl stop',
47 | 'websocket': '/home/app/websocket/bin/jetty.sh stop',
48 | 'batch': '/home/app/tomcat/bin/shutdown.sh',
49 | 'memcache': '/home/app/memcached/bin/stop.sh',
50 | 'sdk': '/home/app/tomcat/bin/shutdown.sh'}
51 |
52 | #server pidfile path
53 | srv_pidfile = {'webap': '/var/run/webap/webap.pid',
54 | 'apache': '',
55 | 'websocket': '',
56 | 'batch': '',
57 | 'memcache': '',
58 | 'sdk': ''}
59 |
60 |
61 | #change return color
62 | def G(s):
63 | return "%s[32;2m%s%s[0m"%(chr(27), s, chr(27))
64 | def A(s):
65 | return "%s[36;2m%s%s[0m"%(chr(27), s, chr(27))
66 | def R(s):
67 | return "%s[31;2m%s%s[0m"%(chr(27), s, chr(27))
68 |
69 |
70 | def start(ServiceName):
71 | '''
72 | Desc: Start GameServer
73 |
74 | CLI Example:
75 | opsmod.py ServiceName start
76 | '''
77 | pid = srv_pidfile[ServiceName]
78 | cmd = srv_up[ServiceName]
79 | logging.info('{0} start'.format(ServiceName))
80 | if os.path.exists(pid):
81 | return R('GameServer is already running !')
82 | else:
83 | proc = Popen(cmd, shell=True)
84 | return G('Start GameServer is successful !')
85 |
86 |
87 | def stop(ServiceName):
88 | '''
89 | Desc: Stop GameServer
90 |
91 | CLI Example:
92 | opsmod.py ServiceName stop
93 | '''
94 | pid = srv_pidfile[ServiceName]
95 | cmd = srv_down[ServiceName]
96 | logging.info('{0} stop'.format(ServiceName))
97 | if os.path.exists(pid):
98 | proc = Popen(cmd, shell=True)
99 | return G('Stop GameServer is running...,please wait !')
100 | else:
101 | return R('GameServer is already stopped !')
102 |
103 |
104 | def status(ServiceName):
105 | '''
106 | Desc: Check GameServer Status
107 |
108 | CLI Example:
109 | opsmod.py ServiceName status
110 | '''
111 | cmd = 'ps -ef|grep "{0}"|grep -v grep'.format(ServiceName)
112 | proc = Popen(cmd, stdout=subprocess.PIPE, shell=True)
113 | item = proc.stdout.read().split('\n')[:-2]
114 | its = '\n'.join(item)
115 | cot = len(item)
116 | ret = its + '\n' + '*'*80 + '\n' + 'The total of process is {0} !'.format(cot)
117 | logging.info('{0} status'.format(ServiceName))
118 | return G(ret)
119 |
120 |
121 | def update(ServiceName, Pkg):
122 | '''
123 | Desc: Update GameServer
124 |
125 | CLI Example:
126 | opsmod.py ServiceName update Pkg
127 | '''
128 | logging.info('{0} update {1}'.format(ServiceName, Pkg))
129 | if Pkg:
130 | fl = os.path.join(src_path, Pkg)
131 | try:
132 | zfile = zipfile.ZipFile(fl,'r')
133 | for filename in zfile.namelist():
134 | zfile.extract(filename, des_path[ServiceName])
135 | return G('Update is successful !')
136 | except IOError:
137 | return R('The package is invalid !!!')
138 | else:
139 | return R('The package is invalid !!!')
140 |
141 |
142 | def backup(ServiceName):
143 | '''
144 | Desc: Backup GameServer
145 |
146 | CLI Example:
147 | opsmod.py ServiceName backup
148 | '''
149 | logging.info('{0} backup'.format(ServiceName))
150 | bakname = ServiceName + '_' + datetime.datetime.now().strftime('%Y%m%d%H%M%S') + '.zip'
151 | zipname = os.path.join(bdes_path, bakname)
152 | f = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED)
153 | for bsrc_path in bsrc_path_lt[ServiceName]:
154 | bac_path = os.path.dirname(bsrc_path)
155 | ls_path = bac_path + '/'
156 | zg_path = bsrc_path.split(ls_path)[1]
157 | os.chdir(bac_path)
158 | for dirpath, dirnames, filenames in os.walk(zg_path):
159 | for filename in filenames:
160 | f.write(os.path.join(dirpath, filename))
161 | f.close()
162 | return G('Backup is successful !')
163 |
164 |
165 | if __name__== "__main__":
166 | if os.path.exists('./logs'):
167 | pass
168 | else:
169 | os.makedirs('./logs')
170 | log_ft = datetime.datetime.now().strftime('%Y-%m-%d-%H')
171 | user_cmd = getpass.getuser()
172 | logging.basicConfig(level=logging.DEBUG,
173 | format='%(asctime)s {0} %(levelname)s: %(message)s'.format(user_cmd),
174 | datefmt='%Y-%m-%d %H:%M:%S',
175 | filename='./logs/control{0}.log'.format(log_ft),
176 | filemode='a')
177 | opts = sys.argv
178 | try:
179 | if opts[1]=='-d' or opts[1]=='--help':
180 | print G('start :') + R('{0}'.format(start.__doc__))
181 | print G('stop :') + R('{0}'.format(stop.__doc__))
182 | print G('status :') + R('{0}'.format(status.__doc__))
183 | print G('update :') + R('{0}'.format(update.__doc__))
184 | print G('backup :') + R('{0}'.format(backup.__doc__))
185 | elif opts[2]=='start':
186 | print start(opts[1])
187 | elif opts[2]=='stop':
188 | print stop(opts[1])
189 | elif opts[2]=='status':
190 | print status(opts[1])
191 | elif opts[2]=='backup':
192 | print backup(opts[1])
193 | elif opts[2]=='update':
194 | print update(opts[1], opts[3])
195 | else:
196 | print R('Script Parameter Error !!!')
197 | except IndexError:
198 | print R('Script Parameter Error !!!')
199 |
200 |
--------------------------------------------------------------------------------
/psf.py:
--------------------------------------------------------------------------------
1 | 1、插入排序
2 | def insert_sort(lists):
3 | # 插入排序
4 | count = len(lists)
5 | for i in range(1, count):
6 | key = lists[i]
7 | j = i - 1
8 | while j >= 0:
9 | if lists[j] > key:
10 | lists[j + 1] = lists[j]
11 | lists[j] = key
12 | j -= 1
13 | return lists
14 |
15 | 2、希尔排序
16 | def shell_sort(lists):
17 | # 希尔排序
18 | count = len(lists)
19 | step = 2
20 | group = count / step
21 | while group > 0:
22 | for i in range(0, group):
23 | j = i + group
24 | while j < count:
25 | k = j - group
26 | key = lists[j]
27 | while k >= 0:
28 | if lists[k] > key:
29 | lists[k + group] = lists[k]
30 | lists[k] = key
31 | k -= group
32 | j += group
33 | group /= step
34 | return lists
35 |
36 | 3、冒泡排序
37 | def bubble_sort(lists):
38 | # 冒泡排序
39 | count = len(lists)
40 | for i in range(0, count):
41 | for j in range(i + 1, count):
42 | if lists[i] > lists[j]:
43 | lists[i], lists[j] = lists[j], lists[i]
44 | return lists
45 |
46 | 4、快速排序
47 | def quick_sort(lists, left, right):
48 | # 快速排序
49 | if left >= right:
50 | return lists
51 | key = lists[left]
52 | low = left
53 | high = right
54 | while left < right:
55 | while left < right and lists[right] >= key:
56 | right -= 1
57 | lists[left] = lists[right]
58 | while left < right and lists[left] <= key:
59 | left += 1
60 | lists[right] = lists[left]
61 | lists[right] = key
62 | quick_sort(lists, low, left - 1)
63 | quick_sort(lists, left + 1, high)
64 | return lists
65 |
66 | 5、直接选择排序
67 | def select_sort(lists):
68 | # 选择排序
69 | count = len(lists)
70 | for i in range(0, count):
71 | min = i
72 | for j in range(i + 1, count):
73 | if lists[min] > lists[j]:
74 | min = j
75 | lists[min], lists[i] = lists[i], lists[min]
76 | return lists
77 |
78 | 6、堆排序
79 | # 调整堆
80 | def adjust_heap(lists, i, size):
81 | lchild = 2 * i + 1
82 | rchild = 2 * i + 2
83 | max = i
84 | if i < size / 2:
85 | if lchild < size and lists[lchild] > lists[max]:
86 | max = lchild
87 | if rchild < size and lists[rchild] > lists[max]:
88 | max = rchild
89 | if max != i:
90 | lists[max], lists[i] = lists[i], lists[max]
91 | adjust_heap(lists, max, size)
92 | # 创建堆
93 | def build_heap(lists, size):
94 | for i in range(0, (size/2))[::-1]:
95 | adjust_heap(lists, i, size)
96 | # 堆排序
97 | def heap_sort(lists):
98 | size = len(lists)
99 | build_heap(lists, size)
100 | for i in range(0, size)[::-1]:
101 | lists[0], lists[i] = lists[i], lists[0]
102 | adjust_heap(lists, 0, i)
103 |
104 | 7、归并排序
105 | def merge(left, right):
106 | i, j = 0, 0
107 | result = []
108 | while i < len(left) and j < len(right):
109 | if left[i] <= right[j]:
110 | result.append(left[i])
111 | i += 1
112 | else:
113 | result.append(right[j])
114 | j += 1
115 | result += left[i:]
116 | result += right[j:]
117 | return result
118 | def merge_sort(lists):
119 | # 归并排序
120 | if len(lists) <= 1:
121 | return lists
122 | num = len(lists) / 2
123 | left = merge_sort(lists[:num])
124 | right = merge_sort(lists[num:])
125 | return merge(left, right)
126 |
127 | 8、基数排序
128 | import math
129 | def radix_sort(lists, radix=10):
130 | k = int(math.ceil(math.log(max(lists), radix)))
131 | bucket = [[] for i in range(radix)]
132 | for i in range(1, k+1):
133 | for j in lists:
134 | bucket[j/(radix**(i-1)) % (radix**i)].append(j)
135 | del lists[:]
136 | for z in bucket:
137 | lists += z
138 | del z[:]
139 | return lists
140 |
--------------------------------------------------------------------------------
/scan_web_banner.py:
--------------------------------------------------------------------------------
1 | #/usr/bin/env python
2 | #-*-coding=utf-8-*-
3 |
4 | # __author__ = 'Zline'
5 |
6 | import requests
7 | import re
8 | from threading import Thread,Lock
9 | import time
10 | import sys
11 | import chardet
12 | import netaddr
13 | import struct
14 | import socket
15 |
16 | lock = Lock()
17 |
18 | def ip2int(addr):
19 | return struct.unpack("!I", socket.inet_aton(addr))[0]
20 | def int2ip(addr):
21 | return socket.inet_ntoa(struct.pack("!I", addr))
22 | def int_dec(pagehtml):
23 |
24 | charset = None
25 | if pagehtml != '':
26 | # print 'use charset dect'
27 | enc = chardet.detect(pagehtml)
28 | # print 'enc= ', enc
29 | if enc['encoding'] and enc['confidence'] > 0.9:
30 | charset = enc['encoding']
31 |
32 | if charset == None:
33 | charset_re = re.compile("((^|;)\s*charset\s*=)([^\"']*)", re.M)
34 | charset=charset_re.search(pagehtml[:1000])
35 | charset=charset and charset.group(3) or None
36 |
37 | # test charset
38 | try:
39 | if charset:
40 | unicode('test',charset,errors='replace')
41 | except Exception,e:
42 | print 'Exception',e
43 | charset = None
44 | # print 'charset=', charset
45 | return charset
46 |
47 |
48 | def http_banner(url):
49 | ip=url
50 | try:
51 | url=requests.get(url,timeout=2)
52 |
53 | body = url.content
54 |
55 | charset = None
56 | if body != '':
57 | charset = int_dec(body)
58 |
59 | if charset == None or charset == 'ascii':
60 | charset = 'ISO-8859-1'
61 |
62 | if charset and charset != 'ascii' and charset != 'unicode':
63 | try:
64 | body = unicode(body,charset,errors='replace')
65 | except Exception, e:
66 | body = ''
67 | Struts=url.status_code
68 | Server=url.headers['server'][0:13]
69 | if Struts==200 or Struts==403 or Struts==401:
70 | title=re.findall(r"(.*)<\/title>",body)
71 | if len(title):
72 | title = title[0].strip()
73 | else:
74 | title = ''
75 | lock.acquire()
76 | print ('%s\t%d\t%-10s\t%s'%(ip.lstrip('http://'),Struts,Server,title))
77 | lock.release()
78 | except (requests.HTTPError,requests.RequestException,AttributeError,KeyError),e:
79 | pass
80 |
81 |
82 |
83 | if __name__ == '__main__':
84 | if len(sys.argv) >= 2:
85 | ips = sys.argv[1]
86 | else:
87 | print 'usage: python http_banner.py 192.168.1./24 '
88 | print 'usage: python http_banner.py 192.168.1.1-192.168.1.254 '
89 | print 'usage: python http_banner.py 192.168.1./24 8080'
90 | print 'usage: python http_banner.py 192.168.1.1-192.168.1.254 8080'
91 | sys.exit()
92 | port = '80'
93 | if len(sys.argv) == 3:
94 | port = sys.argv[2]
95 |
96 | if '-' in ips:
97 | start, end = ips.split('-')
98 | startlong = ip2int(start)
99 | endlong = ip2int(end)
100 | ips = netaddr.IPRange(start,end)
101 | for ip in list(ips):
102 | url='http://%s:%s'%(ip,port)
103 | t = Thread(target=http_banner,args=(url,))
104 | t.daemon=False
105 | t.start()
106 | elif '/' in ips:
107 | ips = netaddr.IPNetwork(ips)
108 | for ip in list(ips):
109 | url='http://%s:%s'%(ip,port)
110 | t = Thread(target=http_banner,args=(url,))
111 | t.daemon=False
112 | t.start()
113 |
--------------------------------------------------------------------------------
/ssh_cmd.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | import os
5 | import sys
6 | import time
7 | import argparse
8 | import datetime
9 | import paramiko
10 |
11 | reload(sys)
12 | sys.setdefaultencoding("utf-8")
13 |
14 | username = 'root'
15 | password = '123456'
16 |
17 | rsa = [
18 | 'ssh-rsa1',
19 | 'ssh-rsa2'
20 | ]
21 |
22 |
23 | #change return color
24 | def G(s):
25 | return "%s[32;2m%s%s[0m"%(chr(27), s, chr(27))
26 | def R(s):
27 | return "%s[31;2m%s%s[0m"%(chr(27), s, chr(27))
28 |
29 |
30 | def cmd_exc(ip, username, password):
31 | conn = paramiko.SSHClient()
32 | conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
33 | try:
34 | conn.connect(hostname = ip, username = username, password = password, timeout = 5)
35 | stdin, stdout, stderr = conn.exec_command(cmd)
36 | result = stdout.readlines()
37 | ret = ''.join(result)
38 | except:
39 | print R("无法连接")
40 | conn.close()
41 | try:
42 | return G(ret)
43 | except UnboundLocalError:
44 | pass
45 |
46 |
47 | def copy_rsa(ip, username, password):
48 | conn = paramiko.SSHClient()
49 | conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
50 | try:
51 | conn.connect(hostname = ip, username = username, password = password, timeout = 5)
52 | stdin, stdout, stderr = conn.exec_command("echo '{0}'>>/root/.ssh/authorized_keys;echo '{1}'>>/root/.ssh/authorized_keys".format(rsa[0], rsa[1]))
53 | result = stdout.readlines()
54 | ret = ''.join(result)
55 | except:
56 | print R("无法连接")
57 | conn.close()
58 | try:
59 | return G(ret)
60 | except UnboundLocalError:
61 | pass
62 |
63 |
64 | def auto_disk(Disk):
65 | if os.path.exists('./auto_disk.sh'):
66 | os.remove('./auto_disk.sh')
67 | with open('auto_disk.sh', 'a') as f:
68 | print >>f, '#!/bin/bash'
69 | print >>f, 'rpm -aq|grep expect'
70 | print >>f, 'if [ $? != 0 ];then'
71 | print >>f, ' yum install -y expect'
72 | print >>f, 'fi'
73 | print >>f, '/usr/bin/expect -c"'
74 | print >>f, 'set timeout -1'
75 | print >>f, 'spawn /sbin/fdisk /dev/{0}'.format(Disk)
76 | print >>f, 'expect \"*m for help*:\"'
77 | print >>f, 'send -- \"n\r\"'
78 | print >>f, 'expect \"*p*\n\"'
79 | print >>f, 'send -- \"p\r\"'
80 | print >>f, 'expect \"*number (1-4):\"'
81 | print >>f, 'send -- \"1\r\"'
82 | print >>f, 'expect \"*default 1*:\"'
83 | print >>f, 'send -- \"\r\"'
84 | print >>f, 'expect \"*default*:\"'
85 | print >>f, 'send -- \"\r\"'
86 | print >>f, 'expect \"*m for help*:\"'
87 | print >>f, 'send -- \"w\r\"'
88 | print >>f, 'expect eof'
89 | print >>f, '"'
90 | print >>f, 'mkfs.ext4 /dev/{0}1'.format(Disk)
91 | print >>f, 'echo "/dev/{0}1 /home/ ext4 defaults 0 0" >> /etc/fstab'.format(Disk)
92 | print >>f, 'mount /dev/{0}1 /home/'.format(Disk)
93 |
94 |
95 | def sftp_auto(ip, username, password):
96 | t = paramiko.Transport((ip,22))
97 | t.connect(username = username, password = password)
98 | sftp = paramiko.SFTPClient.from_transport(t)
99 | sftp.put('./auto_disk.sh','/tmp/auto_disk.sh')
100 | t.close()
101 | conn = paramiko.SSHClient()
102 | conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
103 | try:
104 | conn.connect(hostname = ip, username = username, password = password, timeout = 5)
105 | stdin, stdout, stderr = conn.exec_command('sh /tmp/auto_disk.sh')
106 | result = stdout.readlines()
107 | ret = ''.join(result)
108 | except:
109 | print R("无法连接")
110 | conn.close()
111 | try:
112 | return G(ret)
113 | except UnboundLocalError:
114 | pass
115 |
116 |
117 |
118 | if __name__ == "__main__":
119 | parser=argparse.ArgumentParser(description='ssh_cmd', usage='%(prog)s [options]')
120 | parser.add_argument('-H','--host', nargs='?', dest='listhost', help='主机/多个主机用","分割')
121 | parser.add_argument('-f','--file', nargs='?', dest='filehost', help='主机列表文件')
122 | parser.add_argument('-m','--command', nargs='?', dest='command', help='执行命令')
123 | parser.add_argument('-I','--init', nargs='?', dest='init', help='自动分区挂盘')
124 | parser.add_argument('-A','--add', nargs='?', dest='add_rsa', help='添加信任')
125 | if len(sys.argv)==1:
126 | parser.print_help()
127 | else:
128 | args=parser.parse_args()
129 | cmd = args.command
130 | if args.listhost is not None and args.filehost is None:
131 | if args.command is not None:
132 | for ip in args.listhost.split(','):
133 | print G(ip)
134 | print G('-'*80)
135 | print cmd_exc(ip, username, password)
136 | print
137 | elif args.init is not None:
138 | auto_disk(args.init)
139 | for ip in args.listhost.split(','):
140 | print G(ip)
141 | print G('-'*80)
142 | print sftp_auto(ip, username, password)
143 | print
144 | elif args.add_rsa == 'root':
145 | for ip in args.listhost.split(','):
146 | print G(ip)
147 | print G('-'*80)
148 | print copy_rsa(ip, username, password)
149 | print
150 | else:
151 | print R('功能选项为空')
152 | elif args.listhost is None and args.filehost is not None:
153 | if args.command is not None:
154 | try:
155 | with open(args.filehost) as f:
156 | for ips in f.readlines():
157 | ip = ips.replace('\n', '')
158 | print G(ip)
159 | print G('-'*80)
160 | print cmd_exc(ip, username, password)
161 | print
162 | except IOError:
163 | print R('主机列表文件不存在')
164 | elif args.init is not None:
165 | auto_disk(args.init)
166 | for ip in args.listhost.split(','):
167 | print G(ip)
168 | print G('-'*80)
169 | print sftp_auto(ip, username, password)
170 | print
171 | elif args.add_rsa == 'root':
172 | for ip in args.listhost.split(','):
173 | print G(ip)
174 | print G('-'*80)
175 | print copy_rsa(ip, username, password)
176 | print
177 | else:
178 | print R('功能选项为空')
179 | else:
180 | print R('主机或命令不能为空')
181 |
182 |
--------------------------------------------------------------------------------
/ssh_excel.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 |
5 | import os
6 | import sys
7 | import xlwt
8 | import time
9 | import json
10 | import urllib
11 | import urllib2
12 | import datetime
13 | import paramiko
14 | import commands
15 |
16 |
17 | reload(sys)
18 | sys.setdefaultencoding("utf-8")
19 |
20 | username = 'root'
21 | password = '123456'
22 |
23 | url_idc = 'http://www.baidu.com/assetInfo'
24 | url_clound = 'http://www.tengxun.com/cloudAsset'
25 |
26 | def GetAllSeal(url):
27 | user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
28 | if url == url_clound:
29 | values = {'test': 'demo'}
30 | elif url == url_idc:
31 | values = {'product': u'运维'}
32 | else:
33 | return 'URL is Error !!!'
34 | headers = {'User-Agent': user_agent}
35 | data = urllib.urlencode(values)
36 | req = urllib2.Request(url, data, headers)
37 | response = urllib2.urlopen(req)
38 | res = response.read()
39 | a = json.loads(res)
40 | return a
41 |
42 |
43 | def set_style(name, height, bold=False):
44 | style = xlwt.XFStyle()
45 |
46 | font = xlwt.Font()
47 | font.name = name
48 | font.bold = bold
49 | font.color_index = 4
50 | font.height = height
51 |
52 | style.font = font
53 | return style
54 |
55 | def WriteDateExcel():
56 | Tm = datetime.datetime.now().strftime('%Y-%m-%d')
57 | urls = [url_clound, url_idc]
58 | wbk = xlwt.Workbook(encoding='utf-8')
59 | for url in urls:
60 | result = GetAllSeal(url)
61 | if url == url_clound:
62 | sheet1 = wbk.add_sheet(u'云资产扫描结果', cell_overwrite_ok=True)
63 | row0 = [u'业务', u'负责人', u'外网IP', u'内网IP', u'操作系统', u'扫描结果']
64 | for x in xrange(len(row0)):
65 | sheet1.write(0, x, row0[x], set_style('Times New Roman',220,True))
66 | for i in xrange(len(result)):
67 | conn = paramiko.SSHClient()
68 | conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
69 | try:
70 | conn.connect(hostname = result[i]['WIp'], username = 'root', timeout = 1)
71 | stdin, stdout, stderr = conn.exec_command("iptables -nvL|grep -E '10.0.0.0/8|10.12.0.0/16'")
72 | cdt = stdout.readlines()
73 | ret = ''.join(cdt)
74 | except:
75 | ret = u'无法连接'
76 | contl = [result[i]['Name'], result[i]['Responser'], result[i]['WIp'], result[i]['LIp'], result[i]['os'], ret]
77 | for j in xrange(len(contl)):
78 | sheet1.write(i+1, j, contl[j])
79 | elif url == url_idc:
80 | sheet2 = wbk.add_sheet(u'物理机扫描结果', cell_overwrite_ok=True)
81 | row0 = [u'项目', u'负责人', u'外网IP', u'内网IP', u'操作系统', u'扫描结果']
82 | for x in xrange(len(row0)):
83 | sheet2.write(0, x, row0[x], set_style('Times New Roman',220,True))
84 | for i in xrange(len(result)):
85 | conn = paramiko.SSHClient()
86 | conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
87 | try:
88 | conn.connect(hostname = result[i]['wIp'], username = 'root', timeout = 1)
89 | stdin, stdout, stderr = conn.exec_command("iptables -nvL|grep -E '10.0.0.0/8|10.12.0.0/16'")
90 | cdt = stdout.readlines()
91 | ret = ''.join(cdt)
92 | except:
93 | ret = u'无法连接'
94 | contl = [result[i]['Name'], result[i]['Owner'], result[i]['wIp'], result[i]['lIp'], result[i]['os'], ret]
95 | for j in xrange(len(contl)):
96 | sheet2.write(i+1, j, contl[j])
97 | else:
98 | return 'URL is Error !!!'
99 | wbk.save('checkseal_{0}.xls'.format(Tm))
100 |
101 |
102 | if __name__ == "__main__":
103 | WriteDateExcel()
104 |
--------------------------------------------------------------------------------
/unix_time_format.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | import time
5 |
6 | def timestamp_datetime(value):
7 | format = '%Y-%m-%d %H:%M:%S'
8 | # value为传入的值为时间戳(整形),如:1332888820
9 | value = time.localtime(value)
10 | ## 经过localtime转换后变成
11 | ## time.struct_time(tm_year=2012, tm_mon=3, tm_mday=28, tm_hour=6, tm_min=53, tm_sec=40, tm_wday=2, tm_yday=88, tm_isdst=0)
12 | # 最后再经过strftime函数转换为正常日期格式。
13 | dt = time.strftime(format, value)
14 | return dt
15 |
16 | def datetime_timestamp(dt):
17 | #dt为字符串
18 | #中间过程,一般都需要将字符串转化为时间数组
19 | time.strptime(dt, '%Y-%m-%d %H:%M:%S')
20 | ## time.struct_time(tm_year=2012, tm_mon=3, tm_mday=28, tm_hour=6, tm_min=53, tm_sec=40, tm_wday=2, tm_yday=88, tm_isdst=-1)
21 | #将"2012-03-28 06:53:40"转化为时间戳
22 | s = time.mktime(time.strptime(dt, '%Y-%m-%d %H:%M:%S'))
23 | return int(s)
24 |
25 | if __name__ == '__main__':
26 | d = datetime_timestamp('2015-07-28 21:53:40')
27 | print d
28 | s = timestamp_datetime(1352889820)
29 | print s
30 |
--------------------------------------------------------------------------------
/zabbix-api.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python2.7
2 | #coding:utf-8
3 |
4 | import json
5 | import urllib2
6 | from urllib2 import URLError
7 | import sys,argparse
8 |
9 | class zabbix_api:
10 | def __init__(self):
11 | self.url = 'http://8.8.8.8/zabbix/api_jsonrpc.php' #修改URL
12 | self.header = {"Content-Type":"application/json"}
13 |
14 | def user_login(self):
15 | data = json.dumps({
16 | "jsonrpc": "2.0",
17 | "method": "user.login",
18 | "params": {
19 | "user": "Admin", #修改用户名
20 | "password": "Admin" #修改密码
21 | },
22 | "id": 0
23 | })
24 |
25 | request = urllib2.Request(self.url, data)
26 | for key in self.header:
27 | request.add_header(key, self.header[key])
28 |
29 | try:
30 | result = urllib2.urlopen(request)
31 | except URLError as e:
32 | print "\033[041m 用户认证失败,请检查 !\033[0m", e.code
33 | else:
34 | response = json.loads(result.read())
35 | result.close()
36 | #print response['result']
37 | self.authID = response['result']
38 | return self.authID
39 |
40 | def host_get(self,hostName=''):
41 | data=json.dumps({
42 | "jsonrpc": "2.0",
43 | "method": "host.get",
44 | "params": {
45 | "output": "extend",
46 | "filter":{"host":hostName}
47 | },
48 | "auth": self.user_login(),
49 | "id": 1
50 | })
51 | request = urllib2.Request(self.url,data)
52 | for key in self.header:
53 | request.add_header(key, self.header[key])
54 |
55 |
56 | try:
57 | result = urllib2.urlopen(request)
58 | except URLError as e:
59 | if hasattr(e, 'reason'):
60 | print 'We failed to reach a server.'
61 | print 'Reason: ', e.reason
62 | elif hasattr(e, 'code'):
63 | print 'The server could not fulfill the request.'
64 | print 'Error code: ', e.code
65 | else:
66 | response = json.loads(result.read())
67 | #print response
68 | result.close()
69 | print "主机数量: \033[31m%s\033[0m"%(len(response['result']))
70 | for host in response['result']:
71 | status={"0":"OK","1":"Disabled"}
72 | available={"0":"Unknown","1":"available","2":"Unavailable"}
73 | #print host
74 | if len(hostName)==0:
75 | print "HostID:\033[32m%s\033[0m\t Status:\033[32m%-8s\033[0m Available:\033[31m%-12s\033[0m HostName:%-30s VisbleName:%-40s"%(host['hostid'],status[host['status']],available[host['available']],host['host'],host['name'])
76 | else:
77 | print "HostID: \033[32m%s\033[0m\t Status:\033[32m%-8s\033[0m Available:\033[31m%-12s\033[0m HostName:%-30s VisbleName:%-40s"%(host['hostid'],status[host['status']],available[host['available']],host['host'],host['name'] )
78 | return host['hostid']
79 |
80 | def hostgroup_get(self, hostgroupName=''):
81 | data = json.dumps({
82 | "jsonrpc":"2.0",
83 | "method":"hostgroup.get",
84 | "params":{
85 | "output": "extend",
86 | "filter": {
87 | "name": hostgroupName
88 | }
89 | },
90 | "auth":self.user_login(),
91 | "id":1,
92 | })
93 |
94 | request = urllib2.Request(self.url,data)
95 | for key in self.header:
96 | request.add_header(key, self.header[key])
97 |
98 | try:
99 | result = urllib2.urlopen(request)
100 | except URLError as e:
101 | print "Error as ", e
102 | else:
103 | #print result.read()
104 | response = json.loads(result.read())
105 | result.close()
106 | #print response()
107 | for group in response['result']:
108 | if len(hostgroupName)==0:
109 | print "groupid : %s \t hostgroup: \033[31m%s\033[0m" %(group['groupid'],group['name'])
110 | else:
111 | print "hostgroup: \033[31m%s\033[0m\tgroupid : %s" %(group['name'],group['groupid'])
112 | self.hostgroupID = group['groupid']
113 | return group['groupid']
114 |
115 |
116 | def template_get(self,templateName=''):
117 | data = json.dumps({
118 | "jsonrpc":"2.0",
119 | "method": "template.get",
120 | "params": {
121 | "output": "extend",
122 | "filter": {
123 | "name":templateName
124 | }
125 | },
126 | "auth":self.user_login(),
127 | "id":1,
128 | })
129 |
130 | request = urllib2.Request(self.url, data)
131 | for key in self.header:
132 | request.add_header(key, self.header[key])
133 |
134 | try:
135 | result = urllib2.urlopen(request)
136 | except URLError as e:
137 | print "Error as ", e
138 | else:
139 | response = json.loads(result.read())
140 | result.close()
141 | #print response
142 | for template in response['result']:
143 | if len(templateName)==0:
144 | print "template_id : %s \t template_name : \033[31m%s\033[0m\t" % (template['templateid'],template['name'])
145 | else:
146 | self.templateID = response['result'][0]['templateid']
147 | print "Template Name : \033[31m%s\033[0m "%templateName
148 | return response['result'][0]['templateid']
149 | def hostgroup_create(self,hostgroupName):
150 |
151 | if self.hostgroup_get(hostgroupName):
152 | print "hostgroup \033[42m%s\033[0m is exist !"%hostgroupName
153 | sys.exit(1)
154 | data = json.dumps({
155 | "jsonrpc": "2.0",
156 | "method": "hostgroup.create",
157 | "params": {
158 | "name": hostgroupName
159 | },
160 | "auth": self.user_login(),
161 | "id": 1
162 | })
163 | request=urllib2.Request(self.url,data)
164 |
165 | for key in self.header:
166 | request.add_header(key, self.header[key])
167 |
168 | try:
169 | result = urllib2.urlopen(request)
170 | except URLError as e:
171 | print "Error as ", e
172 | else:
173 | response = json.loads(result.read())
174 | result.close()
175 | print "\033[042m 添加主机组:%s\033[0m hostgroupID : %s"%(hostgroupName,response['result']['groupids'])
176 |
177 |
178 |
179 | def host_create(self, hostip, hostgroupName, templateName):
180 | if self.host_get(hostip):
181 | print "\033[041m该主机已经添加!\033[0m"
182 | sys.exit(1)
183 |
184 | group_list=[]
185 | template_list=[]
186 | for i in hostgroupName.split(','):
187 | var = {}
188 | var['groupid'] = self.hostgroup_get(i)
189 | group_list.append(var)
190 | for i in templateName.split(','):
191 | var={}
192 | var['templateid']=self.template_get(i)
193 | template_list.append(var)
194 |
195 | data = json.dumps({
196 | "jsonrpc":"2.0",
197 | "method":"host.create",
198 | "params":{
199 | "host": hostip,
200 | "interfaces": [
201 | {
202 | "type": 1,
203 | "main": 1,
204 | "useip": 1,
205 | "ip": hostip,
206 | "dns": "",
207 | "port": "10050"
208 | }
209 | ],
210 | "groups": group_list,
211 | "templates": template_list,
212 | },
213 | "auth": self.user_login(),
214 | "id":1
215 | })
216 | request = urllib2.Request(self.url, data)
217 | for key in self.header:
218 | request.add_header(key, self.header[key])
219 |
220 | try:
221 | result = urllib2.urlopen(request)
222 | except URLError as e:
223 | print "Error as ", e
224 | else:
225 | response = json.loads(result.read())
226 | result.close()
227 | print "添加主机 : \033[42m%s\031[0m \tid :\033[31m%s\033[0m" % (hostip, response['result']['hostids'])
228 |
229 |
230 |
231 | def host_disable(self,hostip):
232 | data=json.dumps({
233 | "jsonrpc": "2.0",
234 | "method": "host.update",
235 | "params": {
236 | "hostid": self.host_get(hostip),
237 | "status": 1
238 | },
239 | "auth": self.user_login(),
240 | "id": 1
241 | })
242 | request = urllib2.Request(self.url,data)
243 | for key in self.header:
244 | request.add_header(key, self.header[key])
245 | try:
246 | result = urllib2.urlopen(request)
247 | except URLError as e:
248 | print "Error as ", e
249 | else:
250 | response = json.loads(result.read())
251 | result.close()
252 | print '----主机现在状态------------'
253 | print self.host_get(hostip)
254 |
255 |
256 | def host_delete(self,hostid):
257 | hostid_list=[]
258 | #print type(hostid)
259 | for i in hostid.split(','):
260 | var = {}
261 | var['hostid'] = self.host_get(i)
262 | hostid_list.append(var)
263 | data=json.dumps({
264 | "jsonrpc": "2.0",
265 | "method": "host.delete",
266 | "params": hostid_list,
267 | "auth": self.user_login(),
268 | "id": 1
269 | })
270 |
271 | request = urllib2.Request(self.url,data)
272 | for key in self.header:
273 | request.add_header(key, self.header[key])
274 |
275 | try:
276 | result = urllib2.urlopen(request)
277 | except Exception,e:
278 | print e
279 | else:
280 |
281 | result.close()
282 | print "主机 \033[041m %s\033[0m 已经删除 !"%hostid
283 |
284 |
285 | if __name__ == "__main__":
286 | zabbix=zabbix_api()
287 | parser=argparse.ArgumentParser(description='zabbix api ',usage='%(prog)s [options]')
288 | parser.add_argument('-H','--host',nargs='?',dest='listhost',default='host',help='查询主机')
289 | parser.add_argument('-G','--group',nargs='?',dest='listgroup',default='group',help='查询主机组')
290 | parser.add_argument('-T','--template',nargs='?',dest='listtemp',default='template',help='查询模板信息')
291 | parser.add_argument('-A','--add-group',nargs=1,dest='addgroup',help='添加主机组')
292 | #parser.add_argument('-C','--add-host',dest='addhost',nargs=3,metavar=('192.168.2.1', 'test01,test02', 'Template01,Template02'),help='添加主机,多个主机组或模板使用分号')
293 | parser.add_argument('-C','--add-host',dest='addhost',nargs=3,metavar=('60.28.211.88',"All Linux Server,线上服","Template OS Linux,Template ICMP Ping"),help='添加主机,多个主机组或模板使用分号')
294 | parser.add_argument('-d','--disable',dest='disablehost',nargs=1,metavar=('192.168.2.1'),help='禁用主机')
295 | parser.add_argument('-D','--delete',dest='deletehost',nargs='+',metavar=('192.168.2.1'),help='删除主机,多个主机之间用分号')
296 | parser.add_argument('-v','--version', action='version', version='%(prog)s 1.0')
297 | if len(sys.argv)==1:
298 | print parser.print_help()
299 | else:
300 | args=parser.parse_args()
301 |
302 | if args.listhost != 'host' :
303 | if args.listhost:
304 | zabbix.host_get(args.listhost)
305 | else:
306 | zabbix.host_get()
307 | if args.listgroup !='group':
308 | if args.listgroup:
309 | zabbix.hostgroup_get(args.listgroup)
310 | else:
311 | zabbix.hostgroup_get()
312 | if args.listtemp != 'template':
313 | if args.listtemp:
314 | zabbix.template_get(args.listtemp)
315 | else:
316 | zabbix.template_get()
317 | if args.addgroup:
318 | zabbix.hostgroup_create(args.addgroup[0])
319 | if args.addhost:
320 | zabbix.host_create(args.addhost[0], args.addhost[1], args.addhost[2])
321 | if args.disablehost:
322 | zabbix.host_disable(args.disablehost)
323 | if args.deletehost:
324 | zabbix.host_delete(args.deletehost[0])
325 |
--------------------------------------------------------------------------------
/zabbix_update_pj-api.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | import re
5 | import sys
6 | import json
7 | import urllib
8 | import urllib2
9 |
10 | class zabbixtools:
11 |
12 | def __init__(self, hostip, hostname):
13 | self.url = "http://8.8.8.8/zabbix/api_jsonrpc.php"
14 | self.header = {"Content-Type": "application/json"}
15 | self.authID = self.user_login()
16 | self.hostip = hostip.strip("\n")
17 | self.hostname = hostname.strip("\n")
18 |
19 | def user_login(self):
20 | data = json.dumps(
21 | {
22 | "jsonrpc": "2.0",
23 | "method": "user.login",
24 | "params": {
25 | "user": "zabbix",
26 | "password": "zabbix"
27 | },
28 | "id": 0
29 | })
30 |
31 | request = urllib2.Request(self.url,data)
32 | for key in self.header:
33 | request.add_header(key,self.header[key])
34 | try:
35 | result = urllib2.urlopen(request)
36 | except URLError as e:
37 | print "Auth Failed, Please Check Your Name And Password:"
38 | else:
39 | response = json.loads(result.read())
40 | result.close()
41 | authID = response['result']
42 | return authID
43 |
44 | def get_data(self,data,hostip=""):
45 | request = urllib2.Request(self.url,data)
46 | for key in self.header:
47 | request.add_header(key,self.header[key])
48 | try:
49 | result = urllib2.urlopen(request)
50 | except Exception,e:
51 | if hasattr(e,'reason'):
52 | print "we Failed to reach a server"
53 | print 'reason:',e.reason
54 | elif hasattr(e,'code'):
55 | print "the server could not fulfaild the request"
56 | print "error code:",e.code
57 | return 0
58 | else:
59 | response = json.loads(result.read())
60 | result.close()
61 | return response
62 |
63 |
64 | def host_get(self):
65 | # 生成json格式数据
66 | data = json.dumps(
67 | {
68 | "jsonrpc": "2.0",
69 | "method": "host.get",
70 | "params": {
71 | "output":["hostid","name","status","host"],
72 | "filter": {"host": [self.hostip]}
73 | },
74 | "auth": self.authID,
75 | "id": 1
76 | })
77 | res = self.get_data(data)['result']
78 | if (res != 0) and (len(res) != 0):
79 | host = res[0]
80 | return host['hostid']
81 | else:
82 | print "host_get error please check define host_get()"
83 | return 0
84 |
85 | def host_update(self):
86 | host = self.host_get()
87 | data = json.dumps(
88 | {
89 | "jsonrpc": "2.0",
90 | "method": "host.update",
91 | "params": {
92 | "hostid": host,
93 | "name": self.hostname.encode('utf8')
94 | },
95 | "auth": self.authID,
96 | "id": 1
97 | })
98 | res = self.get_data(data)
99 |
100 |
101 | def hostname(IP):
102 | url = 'http://www.baidu.com/restful/getAssetByIpAddress'
103 | user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
104 | values = {'ipAddress': IP}
105 | headers = {'User-Agent': user_agent}
106 | data = urllib.urlencode(values)
107 | req = urllib2.Request(url, data, headers)
108 | response = urllib2.urlopen(req)
109 | res = response.read()
110 | a = json.loads(res)
111 | #lable = a['returnedInfo']
112 | if a:
113 | lable = a[0]
114 | if len(lable):
115 | #leader = a['returnedInfo'][0]['productLeader']
116 | leader = a[0]['productLeader']
117 | jif = a[0]['cloudSource']
118 | #product = a['returnedInfo'][0]['productName']
119 | product = a[0]['productName']
120 | #os = a['returnedInfo'][0]['osInfo'][0:7]
121 | # os = a[0]['osInfo'][0:7]
122 | #owner = a['returnedInfo'][0]['productOwner']
123 | owner = a[0]['productOwner']
124 | HOSTNAME = "%s_%s_%s_%s_%s" % (IP, u"", product, u"", u"")
125 | return HOSTNAME
126 | else:
127 | return 0
128 | else:
129 | print IP
130 |
131 |
132 | if __name__ == "__main__":
133 | for line in open("hosts.log"):
134 | host = re.findall(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})', line)
135 | IP = host[0]
136 | print IP
137 | b = hostname(IP)
138 | if b:
139 | update = zabbixtools(line,b)
140 | update.host_update()
141 | else:
142 | print b
143 |
--------------------------------------------------------------------------------