Python??????????С???????
?????jianjianjianbing ???????[ 2017/3/22 13:49:14 ] ??????????????? Python
???????????????Ь????????????????Python????????????
????????Ь???Python?????????????????????????????????????????????Python??????????????????????????????Щ?????????????????????Ч???к?????????
????????????Py??????????Щ??????????С?????·???????????????Win10 + Py3.5????ɡ?
????????CMD
????subprocess??Python?????????????????飬????????????????????????????????Щ????????(standard stream)????(pipe)?????????????????????????
?????????????????CMD???????????????????subprocess??????????????
????????1??????SVN????
?????????SVN??????????????????????????????SVN??????????μ???????????????鷳???
????import subprocess
????subprocess.Popen(r'TortoiseProc.exe /command:update /path:"C:project??????" /closeonend:0')
????subprocess.Popen(r'TortoiseProc.exe /command:update /path:"C:project???????" /closeonend:0')
????????2??adb???????
????????????β???????adb????ù??????????????????????apk??????ж???????????APK???????????????????????????????
???????????????????????apk??package??activity????
def run_cmd(cmd):
"""???CMD????"""
p = subprocess.Popen(cmd?? stdout=subprocess.PIPE)
return [i.decode() for i in p.communicate()[0].splitlines()]
def get_apk_info():
"""???apk??package??activity????
:return: list eg ['com.android.calendar'?? 'com.meizu.flyme.calendar.AllInOneActivity']
"""
result = run_cmd("adb shell dumpsys activity top")
for line in result:
if line.strip().startswith('ACTIVITY'):
return line.split()[1].split('/')
print(get_apk_info())
output: ['com.android.calendar'?? 'com.meizu.flyme.calendar.AllInOneActivity']
????????????apk????????
def get_mem_using(package_name=None):
"""??apk????????
:param package_name:
:return: ??λKB
"""
if not package_name:
package_name = get_apk_info()[0]
result = run_cmd("adb shell dumpsys meminfo {}".format(package_name))
info = re.search('TOTALW+d+'?? str(result)).group()
mem = ''
try:
mem = info.split()
except Exception as e:
print(info)
print(e)
return mem[-1]
output: 37769
???????籸????apk??????
def backup_current_apk(path=r"C:UsersjianbingDesktopapks"):
package = get_apk_info()[0]
result = run_cmd("adb shell pm path {}".format(package))
cmd = "adb pull {} {}".format(result[0].split(":")[-1]?? os.path.join(path?? "{}.apk".format(package)))
print(cmd)
run_cmd(cmd)
???????????????????adb???????????ADB????????????????Ь????????????????
???????????
???????????????????????????????
????????????????汾???????????????????????????????????????????????????????????鷽???????????????????????????????????
??????д????????????????????????????????ɡ?
import os
def get_files_by_suffix(path?? suffixes=("txt"?? "xml")?? traverse=True):
"""??path·???£????????????????????
:param path: ????
:param suffixes: ????????????????
:param traverse: ????False????????????
:return:
"""
file_list = []
for root?? dirs?? files in os.walk(path):
for file in files:
file_suffix = os.path.splitext(file)[1][1:].lower() # ?????
if file_suffix in suffixes:
file_list.append(os.path.join(root?? file))
if not traverse:
return file_list
return file_list
if __name__ == '__main__':
keyword = "XXX????"
files = get_files_by_suffix(r"C:projectconfig")
for file in files:
with open(file?? 'r'?? encoding='utf-8'?? errors='ignore') as f:
content = f.read().lower()
position = content.find(keyword.lower())
if position != -1:
print("Find in {0}".format(file))
start = position - 100 if position - 100 > 0 else 0
end = position + 100 if position + 100 < len(content) else len(content)
print(content[start:end])
print("_" * 100)
?????????????????
????????1???????????????
????????????????????????????????????????????????е???????????????????????~
???????????????FTP???????????????????????????????????????????????
????????????Py????~
????paramiko??Python??????????????????SSH2Э?飬?????????????????????????????????????
import paramiko
import time
_transport = paramiko.Transport("192.168.1.10:22")
_transport.connect(username="root"?? password="XXXXXX")
sftp = paramiko.SFTPClient.from_transport(_transport)
result = sftp.listdir_attr("/data/www/sg/sg_dev/socket/conf/config/treasure")
print("??????????{}".format(time.strftime("%Y-%m-%d %H:%M:%S"?? time.localtime(result[0].st_mtime))))
sftp.close()
????????2???????????????
????????в??????????????????????????μ???????????Щ???????????????????????????????????????????????SecureCRT????????????????CD??Log???£????tail -n 200 sg_error.log ???μ?????????
??????????????д???С????????????????????????????????????
import datetime
import paramiko
import time
import os
class ScanError(object):
def __init__(self):
self._ssh = paramiko.SSHClient()
self.last_error_log = None
self._init()
def _init(self):
os.chdir("data") # ??????????????浽data????
self._ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self._ssh.connect("192.168.1.10"?? username="root"?? password="XXXXXX")
error_log = self.get_error_log(500)
self.last_error_log = error_log
# ????????????б??????
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
the_day_before_yesterday = today - datetime.timedelta(days=2)
error_log_str = "
".join(error_log)
if error_log_str.find(str(today)) > -1 or error_log_str.find(str(yesterday)) > -1 or error_log_str.find(str(the_day_before_yesterday)) > -1:
self.save_error_log("error.txt"?? error_log)
print('???????????д???????????')
os.popen('error.txt')
def get_error_log(self?? num=200):
cmd = 'cd /data/www/sg/sg_dev/socket/log&&tail -n {} sg_error.log'.format(num)
stdin?? stdout?? stderr = self._ssh.exec_command(cmd)
error_log = [i.decode("utf-8") for i in stdout.read().splitlines() if i]
return error_log
@staticmethod
def save_error_log(file_name?? log: list):
with open(file_name?? 'w'?? encoding='utf-8') as f:
f.write("
".join(log))
def run_forever(self?? interval=30?? show_error=True):
"""???м????
:param interval: ?????
:param show_error: ???????????????????
:return:
"""
while 1:
time.sleep(interval)
error_log = self.get_error_log()
if error_log != self.last_error_log and "
".join(set(error_log) - set(self.last_error_log)).find("ERROR") > -1:
self.last_error_log = error_log
file_name = time.strftime("%Y-%m-%d-%H-%M-%S.txt"?? time.localtime(time.time()))
print('{} ??????????μ???????'.format(time.strftime("%Y-%m-%d %H:%M:%S"?? time.localtime(time.time()))))
self.save_error_log(file_name?? error_log)
if show_error:
os.popen(file_name)
if __name__ == '__main__':
ScanError().run_forever()
????????????
???????????????
???????????????????N???????????????а????????????????????????????Pythonд????????????????????
import cymysql
player_name = "XXXXXX"
conn = cymysql.connect(host='XXXXXX'?? user='sg'?? passwd='XXXXXX'?? db="dev"?? charset='utf8')
cur = conn.cursor()
sql = "select * from Player where name like '%{0}%'".format(player_name) # ?????????????????????????ID
cur.execute(sql)
for r in cur.fetchall():
sql = "select * from Account where uid = '{0}'".format(r[0]) # ?????ID??????????
cur.execute(sql)
for row in cur.fetchall():
print('{0}?? {1}?? {2}'.format(r[0]?? r[1]?? row[2])) # ?????????
conn.close()
??????????????????
?????????????????????????????????????????????????????????????????????????????????????????д????ID?????????б??????????????????????????????д??????
???????????????????????Ч???????????????????????????????????????д????????????????м??????????????á?
?????????????????????????????????????????????????????????HTTP???????????Python???????~
import requests
player_id = 1100000103
server_ip = "192.168.1.21:5000"
data = {"stuffList": []}
url = "http://{}/api/{}/stuff".format(server_ip?? player_id)
data["stuffList"].append({"itemID": 1104000007?? "number": 1000}) # itemID?1104000007???????????1000
data["stuffList"].append({"itemID": 1104000008?? "number": 1000})
data["stuffList"].append({"itemID": 1104000009?? "number": 1000})
data["stuffList"].append({"itemID": 1104000010?? "number": 1000})
data["stuffList"].append({"itemID": 1104000011?? "number": 1000})
data["stuffList"].append({"itemID": 1104000012?? "number": 1000})
requests.post(url?? json=data?? timeout=5) # ??????
# requests.delete(url?? json=data?? timeout=5) # ???????
????????з????????????????~
??????
???·???
??????????????????
2023/3/23 14:23:39???д?ò??????????
2023/3/22 16:17:39????????????????????Щ??
2022/6/14 16:14:27??????????????????????????
2021/10/18 15:37:44???????????????
2021/9/17 15:19:29???·???????·
2021/9/14 15:42:25?????????????
2021/5/28 17:25:47??????APP??????????
2021/5/8 17:01:11