-
-
Save lidaobing/d2d2a12fd885553d5d1bf0d31b631e99 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#coding=utf-8 | |
import json, os, sys, uuid, datetime, subprocess, traceback | |
def runCmd(cmd): | |
return [str(x) for x in subprocess.check_output(cmd, shell=True).splitlines()] | |
def getServerId(): | |
try: | |
return open('/tmp/serverId').read() | |
except IOError: | |
serverId = str(uuid.uuid4())+" "+str(datetime.datetime.now()) | |
ofile = open('/tmp/serverId', 'w') | |
ofile.write(serverId) | |
ofile.close() | |
return serverId | |
def handler(event, context): | |
try: | |
return handler2(event, context) | |
except Exception as e: | |
exstr = traceback.format_exc() | |
result = { | |
'statusCode': 500, | |
'headers': {'Content-Type': 'application/json; charset=utf-8'}, | |
'body': json.dumps({ | |
"exception": exstr.splitlines(), | |
})} | |
return result | |
def handler2(event, context): | |
reqid = event['detail']["headers"]["x-jdcloud-request-id"] | |
print(reqid) | |
serverId = None | |
try: | |
serverId = getServerId() | |
except Exception as e: | |
serverId = str(e) | |
cmds = event['detail']["queryParameters"].get("cmds", None) | |
if cmds is None: | |
cmds = [] | |
elif type(cmds) is str: | |
cmds = [cmds] | |
cmdResult = [] | |
for cmd in cmds: | |
cmdResult.append([cmd, runCmd(cmd)]) | |
result = { | |
'statusCode': 200, | |
'headers': {'Content-Type': 'application/json; charset=utf-8'}, | |
'body': json.dumps({ | |
'serverId': serverId, | |
"sys.version": sys.version, | |
"event":event, | |
"uid":os.getuid(), | |
"context":str(context), | |
"cmdResult": cmdResult, | |
#"environ":dict(os.environ.items()), | |
}), | |
} | |
return result | |
if __name__ == '__main__': | |
event = { | |
"version": "0", | |
"id": "6a7e8feb-b491-4cf7-a9f1-bf3703467718", | |
"time": "2006-01-02T15:04:05.999999999Z", | |
"source": "apigateway", | |
"base64OwnerPin": "NTk0MDM1MjYzMDE5", | |
"resources": [], | |
"region": "cn-north-1", | |
"detailType": "ApiGatewayReceived", | |
"detail": { | |
"path": "api request path", | |
"httpMethod": "GET/POST/DELETE/PUT/PATCH", | |
"headers": { | |
"x-jdcloud-request-id": "headerValue" | |
}, | |
"pathParameters": { | |
"pathParam": "pathValue" | |
}, | |
"queryParameters": { | |
"cmds": ["df", "df"], | |
}, | |
"body": "string of request payload", | |
"requestContext": { | |
"stage": "test", | |
"apiId": "testsvc", | |
"identity": { | |
"accountId": "", | |
"apiKey": "", | |
"user": "", | |
"authType": "" | |
}, | |
"requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", | |
"sourceIp": "10.0.2.14" | |
} | |
} | |
} | |
print(handler(event, None)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment