xcloud пре 4 година
комит
924ad64960
100 измењених фајлова са 5154 додато и 0 уклоњено
  1. 11 0
      .idea/git-python.iml
  2. 6 0
      .idea/inspectionProfiles/profiles_settings.xml
  3. 4 0
      .idea/misc.xml
  4. 8 0
      .idea/modules.xml
  5. 6 0
      .idea/vcs.xml
  6. 103 0
      .idea/workspace.xml
  7. 3 0
      .vscode/settings.json
  8. 33 0
      AWS-test/1.py
  9. 13 0
      AWS-test/2.py
  10. 27 0
      AWS-test/3.py
  11. 251 0
      AWS-test/Api-Gateway-Lambda-Auth.py
  12. 36 0
      AWS-test/ApiGateway-REST-http_post.py
  13. 73 0
      AWS-test/EBS-snapsgots-test.py
  14. 31 0
      AWS-test/ElasticSearch-cw.py
  15. 171 0
      AWS-test/Lambda-SNS-sql.py
  16. 31 0
      AWS-test/Lambda-exec-sqs.py
  17. 144 0
      AWS-test/Rek_lambda.py
  18. 273 0
      AWS-test/api+ Dy_updata.py
  19. 140 0
      AWS-test/api_dy_sh.py
  20. 51 0
      AWS-test/awslogs + lambda.py
  21. 229 0
      AWS-test/cloudfront_sgs.py
  22. 169 0
      AWS-test/cstor-foundcation.py
  23. 12 0
      AWS-test/flask-post.py
  24. 31 0
      AWS-test/game.py
  25. 13 0
      AWS-test/import requests.py
  26. 381 0
      AWS-test/jam-sagamaker.py
  27. 69 0
      AWS-test/lambda_api_性能测试.py
  28. 52 0
      AWS-test/lambda_http.py
  29. 0 0
      AWS-test/password.txt
  30. 237 0
      AWS-test/phn-founation.py
  31. 73 0
      AWS-test/pro-aws-ebs-snapshot.py
  32. 10 0
      AWS-test/sec.txt
  33. 71 0
      AWS-test/server破解.py
  34. 6 0
      AWS-test/sh.py
  35. 68 0
      AWS-test/waf_ip_update.py
  36. 232 0
      AWS-test/zjw-foundation.py
  37. 126 0
      AWS-test/随机字符组合.py
  38. 1 0
      README.md
  39. 35 0
      aws-task-ruleless/jam-EDA.py
  40. 262 0
      awsClean/appclean.py
  41. 9 0
      myapp.log
  42. 0 0
      password.txt
  43. 31 0
      python_base/day10/函数的作用域关系.py
  44. 40 0
      python_base/day10/多层装饰器.py
  45. 18 0
      python_base/day10/递归函数实现.py
  46. 43 0
      python_base/day10/面向对象之类.py
  47. 20 0
      python_base/day11/属性.py
  48. 96 0
      python_base/day11/方法.py
  49. 22 0
      python_base/day11/类的继承.py
  50. 86 0
      python_base/day11/计算.py
  51. 16 0
      python_base/day11/面向对象.py
  52. 13 0
      python_base/day11/魔法函数(方法).py
  53. 14 0
      python_base/day12/cmdb/bin/run.py
  54. BIN
      python_base/day12/cmdb/plugins/__pycache__/cpu.cpython-37.pyc
  55. BIN
      python_base/day12/cmdb/plugins/__pycache__/mem.cpython-37.pyc
  56. 3 0
      python_base/day12/cmdb/plugins/cpu.py
  57. 3 0
      python_base/day12/cmdb/plugins/mem.py
  58. 7 0
      python_base/day12/cmdb/test.py
  59. 22 0
      python_base/day12/判断是否是某些类型的实例.py
  60. 28 0
      python_base/day12/方法的个性实验.py
  61. 28 0
      python_base/day12/私用属性.py
  62. 49 0
      python_base/day12/类的继承顺序.py
  63. 42 0
      python_base/day12/继承2.py
  64. 14 0
      python_base/day13/cmdb/bin/run.py
  65. 4 0
      python_base/day13/cmdb/conf/settings.py
  66. 18 0
      python_base/day13/cmdb/core/main.py
  67. BIN
      python_base/day13/cmdb/plugins/__pycache__/cpu.cpython-37.pyc
  68. BIN
      python_base/day13/cmdb/plugins/__pycache__/mem.cpython-37.pyc
  69. 3 0
      python_base/day13/cmdb/plugins/cpu.py
  70. 3 0
      python_base/day13/cmdb/plugins/mem.py
  71. 8 0
      python_base/day13/cmdb/test.py
  72. 11 0
      python_base/day13/反射倒入模块.py
  73. 35 0
      python_base/day13/自省与反射.py
  74. 42 0
      python_base/day13/自省与反射的概念.py
  75. 17 0
      python_base/day14/发送邮件.py
  76. 29 0
      python_base/day14/小爬虫学习.py
  77. 19 0
      python_base/day14/时间模块之预约时.py
  78. 12 0
      python_base/day14/正则表达式.py
  79. 30 0
      python_base/day15/JSON序列化.py
  80. 11 0
      python_base/day15/redis使用.py
  81. 59 0
      python_base/day15/异常处理.py
  82. 29 0
      python_base/day15/执行远程主机命令.py
  83. 103 0
      python_base/day15/日志模块.py
  84. 13 0
      python_base/day15/生产环境异常处理.py
  85. 56 0
      python_base/day16/可迭代对象和迭代器.py
  86. 55 0
      python_base/day16/抽象类.py
  87. 21 0
      python_base/day16/生成器.py
  88. 11 0
      python_base/day3/test.py
  89. 29 0
      python_base/day3/元组.py
  90. 49 0
      python_base/day3/列表.py
  91. 23 0
      python_base/day3/文件操作.py
  92. 54 0
      python_base/day4/cpu_info.txt
  93. 1 0
      python_base/day4/tempCodeRunnerFile.py
  94. 70 0
      python_base/day4/作业讲解.py
  95. 20 0
      python_base/day4/字典.py
  96. 118 0
      python_base/day4/字典高级操作.py
  97. 4 0
      python_base/day5/test.txt
  98. 64 0
      python_base/day5/字典.py
  99. 36 0
      python_base/day5/文件操作.py
  100. 1 0
      python_base/day6/tempCodeRunnerFile.py

+ 11 - 0
.idea/git-python.iml

@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module type="PYTHON_MODULE" version="4">
+  <component name="NewModuleRootManager">
+    <content url="file://$MODULE_DIR$" />
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+  </component>
+  <component name="TestRunnerService">
+    <option name="PROJECT_TEST_RUNNER" value="Unittests" />
+  </component>
+</module>

+ 6 - 0
.idea/inspectionProfiles/profiles_settings.xml

@@ -0,0 +1,6 @@
+<component name="InspectionProjectProfileManager">
+  <settings>
+    <option name="PROJECT_PROFILE" />
+    <version value="1.0" />
+  </settings>
+</component>

+ 4 - 0
.idea/misc.xml

@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ProjectRootManager" version="2" project-jdk-name="Python 3.6" project-jdk-type="Python SDK" />
+</project>

+ 8 - 0
.idea/modules.xml

@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ProjectModuleManager">
+    <modules>
+      <module fileurl="file://$PROJECT_DIR$/.idea/git-python.iml" filepath="$PROJECT_DIR$/.idea/git-python.iml" />
+    </modules>
+  </component>
+</project>

+ 6 - 0
.idea/vcs.xml

@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="VcsDirectoryMappings">
+    <mapping directory="$PROJECT_DIR$" vcs="Git" />
+  </component>
+</project>

+ 103 - 0
.idea/workspace.xml

@@ -0,0 +1,103 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project version="4">
+  <component name="ChangeListManager">
+    <list default="true" id="5cd848bb-c5da-41c6-9fe5-d59e7297debc" name="Default" comment="" />
+    <option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
+    <option name="TRACKING_ENABLED" value="true" />
+    <option name="SHOW_DIALOG" value="false" />
+    <option name="HIGHLIGHT_CONFLICTS" value="true" />
+    <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
+    <option name="LAST_RESOLUTION" value="IGNORE" />
+  </component>
+  <component name="Git.Settings">
+    <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
+  </component>
+  <component name="JsBuildToolGruntFileManager" detection-done="true" sorting="DEFINITION_ORDER" />
+  <component name="JsBuildToolPackageJson" detection-done="true" sorting="DEFINITION_ORDER" />
+  <component name="JsGulpfileManager">
+    <detection-done>true</detection-done>
+    <sorting>DEFINITION_ORDER</sorting>
+  </component>
+  <component name="ProjectFrameBounds">
+    <option name="x" value="162" />
+    <option name="y" value="43" />
+    <option name="width" value="1359" />
+    <option name="height" value="937" />
+  </component>
+  <component name="ProjectView">
+    <navigator currentView="ProjectPane" proportions="" version="1">
+      <flattenPackages />
+      <showMembers />
+      <showModules />
+      <showLibraryContents />
+      <hideEmptyPackages />
+      <abbreviatePackageNames />
+      <autoscrollToSource />
+      <autoscrollFromSource />
+      <sortByType />
+      <manualOrder />
+      <foldersAlwaysOnTop value="true" />
+    </navigator>
+    <panes>
+      <pane id="ProjectPane" />
+      <pane id="Scope" />
+      <pane id="Scratches" />
+    </panes>
+  </component>
+  <component name="PropertiesComponent">
+    <property name="WebServerToolWindowFactoryState" value="false" />
+  </component>
+  <component name="RunDashboard">
+    <option name="ruleStates">
+      <list>
+        <RuleState>
+          <option name="name" value="ConfigurationTypeDashboardGroupingRule" />
+        </RuleState>
+        <RuleState>
+          <option name="name" value="StatusDashboardGroupingRule" />
+        </RuleState>
+      </list>
+    </option>
+  </component>
+  <component name="ShelveChangesManager" show_recycled="false">
+    <option name="remove_strategy" value="false" />
+  </component>
+  <component name="TaskManager">
+    <task active="true" id="Default" summary="Default task">
+      <changelist id="5cd848bb-c5da-41c6-9fe5-d59e7297debc" name="Default" comment="" />
+      <created>1619678159665</created>
+      <option name="number" value="Default" />
+      <option name="presentableId" value="Default" />
+      <updated>1619678159665</updated>
+    </task>
+    <servers />
+  </component>
+  <component name="ToolWindowManager">
+    <frame x="162" y="43" width="1359" height="937" extended-state="0" />
+    <layout>
+      <window_info id="Project" active="true" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.24981017" sideWeight="0.5" order="0" side_tool="false" content_ui="combo" />
+      <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
+      <window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="true" content_ui="tabs" />
+      <window_info id="Database" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
+      <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
+      <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
+      <window_info id="Python Console" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
+      <window_info id="SciView" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
+      <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
+      <window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
+      <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
+      <window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="true" content_ui="tabs" />
+      <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
+      <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
+      <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
+      <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
+      <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
+      <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
+      <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
+    </layout>
+  </component>
+  <component name="XDebuggerManager">
+    <breakpoint-manager />
+    <watches-manager />
+  </component>
+</project>

+ 3 - 0
.vscode/settings.json

@@ -0,0 +1,3 @@
+{
+    "python.pythonPath": "/Library/Frameworks/Python.framework/Versions/3.8/bin/python3"
+}

+ 33 - 0
AWS-test/1.py

@@ -0,0 +1,33 @@
+# -*- coding: UTF-8 -*-
+
+from flask import Flask
+app = Flask(__name__)
+@app.route('/')
+def index():
+    return 'Hello World'
+if __name__ == '__main__':
+    app.debug = True # 设置调试模式,生产模式的时候要关掉debug
+    app.run()
+
+from flask import Flask, request, session
+import hmac
+import json
+
+key = b'HuiZhangDaDeXingFu'
+
+application = Flask(__name__)
+
+@application.route('/',methods=['POST', 'GET'])
+def index():
+    if request.method == 'GET':
+        name1 = print(request.headers)
+        return name1
+    if request.method == 'POST':
+        response = {'value':'','user_id': 888}
+        req = request.json
+        message = str.encode(req['msg'])
+        response['value'] = hmac.new(key, message, digestmod='MD5').hexdigest()
+        return response
+
+if __name__ == '__main__':
+    application.run(host='0.0.0.0', port='80')

+ 13 - 0
AWS-test/2.py

@@ -0,0 +1,13 @@
+from flask import Flask, request
+import json
+
+application = Flask(__name__)
+
+@application.route('/',methods=['POST', 'GET'])
+def index():
+    if request.method == 'GET':
+        response = dict(request.headers)
+        return str(response)
+
+if __name__ == '__main__':
+    application.run(host='0.0.0.0', port=80)

+ 27 - 0
AWS-test/3.py

@@ -0,0 +1,27 @@
+import json
+import boto3
+
+def lambda_handler(event, context):
+    # TODO implement
+    #print(event)
+    
+    ddb = boto3.client('dynamodb')
+    response = ddb.scan(TableName='zjw-test', Limit=100)
+    items = response['Items']
+    
+    #print(items)
+   # print(items[1]['message']['S'])
+    responseBody = []
+    responseDict = {}
+    for item in items:
+        responseDict['message'] = item['message']['S']
+        responseBody.append(responseDict)
+        print(responseDict)
+    print(responseBody)
+    
+        #responseDict['message'] = items[item]['message']['S']
+        #responseBody.append(responseDict)
+    return responseBody
+    #print(responseBody)
+    
+    #return items

+ 251 - 0
AWS-test/Api-Gateway-Lambda-Auth.py

@@ -0,0 +1,251 @@
+"""
+   Copyright 2018 Amazon.com, Inc. and its affiliates. All Rights Reserved.
+   Licensed under the MIT License. See the LICENSE accompanying this file
+   for the specific language governing permissions and limitations under
+   the License.
+"""
+from __future__ import print_function
+
+import os
+import re
+import json
+import logging
+import base64
+
+import boto3
+from aws_xray_sdk.core import xray_recorder
+from aws_xray_sdk.core import patch_all
+
+patch_all()
+
+# Static code used for DynamoDB connection and logging
+dynamodb = boto3.resource('dynamodb')
+table = dynamodb.Table(os.environ['TABLE_NAME'])
+log_level = os.environ['LOG_LEVEL']
+log = logging.getLogger(__name__)
+logging.getLogger().setLevel(log_level)
+
+
+def lambda_handler(event, context):
+    log.debug("Event: " + json.dumps(event))
+
+    # Ensure the incoming Lambda event is for a request authorizer
+    if event['type'] != 'REQUEST':
+        raise Exception('Unauthorized')
+
+    try:
+        # Set the principalId to the accountId making the authorizer call
+        principalId = event['requestContext']['accountId']
+
+        tmp = event['methodArn'].split(':')
+        apiGatewayArnTmp = tmp[5].split('/')
+        awsAccountId = tmp[4]
+
+        policy = AuthPolicy(principalId, awsAccountId)
+        policy.restApiId = apiGatewayArnTmp[0]
+        policy.region = tmp[3]
+        policy.stage = apiGatewayArnTmp[1]
+
+        # Get authorization header in lowercase
+        authorization_header = {k.lower(): v for k, v in event['headers'].items() if k.lower() == 'authorization'}
+        log.debug("authorization: " + json.dumps(authorization_header))
+
+        # Get the username:password hash from the authorization header
+        username_password_hash = authorization_header['authorization'].split()[1]
+        log.debug("username_password_hash: " + username_password_hash)
+
+        # Decode username_password_hash and get username
+        username = base64.standard_b64decode(username_password_hash).split(':')[0]
+        log.debug("username: " + username)
+
+        # Get the password from DynamoDB for the username
+        item = table.get_item(ConsistentRead=True, Key={"username": username})
+        if item.get('Item') is not None:
+            log.debug("item: " + json.dumps(item))
+            ddb_password = item.get('Item').get('password')
+            log.debug("ddb_password:" + json.dumps(ddb_password))
+
+            if ddb_password is not None:
+                ddb_username_password = (username + ":" + ddb_password)
+                ddb_username_password_hash = base64.standard_b64encode(ddb_username_password)
+                log.debug("ddb_username_password_hash:" + ddb_username_password_hash)
+
+                if username_password_hash == ddb_username_password_hash:
+                    policy.allowMethod(event['requestContext']['httpMethod'], event['path'])
+                    log.info("password match for: " + username)
+                else:
+                    policy.denyMethod(event['requestContext']['httpMethod'], event['path'])
+                    log.info("password does not match for: " + username)
+            else:
+                log.info("No password found for username:" + username)
+                policy.denyMethod(event['requestContext']['httpMethod'], event['path'])
+        else:
+            log.info("Did not find username: " + username)
+            policy.denyMethod(event['requestContext']['httpMethod'], event['path'])
+
+        # Finally, build the policy
+        authResponse = policy.build()
+        log.debug("authResponse: " + json.dumps(authResponse))
+
+        return authResponse
+    except Exception:
+        raise Exception('Unauthorized')
+
+
+class HttpVerb:
+    GET = "GET"
+    POST = "POST"
+    PUT = "PUT"
+    PATCH = "PATCH"
+    HEAD = "HEAD"
+    DELETE = "DELETE"
+    OPTIONS = "OPTIONS"
+    ALL = "*"
+
+
+class AuthPolicy(object):
+    awsAccountId = ""
+    """The AWS account id the policy will be generated for. This is used to create the method ARNs."""
+    principalId = ""
+    """The principal used for the policy, this should be a unique identifier for the end user."""
+    version = "2012-10-17"
+    """The policy version used for the evaluation. This should always be '2012-10-17'"""
+    pathRegex = "^[/.a-zA-Z0-9-\*]+$"
+    """The regular expression used to validate resource paths for the policy"""
+
+    """these are the internal lists of allowed and denied methods. These are lists
+    of objects and each object has 2 properties: A resource ARN and a nullable
+    conditions statement.
+    the build method processes these lists and generates the approriate
+    statements for the final policy"""
+    allowMethods = []
+    denyMethods = []
+
+    restApiId = "*"
+    """The API Gateway API id. By default this is set to '*'"""
+    region = "*"
+    """The region where the API is deployed. By default this is set to '*'"""
+    stage = "*"
+    """The name of the stage used in the policy. By default this is set to '*'"""
+
+    def __init__(self, principal, awsAccountId):
+        self.awsAccountId = awsAccountId
+        self.principalId = principal
+        self.allowMethods = []
+        self.denyMethods = []
+
+    def _addMethod(self, effect, verb, resource, conditions):
+        """Adds a method to the internal lists of allowed or denied methods. Each object in
+        the internal list contains a resource ARN and a condition statement. The condition
+        statement can be null."""
+        if verb != "*" and not hasattr(HttpVerb, verb):
+            raise NameError("Invalid HTTP verb " + verb + ". Allowed verbs in HttpVerb class")
+        resourcePattern = re.compile(self.pathRegex)
+        if not resourcePattern.match(resource):
+            raise NameError("Invalid resource path: " + resource + ". Path should match " + self.pathRegex)
+
+        if resource[:1] == "/":
+            resource = resource[1:]
+
+        resourceArn = ("arn:aws:execute-api:" +
+            self.region + ":" +
+            self.awsAccountId + ":" +
+            self.restApiId + "/" +
+            self.stage + "/" +
+            verb + "/" +
+            resource)
+
+        if effect.lower() == "allow":
+            self.allowMethods.append({
+                'resourceArn': resourceArn,
+                'conditions': conditions
+            })
+        elif effect.lower() == "deny":
+            self.denyMethods.append({
+                'resourceArn': resourceArn,
+                'conditions': conditions
+            })
+
+    def _getEmptyStatement(self, effect):
+        """Returns an empty statement object prepopulated with the correct action and the
+        desired effect."""
+        statement = {
+            'Action': 'execute-api:Invoke',
+            'Effect': effect[:1].upper() + effect[1:].lower(),
+            'Resource': []
+        }
+
+        return statement
+
+    def _getStatementForEffect(self, effect, methods):
+        """This function loops over an array of objects containing a resourceArn and
+        conditions statement and generates the array of statements for the policy."""
+        statements = []
+
+        if len(methods) > 0:
+            statement = self._getEmptyStatement(effect)
+
+            for curMethod in methods:
+                if curMethod['conditions'] is None or len(curMethod['conditions']) == 0:
+                    statement['Resource'].append(curMethod['resourceArn'])
+                else:
+                    conditionalStatement = self._getEmptyStatement(effect)
+                    conditionalStatement['Resource'].append(curMethod['resourceArn'])
+                    conditionalStatement['Condition'] = curMethod['conditions']
+                    statements.append(conditionalStatement)
+
+            statements.append(statement)
+
+        return statements
+
+    def allowAllMethods(self):
+        """Adds a '*' allow to the policy to authorize access to all methods of an API"""
+        self._addMethod("Allow", HttpVerb.ALL, "*", [])
+
+    def denyAllMethods(self):
+        """Adds a '*' allow to the policy to deny access to all methods of an API"""
+        self._addMethod("Deny", HttpVerb.ALL, "*", [])
+
+    def allowMethod(self, verb, resource):
+        """Adds an API Gateway method (Http verb + Resource path) to the list of allowed
+        methods for the policy"""
+        self._addMethod("Allow", verb, resource, [])
+
+    def denyMethod(self, verb, resource):
+        """Adds an API Gateway method (Http verb + Resource path) to the list of denied
+        methods for the policy"""
+        self._addMethod("Deny", verb, resource, [])
+
+    def allowMethodWithConditions(self, verb, resource, conditions):
+        """Adds an API Gateway method (Http verb + Resource path) to the list of allowed
+        methods and includes a condition for the policy statement. More on AWS policy
+        conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition"""
+        self._addMethod("Allow", verb, resource, conditions)
+
+    def denyMethodWithConditions(self, verb, resource, conditions):
+        """Adds an API Gateway method (Http verb + Resource path) to the list of denied
+        methods and includes a condition for the policy statement. More on AWS policy
+        conditions here: http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements.html#Condition"""
+        self._addMethod("Deny", verb, resource, conditions)
+
+    def build(self):
+        """Generates the policy document based on the internal lists of allowed and denied
+        conditions. This will generate a policy with two main statements for the effect:
+        one statement for Allow and one statement for Deny.
+        Methods that includes conditions will have their own statement in the policy."""
+        if ((self.allowMethods is None or len(self.allowMethods) == 0) and
+            (self.denyMethods is None or len(self.denyMethods) == 0)):
+            raise NameError("No statements defined for the policy")
+
+        policy = {
+            'principalId': self.principalId,
+            'policyDocument': {
+                'Version': self.version,
+                'Statement': []
+            }
+        }
+
+        policy['policyDocument']['Statement'].extend(self._getStatementForEffect("Allow", self.allowMethods))
+        policy['policyDocument']['Statement'].extend(self._getStatementForEffect("Deny", self.denyMethods))
+
+        return policy

+ 36 - 0
AWS-test/ApiGateway-REST-http_post.py

@@ -0,0 +1,36 @@
+import json
+import random
+
+def lambda_handler(event, context):
+   
+    #unchangable values
+
+    print(event)
+    #min=1
+    #max=10
+    
+    #integration changable values from url params
+    #min=int(event['queryStringParameters']['min'])
+    #max=int(event['queryStringParameters']['max'])
+    
+    #not integration changable values from mapping body
+    #min=int(event['min'])
+    #max=int(event['max'])
+    
+    # user post httpMethod 
+    par_init=json.loads(event['body'])
+    min=par_init['min']
+    max=par_init['max']
+    
+    
+    resp=random.randint(min,max)
+    
+    # not integration response
+    #return resp
+    
+    #integration response
+
+    return {
+        'statusCode': 200,
+        'body': resp
+    }

+ 73 - 0
AWS-test/EBS-snapsgots-test.py

@@ -0,0 +1,73 @@
+import boto3
+import os,time
+from botocore.exceptions import ClientError
+from datetime import datetime, timedelta, timezone
+
+AK = "AKIAR62ETW27TAM"
+SK = "B52Y/Rv0h2nOYjoE69d9Wo3"
+
+
+client = boto3.client('ec2',region_name='cn-northwest-1',aws_access_key_id=AK,
+    aws_secret_access_key=SK)
+ec2 = boto3.resource('ec2',region_name='cn-northwest-1',aws_access_key_id=AK,
+    aws_secret_access_key=SK)
+ddb = boto3.resource('dynamodb',region_name='cn-northwest-1',aws_access_key_id=AK,
+    aws_secret_access_key=SK)
+
+# 'EBS-Snapshot-Lifecycle' is the table you store snapshot metadata, modify it to your own table name
+table = ddb.Table('EBS-Snapshot-Lifecycle')
+
+
+DAYS_TO_RETAIN = 7
+
+def lambda_handler(event, context):
+
+    os.environ['TZ'] = 'Asia/Shanghai'
+    time.tzset()
+    i=time.strftime('%X %x %Z')
+    
+    volume_id_list = ['vol-0cb469d952fcf6108']
+
+    # set snapshot
+    for volume_id in volume_id_list:
+        volume = ec2.Volume(volume_id)
+    
+        for tags in volume.tags:
+            if(tags.get('Key') == 'Name'):
+                volume_name = tags.get('Value')
+        description = volume_name + ' volume snapshot is created at ' + i
+        
+        try:
+            response = client.create_snapshot(
+                Description=description,
+                # Description=i + ' -- ',
+                VolumeId=volume_id)
+        except Exception as e:
+            print('Create Snapshot occured error, Volume id is ' + volume_id)
+        else:
+            print('Snapshot is created succeed, Snapshot id is ' + response.get('SnapshotId'))
+        
+        # write into DynanoDB table
+        '''
+        snapshot_id = response.get('SnapshotId')
+        start_time = response.get('StartTime')
+        ttl_time = int(start_time.timestamp()) + 86400 * DAYS_TO_RETAIN
+    
+        try:
+            table.put_item(
+                Item={
+                    'snapshot_id': snapshot_id,
+                    'create_time': start_time.astimezone(timezone(timedelta(hours=8))).strftime('%X %x %Z'),
+                    'description': description,
+                    'timestamp': int(start_time.timestamp()),
+                    'ttl': ttl_time,
+                }
+            )
+        except:
+            print('Write to DynanoDB Table occured error, snapshot id is ' + snapshot_id)
+        else:
+            print('Write to DynanoDB Table succeed, snapshot id is ' + snapshot_id)
+
+        '''
+if __name__ == '__main__':
+    lambda_handler(None,None)

+ 31 - 0
AWS-test/ElasticSearch-cw.py

@@ -0,0 +1,31 @@
+import boto3
+import re,json,base64,gzip
+import requests
+from requests_aws4auth import AWS4Auth
+
+region = 'cn-northwest-1'
+service = 'es'
+credentials = boto3.Session().get_credentials()
+awsauth = AWS4Auth(credentials.access_key,credentials.secret_key,region,service,session_token=credentials.token)
+
+host = 'https://search-es-test-rssutkotldfmnca64hpfbi5jya.cn-northwest-1.es.amazonaws.com.cn'
+index = 'lambda-cw'
+type_a = 'lambda-type'
+url = host + '/' + index + '/' + type_a
+
+headers = {"Content-Type":"application/json"}
+
+
+def lambda_handler(event, context):
+
+    de_content = base64.b64decode(event['awslogs']['data'])
+    ret = json.loads(gzip.decompress(de_content).decode('utf8'))
+
+    # log_msg = ret['logEvents'][0]['message']
+    # tup_log = log_msg.split(' ', -1)
+    # tup_log = json.loads(tup_log)
+    # print(type(tup_log))
+
+    r = requests.post(url,auth=awsauth,json=ret,headers=headers)
+    print(r)
+    

+ 171 - 0
AWS-test/Lambda-SNS-sql.py

@@ -0,0 +1,171 @@
+# 1、 SQS——lambda
+import json
+import boto3
+import time
+import pymysql
+
+def updata_db(m_key,m_value):
+    conn2 = pymysql.connect(
+        host='a.xdc.ink',
+        port=3306,
+        user='root',
+        passwd='xclouds123',
+        db='cmd',
+        charset='utf8mb4')
+
+    cs2 = conn2.cursor()
+    select_sql = f'INSERT INTO kv (mykey, myvalue) VALUES ("{m_key}", "{m_value}");'
+    cs2.execute(select_sql)
+    conn2.commit()
+    cs2.close()
+    conn2.close()
+    
+def lambda_handler(event, context):
+    # print(event)
+    time.sleep(3)
+    body = event['Records'][0]['body']
+    m_key = event['Records'][0]['messageAttributes']['mykey']['stringValue']
+    # print("FORMSQS:" + m_key + ":" + body)
+    
+    ddb= boto3.client('dynamodb')
+    
+    table_name = 'found'
+ 
+    ddb.update_item(
+        TableName=table_name,
+
+        ExpressionAttributeValues={
+            ':y': {
+                'S': body,
+            }
+        },
+        Key={
+        'm_key': {
+            'S': m_key,
+        }
+        },
+        UpdateExpression='SET sqs = :y',
+        ReturnValues="UPDATED_NEW"
+    )
+    
+    res = ddb.get_item(
+    Key={
+        'm_key': {
+            'S': m_key,
+        }
+    },
+    TableName=table_name,)
+
+    lambda_code=res.get['Item']['lambda']['S']
+    https_code=res.get['Item']['https']['S']
+    sqs_code=res.get['Item']['sqs']['S']
+    order=res.get['Item']['order']['S']
+    # print(order,https,lambdaa,sqs)
+    if "012" == order:
+        valueb = sqs_code+https_code+lambda_code
+        valuea = valueb.replace("\n","")
+        # print(valuea,keya)
+        updata_db(m_key,valuea)
+    elif "021" == order:
+        valueb = sqs_code+lambda_code+https_code
+        valuea = valueb.replace("\n","")
+        updata_db(m_key,valuea)
+    elif "102" == order:
+        valueb = https_code+sqs_code+lambda_code
+        valuea = valueb.replace("\n","")
+        updata_db(m_key,valuea)
+    elif "120" == order:
+        valueb = lambda_code+sqs_code+https_code
+        valuea = valueb.replace("\n","")
+        updata_db(m_key,valuea)
+    elif "201" == order:
+        valueb = https_code+lambda_code+sqs_code
+        valuea = valueb.replace("\n","")
+        updata_db(m_key,valuea)
+    elif "210" == order:
+        valueb = lambda_code+https_code+sqs_code
+        valuea = valueb.replace("\n","")
+        updata_db(m_key,valuea)
+    return {
+        'statusCode': 200,
+        'body': json.dumps('Hello from Lambda!')
+    }
+    
+# 2、API-gateway lambda
+
+import json
+import boto3
+import time
+
+def lambda_handler(event, context):
+    time.sleep(2)
+    # print(event)
+    # print(event)
+    body = json.loads(event['body'])
+    # print(type(body))
+    val = body["Message"]
+    key = body['MessageAttributes']['mykey']['Value']
+
+    print("FORMHTTPS:" + key + ":" + val)
+    
+    ddb= boto3.client('dynamodb')
+    
+    table_name = 'found'
+
+    ddb.update_item(
+        TableName=table_name,
+        ExpressionAttributeValues={
+            ':y': {
+                'S': val,
+            }
+        },
+        Key={
+        'm_key': {
+            'S': key,
+        }
+        },
+        UpdateExpression='SET https = :y',
+        ReturnValues="UPDATED_NEW"
+    )
+    # TODO implement
+    return {
+        'statusCode': 200,
+        'body': json.dumps('Hello from Lambda!')
+    }
+
+# 3、lambda - lambda
+
+import json
+import boto3
+
+def lambda_handler(event, context):
+    # TODO implement
+    # print(event)
+
+
+    sec = event['Records'][0]['Sns']['MessageAttributes']
+    mes = event['Records'][0]['Sns']['Message']
+    m_key = sec['mykey']['Value']
+    order = sec['order']['Value']
+
+    a1 = order.replace(":", "")
+    a2 = a1.replace("SQS", '')
+    a3 = a2.replace("HTTPS","")
+    a4=a3.replace("LAMBDA","")
+    a5=a4.replace(" ","")
+    
+    print("ORDER:"+ m_key + ":" + a5)
+    print("FORMLAMBDA:" + m_key + ":" + mes)
+    # updata_db(m_key,a5)
+    
+    ddb= boto3.client('dynamodb')
+    
+    tableName = 'found'
+    item = {  'm_key': {'S': m_key},
+              'order': {'S': a5},
+              'lambda': {'S': mes}
+           }
+
+    ddb.put_item(TableName = tableName, Item = item)
+    
+    

+ 31 - 0
AWS-test/Lambda-exec-sqs.py

@@ -0,0 +1,31 @@
+import json
+import pymysql
+import sys
+import time
+import boto3
+
+def updata_db(m_key,m_value):
+    conn2 = pymysql.connect(
+        host='a.xdc.ink',
+        port=3306,
+        user='root',
+        passwd='xclouds123',
+        db='cmd',
+        charset='utf8mb4')
+
+    cs2 = conn2.cursor()
+    select_sql = f'INSERT INTO kv (mykey, myvalue) VALUES ("{m_key}", "{m_value}");'
+    cs2.execute(select_sql)
+    conn2.commit()
+    cs2.close()
+    conn2.close()
+
+def lambda_handler(event, context):
+    # TODO implement
+    sec = event['Records'][0]['messageAttributes']
+    m_key = sec['mykey']['stringValue']
+    m_value = sec['myvalue']['stringValue']
+    print(m_key,m_value)
+    updata_db(m_key,m_value)
+
+    

+ 144 - 0
AWS-test/Rek_lambda.py

@@ -0,0 +1,144 @@
+
+
+"""
+This is the starter code to detecting the faces/labels
+in our images of Kyle.
+
+It's mostly complete but we didn't know all the specifics
+to the API calls.
+
+If you look at the boto3 documentation you will be able to find
+all the answers!
+"""
+
+import boto3
+import json
+import os
+
+######
+# Getting our environment variables
+# Make sure to set these in your lambda function
+######
+# this is the name of the rekognition collection you've created
+rekognition_collection_id = os.environ['collection']
+# output on the dashboard
+sns_topic_arn = os.environ['sns_arn']
+# this is your "Team ID" you see at the top of the player 
+# dashboard like: 5a0e59338b894b57b48828b315a40afb
+# **IT IS NOT YOUR TEAM NAME**
+team_id = os.environ['team_id']
+
+
+# Rekognition allows you to specify a "tag" with your image.
+# so later when we detect a matching face, we read this tag
+# so we know the name or title of the person we've matched
+external_image_id = 'Kyle'
+
+# our boto3 rekognition client
+rekognition_client=boto3.client('rekognition')
+sns_client=boto3.client('sns')
+
+def facial_recognition(key, bucket):
+    response = rekognition_client.index_faces(
+        CollectionId=rekognition_collection_id,
+        Image={
+            'S3Object': {
+            'Bucket': bucket,
+            'Name': key
+        }
+        }
+    )
+    print "Index Faces response:\n %s" % response
+    # see if Rekognition detected any faces in this image
+    if not response['FaceRecords']:
+        # no faces detected, so we send back a false
+        return False
+
+    # we found faces, so let's see if they match our CEO
+    # iterating through the faces found in the submitted image
+    for face in response['FaceRecords']:
+        face_id = face['Face']['FaceId']
+        print "Face ID: %s" % face_id
+        # send the detected face to Rekognition to see if it matches
+        # anything in our collection
+        response = rekognition_client.search_faces(
+            CollectionId=rekognition_collection_id,
+            FaceId=face_id
+        )
+        print "Searching faces response:\n %s" % response
+        # checking if there were any matches
+        if not response['FaceMatches']:
+            # not our CEO
+            return False
+
+        # we recognized a face, let's see if it matches our CEO
+        for match in response['FaceMatches']:
+            if "ExternalImageId" in match['Face'] and match['Face']["ExternalImageId"] == external_image_id:
+                # we have a picture of our CEO
+                print "We've found our CEO!! Huzzah!"
+                return True
+
+        # At this point, we have other faces in our collection that 
+        # match this face, but it didn't match our CEO
+        print "not kyle :("
+        return False
+
+def get_labels(key, bucket):
+    response = rekognition_client.detect_labels(
+        Image={
+            'S3Object': {
+            'Bucket': bucket,
+            'Name': key
+        }
+        },
+        MinConfidence=50
+    )
+    raw_labels = response['Labels']
+    top_five=[]
+    for x in range(0,5):
+        top_five.append(raw_labels[x]['Name'])
+
+    return top_five
+
+def send_sns(message):
+    """
+    We'll use SNS to send our response back to the master account
+    with our labels
+    """
+    print message
+    response = sns_client.publish(
+        TopicArn=sns_topic_arn,
+        Message=json.dumps(message)
+    )
+
+    return
+
+def lambda_handler(event, context):
+    """
+    Main Lambda handler
+    """
+    print json.dumps(event)
+    # our incoming event is the S3 put event notification
+    s3_message = event
+    # get the object key and bucket name
+    key = s3_message['Records'][0]['s3']['object']['key']
+    bucket = s3_message['Records'][0]['s3']['bucket']['name']
+
+    # first we need to see if our CEO is in this picture
+    proceed = facial_recognition(key, bucket)
+
+    return_message={
+        "key":key,
+        "team_id":team_id
+    }
+
+    # now we move on to detecting what's in the image
+    if proceed:
+        labels = get_labels(key, bucket)
+        return_message['labels']=labels
+        return_message['kyle_present']=True
+    else:
+        # we need to signal back that our CEO wasn't in the picture
+        return_message['kyle_present']=False
+    
+    send_sns(return_message)

+ 273 - 0
AWS-test/api+ Dy_updata.py

@@ -0,0 +1,273 @@
+import json
+import boto3
+import time
+
+def lambda_handler(event, context):
+    print(event)
+    msg = json.loads(event['body'])
+    secret = msg['secret_code']
+    print(secret)
+    
+    client = boto3.client('dynamodb')
+    
+    table_name = "xdctb"
+    # timedata = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
+    response = client.update_item(
+        TableName=table_name,
+        # ExpressionAttributeNames={
+        #     'skip': secret,
+        # },
+        ExpressionAttributeValues={
+            ':y': {
+                'S': secret,
+            }
+        },
+        Key={
+        'dtime': {
+            'S': '20200605',
+        }
+        },
+        UpdateExpression='SET skip = :y',
+        ReturnValues="UPDATED_NEW"
+    )
+    
+    return {
+    "statusCode": 200,
+    "isBase64Encoded": False,
+    "headers": {
+        "Content-Type": "application/json; charset=utf-8"
+        },
+    "body": "OK ! "
+    }
+
+
+#=======================第一版本=========================#
+
+import json
+import boto3
+import time
+
+def lambda_handler(event, context):
+    print(event)
+    msg = json.loads(event['body'])
+    secret = msg['secret_code']
+    print(secret)
+    
+    client = boto3.client('dynamodb')
+    
+    table_name = "xdctb"
+    # timedata = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
+    response = client.update_item(
+        TableName=table_name,
+        Key={
+        'dtime': {
+            'S': '20200605',
+        },
+        'skip': {
+            'S': secret,
+        },
+        })
+        
+    # print(timedata)
+    return {
+    "statusCode": 200,
+    "isBase64Encoded": False,
+    "headers": {
+        "Content-Type": "application/json; charset=utf-8"
+        },
+    "body": "OK ! "
+    } 
+
+
+# ========================? v2 ========================
+
+import boto3
+import json
+import time
+import base64
+from botocore.exceptions import ClientError
+
+print('Loading function')
+dynamodb = boto3.client('dynamodb')
+
+
+def respond(err, res=None):
+    return {
+        'statusCode': '400' if err else '200',
+        'body': err.message if err else json.dumps(res),
+        'headers': {
+            'Content-Type': 'application/json',
+        },
+    }
+
+
+def lambda_handler(event, context):
+    response = {}
+    response["headers"] = event["headers"]
+    #dynamodb.put_item(TableName='K12D', Item= {'id':{"S": json.loads(event['body'])["secret_code"]},'key':{"S": str(round(time.time()))}})
+    #ret_data=dynamodb.scan(TableName='K12D')
+
+    secret_name = "test"
+    region_name = "cn-northwest-1"
+
+    # Create a Secrets Manager client
+    session = boto3.session.Session()
+    client = session.client(
+        service_name='secretsmanager',
+        region_name=region_name
+    )
+
+    # In this sample we only handle the specific exceptions for the 'GetSecretValue' API.
+    # See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
+    # We rethrow the exception by default.
+
+    try:
+        get_secret_value_response = client.get_secret_value(
+            SecretId=secret_name
+        )
+    except ClientError as e:
+        if e.response['Error']['Code'] == 'DecryptionFailureException':
+            # Secrets Manager can't decrypt the protected secret text using the provided KMS key.
+            # Deal with the exception here, and/or rethrow at your discretion.
+            raise e
+        elif e.response['Error']['Code'] == 'InternalServiceErrorException':
+            # An error occurred on the server side.
+            # Deal with the exception here, and/or rethrow at your discretion.
+            raise e
+        elif e.response['Error']['Code'] == 'InvalidParameterException':
+            # You provided an invalid value for a parameter.
+            # Deal with the exception here, and/or rethrow at your discretion.
+            raise e
+        elif e.response['Error']['Code'] == 'InvalidRequestException':
+            # You provided a parameter value that is not valid for the current state of the resource.
+            # Deal with the exception here, and/or rethrow at your discretion.
+            raise e
+        elif e.response['Error']['Code'] == 'ResourceNotFoundException':
+            # We can't find the resource that you asked for.
+            # Deal with the exception here, and/or rethrow at your discretion.
+            raise e
+    else:
+        # Decrypts secret using the associated KMS CMK.
+        # Depending on whether the secret is a string or binary, one of these fields will be populated.
+        if 'SecretString' in get_secret_value_response:
+            secret = get_secret_value_response['SecretString']
+        else:
+            decoded_binary_secret = base64.b64decode(get_secret_value_response['SecretBinary'])
+        
+        #updated_secret=get_secret_value_response.update({"key": "test223123123"})
+        try:
+            client.update_secret(SecretId=secret_name, SecretString=json.dumps(json.loads(event['body'])["secret_code"]))
+            return {
+                'statusCode': 200,
+                #'body': json.loads(event['body'])["secret_code"]
+                #'body': str(max(ret_data['Items'].key))
+                #'body': json.loads(get_secret_value_response['SecretString'])['key']
+                #'body': get_secret_value_response['SecretString']
+                'body': json.loads(event['body'])["secret_code"]
+            }
+        except:
+            return {
+                'statusCode': 200,
+                #'body': json.loads(event['body'])["secret_code"]
+                #'body': str(max(ret_data['Items'].key))
+                #'body': json.loads(get_secret_value_response['SecretString'])['key']
+                #'body': get_secret_value_response['SecretString']
+                'body': json.loads(get_secret_value_response['SecretString'])
+            }
+
+# ========================? v3 ========================
+
+import boto3
+import json
+import time
+import base64
+from botocore.exceptions import ClientError
+
+print('Loading function')
+dynamodb = boto3.client('dynamodb')
+
+
+def respond(err, res=None):
+    return {
+        'statusCode': '400' if err else '200',
+        'body': err.message if err else json.dumps(res),
+        'headers': {
+            'Content-Type': 'application/json',
+        },
+    }
+
+
+def lambda_handler(event, context):
+    response = {}
+    response["headers"] = event["headers"]
+    #dynamodb.put_item(TableName='K12D', Item= {'id':{"S": json.loads(event['body'])["secret_code"]},'key':{"S": str(round(time.time()))}})
+    #ret_data=dynamodb.scan(TableName='K12D')
+
+    secret_name = "test"
+    region_name = "cn-northwest-1"
+
+    # Create a Secrets Manager client
+    session = boto3.session.Session()
+    client = session.client(
+        service_name='secretsmanager',
+        region_name=region_name
+    )
+
+    # In this sample we only handle the specific exceptions for the 'GetSecretValue' API.
+    # See https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html
+    # We rethrow the exception by default.
+
+    try:
+        get_secret_value_response = client.get_secret_value(
+            SecretId=secret_name
+        )
+    except ClientError as e:
+        if e.response['Error']['Code'] == 'DecryptionFailureException':
+            # Secrets Manager can't decrypt the protected secret text using the provided KMS key.
+            # Deal with the exception here, and/or rethrow at your discretion.
+            raise e
+        elif e.response['Error']['Code'] == 'InternalServiceErrorException':
+            # An error occurred on the server side.
+            # Deal with the exception here, and/or rethrow at your discretion.
+            raise e
+        elif e.response['Error']['Code'] == 'InvalidParameterException':
+            # You provided an invalid value for a parameter.
+            # Deal with the exception here, and/or rethrow at your discretion.
+            raise e
+        elif e.response['Error']['Code'] == 'InvalidRequestException':
+            # You provided a parameter value that is not valid for the current state of the resource.
+            # Deal with the exception here, and/or rethrow at your discretion.
+            raise e
+        elif e.response['Error']['Code'] == 'ResourceNotFoundException':
+            # We can't find the resource that you asked for.
+            # Deal with the exception here, and/or rethrow at your discretion.
+            raise e
+    else:
+        # Decrypts secret using the associated KMS CMK.
+        # Depending on whether the secret is a string or binary, one of these fields will be populated.
+        if 'SecretString' in get_secret_value_response:
+            secret = get_secret_value_response['SecretString']
+        else:
+            decoded_binary_secret = base64.b64decode(get_secret_value_response['SecretBinary'])
+        
+        #updated_secret=get_secret_value_response.update({"key": "test223123123"})
+        try:
+            client.update_secret(SecretId=secret_name, SecretString=json.dumps(json.loads(event['body'])["secret_code"]))
+            return {
+                'statusCode': 200,
+                #'body': json.loads(event['body'])["secret_code"]
+                #'body': str(max(ret_data['Items'].key))
+                #'body': json.loads(get_secret_value_response['SecretString'])['key']
+                #'body': get_secret_value_response['SecretString']
+                'body': json.loads(event['body'])["secret_code"]
+            }
+        except:
+            return {
+                'statusCode': 200,
+                #'body': json.loads(event['body'])["secret_code"]
+                #'body': str(max(ret_data['Items'].key))
+                #'body': json.loads(get_secret_value_response['SecretString'])['key']
+                #'body': get_secret_value_response['SecretString']
+                'body': json.loads(get_secret_value_response['SecretString'])
+            }
+

+ 140 - 0
AWS-test/api_dy_sh.py

@@ -0,0 +1,140 @@
+import json
+import subprocess
+
+file_a = '/root/sec.txt'
+file_b = '/root/conf.toml'
+
+with open(file_a,'r') as file_obj:
+    json_data = json.load(file_obj)
+    first_secret = json_data['Item']['skip']['S']
+    # print(secret)
+    file_obj.close()
+
+
+cmd_aws_get = "aws dynamodb get-item --table-name xdctb --key file:///root/data.json > /root/sec.txt"
+cmd_kill = "killall server_k12"
+# cmd_s3cp = "aws s3 cp /root/conf.toml  s3://serverapi & "
+cmd_run_server = "nohup /root/server_k12 /root/conf.toml & > /dev/null "
+
+subprocess.getstatusoutput(cmd_aws_get)
+
+with open(file_a,'r') as file_obj:
+    json_data = json.load(file_obj)
+    second_secret = json_data['Item']['skip']['S']
+    # print(secret)
+    file_obj.close()
+
+cmd_sed = "sed -i '3c secret_code = \"{:s}\"' conf.toml &".format(second_secret)
+if first_secret == second_secret:
+    print(first_secret, "-->11")
+else:
+    print(second_secret)
+    subprocess.getstatusoutput(cmd_kill)
+    subprocess.getstatusoutput(cmd_sed)
+    # subprocess.getstatusoutput(cmd_s3cp)
+    subprocess.getstatusoutput(cmd_run_server)
+
+# #!/bin/bash
+# while :
+# do
+# 	python3 /root/sh.py &
+# 	sleep 5
+# done
+
+# data.json -->> {"dtime": {"S": "20200605"}}
+# aws dynamodb get-item --table-name xdc-tb --key file://data.json > /root/sec.txt
+# grep -Po 'S[" :]+\K[^"]+' /root/sec.txt | tail -1
+
+
+#==================================================================
+
+# import json
+# import os
+# import subprocess
+
+# file_a = '/root/sec.txt'
+# file_b = '/root/conf.toml'
+
+# with open(file_a,'r') as file_obj:
+#     json_data = json.load(file_obj)
+#     first_secret = json_data['Item']['skip']['S']
+#     # print(secret)
+#     file_obj.close()
+
+
+# cmd_aws_get = "aws dynamodb get-item --table-name xdctb --key file:///root/data.json > /root/sec.txt"
+# cmd_kill = "killall server_k12"
+# cmd_s3cp = "aws s3 cp /root/conf.toml  s3://serverapi & "
+# cmd_run_server = "/root/server_k12 /root/conf.toml > /dev/null &"
+
+# subprocess.getstatusoutput(cmd_aws_get)
+
+# with open(file_a,'r') as file_obj:
+#     json_data = json.load(file_obj)
+#     second_secret = json_data['Item']['skip']['S']
+#     # print(secret)
+#     file_obj.close()
+
+# cmd_sed = "sed -i '3c secret_code = \"{:s}\"' conf.toml &".format(second_secret)
+# if first_secret == second_secret:
+#     print(first_secret, "-->11")
+# else:
+#     print(second_secret)
+#     subprocess.getstatusoutput(cmd_kill)
+#     subprocess.getstatusoutput(cmd_sed)
+#     subprocess.getstatusoutput(cmd_s3cp)
+#     subprocess.getstatusoutput(cmd_run_server)
+#     os._exit()
+
+
+
+
+
+
+
+
+# data.json -->> {"dtime": {"S": "20200605"}}
+# aws dynamodb get-item --table-name xdc-tb --key file://data.json > /root/sec.txt
+# grep -Po 'S[" :]+\K[^"]+' /root/sec.txt | tail -1
+
+#=============================================
+
+# import json
+# import subprocess
+
+# cmd_aws_get = "aws dynamodb get-item --table-name xdctb --key file:///root/data.json > /root/sec.txt"
+# cmd_kill = "killall server_k12"
+# subprocess.getstatusoutput(cmd_aws_get)
+# subprocess.getstatusoutput(cmd_kill)
+
+# file_a = '/root/sec.txt'
+# file_b = '/root/conf.toml'
+
+# with open(file_a,'r') as file_obj:
+#     json_data = json.load(file_obj)
+#     secret = json_data['Item']['skip']['S']
+#     # print(secret)
+#     file_obj.close()
+
+# # netstat = "ss -tnl |grep 7777"
+# cmd_sed = "sed -i '3c secret_code = \"{:s}\"' conf.toml".format(secret)
+# cmd_run_server = "/root/server_k12 /root/conf.toml &"
+
+# def cmd_run(cmd):
+#     stat, result = subprocess.getstatusoutput(cmd)
+#     if stat != 0:
+#         subprocess.getstatusoutput(cmd_sed)
+#         subprocess.getstatusoutput(cmd_run_server)
+
+# cmd_run("ss -tnl |grep 7777")
+# print(secret)
+
+# # data.json -->> {"dtime": {"S": "20200605"}}
+# # aws dynamodb get-item --table-name xdc-tb --key file://data.json > /root/sec.txt
+# # grep -Po 'S[" :]+\K[^"]+' /root/sec.txt | tail -1
+
+
+# wget -O /root/conf.toml https://serverapi.s3.cn-northwest-1.amazonaws.com.cn/conf.toml
+# killall server_k12
+# /root/server_k12 /root/conf.toml
+

+ 51 - 0
AWS-test/awslogs + lambda.py

@@ -0,0 +1,51 @@
+
+#======================= test =========================#
+
+import requests
+import json
+
+user_id=715
+game_id=141
+url = "http://onlyellow.cstor.cn:18888/launch_refund"  
+
+server_logs = "[Server] 2020/06/16 09:52:56 Refund ID: 22f6f61f-d573-4eff-963a-708983317057"
+sp_log = server_logs.split(' ', -1)
+refund_id = sp_log[5]
+# print(refund_id)
+data = json.dumps({"user_id":user_id, "game_id":game_id, "refund_id":refund_id})
+response = requests.post(url=url, data=data)
+print(response)
+
+
+data_a = {"user_id":user_id, "game_id":game_id, "refund_id":refund_id}
+print(type(data_a))
+
+
+#======================= comp =========================#
+
+
+import json
+import urllib.request
+import urllib.parse
+import base64
+import gzip
+# import requests
+
+def lambda_handler(event, context):
+    
+    user_id=715
+    game_id=141
+    url = "http://onlyellow.cstor.cn:18888/launch_refund"
+    
+    de_content = base64.b64decode(event['awslogs']['data'])
+    ret = json.loads(gzip.decompress(de_content).decode('utf8'))
+    log_msg = ret['logEvents'][0]['message']
+    tup_log = log_msg.split(' ', -1)
+    refund_id = tup_log[5]
+    # post
+    data = json.dumps({"user_id":user_id, "game_id":game_id, "refund_id":refund_id})
+    last_data=bytes(data,encoding='utf-8')
+    headers = {"Content-Type":'application/json'}
+    req = urllib.request.Request(url=url, headers=headers, data=last_data)
+    response = urllib.request.urlopen(req)
+    print(response.read().decode('utf-8'))

+ 229 - 0
AWS-test/cloudfront_sgs.py

@@ -0,0 +1,229 @@
+'''
+Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
+Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/
+or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
+'''
+
+import sys
+import boto3
+import json
+import urllib2
+
+# Name of the service, as seen in the ip-groups.json file, to extract information for
+SERVICE = "CLOUDFRONT"
+# Ports your application uses that need inbound permissions from the service for
+INGRESS_PORTS = [80]
+# Tags which identify the security groups you want to update
+SECURITY_GROUP_TAGS = {'Name': 'WebServerSG'}
+# Max number of rules to add to a security group
+MAX_RULES_PER_GROUP = 50
+
+def get_ranges_for_service(ranges, service):
+    """
+    Loop thru the IP ranges and return the matching services
+    """
+    service_ranges = list()
+    for prefix in ranges['prefixes']:
+        if prefix['service'] == service:
+            print 'Found ' + service + ' range: ' + prefix['ip_prefix']
+            service_ranges.append(prefix['ip_prefix'])
+
+    return service_ranges
+
+def update_security_groups(new_ranges):
+    """
+    Update matching security groups with a list of ranges
+    """
+    client = boto3.client('ec2')
+
+    groups = get_security_groups_for_update(client)
+    print 'Found ' + str(len(groups)) + ' SecurityGroups to update'
+
+    result = list()
+    updated = 0
+
+    for group in groups:
+        if update_security_group(client, group, new_ranges):
+            updated += 1
+            result.append('Updated ' + group['GroupId'])
+
+    result.append('Updated ' + str(updated) + ' of ' + str(len(groups)) + ' SecurityGroups')
+
+    return result
+
+def update_security_group(client, group, new_ranges):
+    """
+    Update security group with a list of ranges
+    """
+    added = 0
+    removed = 0
+
+    if 'IpPermissions' in group and len(group['IpPermissions']) > 0:
+        for permission in group['IpPermissions']:
+            if INGRESS_PORTS.count(permission['ToPort']) > 0:
+                old_prefixes = list()
+                to_revoke = list()
+                to_add = list()
+                for ip_range in permission['IpRanges']:
+                    cidr = ip_range['CidrIp']
+                    old_prefixes.append(cidr)
+                    if new_ranges.count(cidr) == 0:
+                        to_revoke.append(ip_range)
+                        print group['GroupId'] + ": Revoking " + cidr + ":" + str(permission['ToPort'])
+
+                for ip_range in new_ranges:
+                    if old_prefixes.count(ip_range) == 0:
+                        to_add.append({'CidrIp': ip_range})
+                        print group['GroupId'] + ": Adding " + ip_range + ":" + str(permission['ToPort'])
+
+                removed += revoke_permissions(client, group, permission, to_revoke)
+                added += add_permissions(client, group, permission, to_add)
+    else:
+        for port in INGRESS_PORTS:
+            to_add = list()
+            for ip_range in new_ranges:
+                to_add.append({'CidrIp': ip_range})
+                print group['GroupId'] + ": Adding " + ip_range + ":" + str(port)
+            permission = {'ToPort': port, 'FromPort': port, 'IpProtocol': 'tcp'}
+            added += add_permissions(client, group, permission, to_add)
+
+    print group['GroupId'] + ": Added " + str(added) + ", Revoked " + str(removed)
+    return added > 0 or removed > 0
+
+def revoke_permissions(client, group, permission, to_revoke):
+    """
+    Revoke a rule from a security group
+    """
+    if len(to_revoke) > 0:
+        revoke_params = {
+            'ToPort': permission['ToPort'],
+            'FromPort': permission['FromPort'],
+            'IpRanges': to_revoke,
+            'IpProtocol': permission['IpProtocol']
+        }
+
+        client.revoke_security_group_ingress(GroupId=group['GroupId'], IpPermissions=[revoke_params])
+
+    return len(to_revoke)
+
+
+def add_permissions(client, group, permission, to_add):
+    """
+    Add a rule to a security group
+    """
+    if len(to_add) > 0:
+        add_params = {
+            'ToPort': permission['ToPort'],
+            'FromPort': permission['FromPort'],
+            'IpRanges': to_add,
+            'IpProtocol': permission['IpProtocol']
+        }
+
+        client.authorize_security_group_ingress(GroupId=group['GroupId'], IpPermissions=[add_params])
+
+    return len(to_add)
+
+def get_security_groups_for_update(client):
+    """
+    Return a list of matching security groups
+    """
+    filters = []
+    for key, value in SECURITY_GROUP_TAGS.iteritems():
+        filters.extend(
+            [
+                {'Name': "tag-key", 'Values': [key]},
+                {'Name': "tag-value", 'Values': [value]}
+            ]
+        )
+
+    response = client.describe_security_groups(Filters=filters)
+
+    return response['SecurityGroups']
+
+def get_ip_groups_json(url):
+    """
+    Return the HTTP response from URL
+    """
+    print "Updating from " + url
+
+    response = urllib2.urlopen(url)
+    ip_json = response.read()
+
+    return ip_json
+
+def create_ranges_groups(ranges, vpc_id):
+    """
+    Create 1 or more groups to hold the ranges
+    """
+    client = boto3.client('ec2')
+    prefix = SERVICE + "-only-"
+    description = SERVICE + " only"
+    i = 1
+    remainder = list(ranges)
+    groups = []
+
+    while remainder:
+        head = remainder[:MAX_RULES_PER_GROUP]
+        remainder = remainder[MAX_RULES_PER_GROUP:]
+        group_name = prefix + str(i)
+
+        all_groups = client.describe_security_groups()
+        filter_groups = [ sg for sg in all_groups['SecurityGroups'] if sg['GroupName'] == group_name ]
+        if filter_groups:
+            print("Existing security group: %s" % group_name)
+            update_group = filter_groups[0]
+        else:
+            print("Creating security group: %s" % group_name)
+            update_group = client.create_security_group(
+                Description=description,
+                GroupName=group_name,
+                VpcId=vpc_id
+            )
+        groups.append(update_group['GroupId'])
+        if update_security_group(client, update_group, head):
+            print('Updated ' + update_group['GroupId'])
+        i += 1
+    return groups
+
+
+def main():
+    """
+    Retrieve AWS IP Address Ranges https://docs.aws.amazon.com/general/latest/gr/aws-ip-ranges.html
+    Update matching security groups with the SERVICE ranges
+    """
+    ip_ranges = json.loads(get_ip_groups_json('https://ip-ranges.amazonaws.com/ip-ranges.json'))
+
+    # extract the service ranges
+    cf_ranges = get_ranges_for_service(ip_ranges, SERVICE)
+
+    # Clean out the matching security groups
+    result = update_security_groups([])
+    print "\n".join(result)
+
+
+    try:
+        response = urllib2.urlopen("http://169.254.169.254/latest/meta-data/instance-id", timeout=5)
+        instance_id = response.read()
+    except:
+        print("Not running on an instance")
+        sys.exit(0)
+
+    client = boto3.client('ec2')
+    sgs = client.describe_instances(
+        InstanceIds = [ instance_id ]
+    )
+    vpc_id = sgs['Reservations'][0]['Instances'][0]["VpcId"]
+    current_sgs = [sg['GroupId'] for sg in sgs['Reservations'][0]['Instances'][0]["SecurityGroups"] ]
+
+    # create new groups that lock down to SERVICE
+    new_sgs = create_ranges_groups(cf_ranges, vpc_id)
+    union_sgs = list(set().union(current_sgs, new_sgs))
+    # update the instance security groups
+    print("Updating security group on: %s -> %s" % (instance_id, " ".join(union_sgs)))
+    client.modify_instance_attribute(
+        InstanceId=instance_id,
+        Groups=union_sgs
+    )
+
+if __name__ == "__main__":
+    main()

+ 169 - 0
AWS-test/cstor-foundcation.py

@@ -0,0 +1,169 @@
+
+# 1、 SQS——lambda
+import json
+import boto3
+import time
+import pymysql
+
+def updata_db(m_key,m_value):
+    conn2 = pymysql.connect(
+        host='a.xdc.ink',
+        port=3306,
+        user='root',
+        passwd='xclouds12',
+        db='cmd',
+        charset='utf8mb4')
+
+    cs2 = conn2.cursor()
+    select_sql = f'INSERT INTO kv (mykey, myvalue) VALUES ("{m_key}", "{m_value}");'
+    cs2.execute(select_sql)
+    conn2.commit()
+    cs2.close()
+    conn2.close()
+    
+def lambda_handler(event, context):
+    # print(event)
+    time.sleep(3)
+    body = event['Records'][0]['body']
+    m_key = event['Records'][0]['messageAttributes']['mykey']['stringValue']
+    # print("FORMSQS:" + m_key + ":" + body)
+    
+    ddb= boto3.client('dynamodb')
+    
+    table_name = 'found'
+ 
+    ddb.update_item(
+        TableName=table_name,
+
+        ExpressionAttributeValues={
+            ':y': {
+                'S': body,
+            }
+        },
+        Key={
+        'm_key': {
+            'S': m_key,
+        }
+        },
+        UpdateExpression='SET sqs = :y',
+        ReturnValues="UPDATED_NEW"
+    )
+    
+    res = ddb.get_item(
+    Key={
+        'm_key': {
+            'S': m_key,
+        }
+    },
+    TableName=table_name,)
+
+    lambda_code=res['Item']['lambda']['S']
+    https_code=res['Item']['https']['S']
+    sqs_code=res['Item']['sqs']['S']
+    order=res['Item']['order']['S']
+    # print(order,https,lambdaa,sqs)
+    if "012" == order:
+        valueb = sqs_code+https_code+lambda_code
+        valuea = valueb.replace("\n","")
+        # print(valuea,keya)
+        updata_db(m_key,valuea)
+    elif "021" == order:
+        valueb = sqs_code+lambda_code+https_code
+        valuea = valueb.replace("\n","")
+        updata_db(m_key,valuea)
+    elif "102" == order:
+        valueb = https_code+sqs_code+lambda_code
+        valuea = valueb.replace("\n","")
+        updata_db(m_key,valuea)
+    elif "120" == order:
+        valueb = https_code+lambda_code+sqs_code
+        valuea = valueb.replace("\n","")
+        updata_db(m_key,valuea)
+    elif "201" == order:
+        valueb = lambda_code+sqs_code+https_code
+        valuea = valueb.replace("\n","")
+        updata_db(m_key,valuea)
+    elif "210" == order:
+        valueb = lambda_code+https_code+sqs_code
+        valuea = valueb.replace("\n","")
+        updata_db(m_key,valuea)
+    return {
+        'statusCode': 200,
+        'body': json.dumps('Hello from Lambda!')
+    }
+    
+# 2、API-gateway lambda
+
+import json
+import boto3
+import time
+
+def lambda_handler(event, context):
+    time.sleep(2)
+    # print(event)
+    # print(event)
+    body = json.loads(event['body'])
+    # print(type(body))
+    val = body["Message"]
+    key = body['MessageAttributes']['mykey']['Value']
+
+    print("FORMHTTPS:" + key + ":" + val)
+    
+    ddb= boto3.client('dynamodb')
+    
+    table_name = 'found'
+
+    ddb.update_item(
+        TableName=table_name,
+        ExpressionAttributeValues={
+            ':y': {
+                'S': val,
+            }
+        },
+        Key={
+        'm_key': {
+            'S': key,
+        }
+        },
+        UpdateExpression='SET https = :y',
+        ReturnValues="UPDATED_NEW"
+    )
+    # TODO implement
+    return {
+        'statusCode': 200,
+        'body': json.dumps('Hello from Lambda!')
+    }
+
+# 3、lambda - lambda
+
+import json
+import boto3
+
+def lambda_handler(event, context):
+    # TODO implement
+    # print(event)
+
+    sec = event['Records'][0]['Sns']['MessageAttributes']
+    mes = event['Records'][0]['Sns']['Message']
+    m_key = sec['mykey']['Value']
+    order = sec['order']['Value']
+
+    a1 = order.replace(":", "")
+    a2 = a1.replace("SQS", '')
+    a3 = a2.replace("HTTPS","")
+    a4=a3.replace("LAMBDA","")
+    a5=a4.replace(" ","")
+    
+    print("ORDER:"+ m_key + ":" + a5)
+    print("FORMLAMBDA:" + m_key + ":" + mes)
+    # updata_db(m_key,a5)
+    
+    ddb= boto3.client('dynamodb')
+    
+    tableName = 'found'
+    item = {  'm_key': {'S': m_key},
+              'order': {'S': a5},
+              'lambda': {'S': mes}
+           }
+    ddb.put_item(TableName = tableName, Item = item)
+    

+ 12 - 0
AWS-test/flask-post.py

@@ -0,0 +1,12 @@
+from flask import Flask,request
+import json
+app = Flask(__name__)
+
+@app.route("/a",methods=['GET', 'POST'])
+def hehe():
+    aaa=request.args.get('aaa')
+    return {'aa':aaa}
+
+if __name__ == '__main__':
+    app.run(debug=True)
+

+ 31 - 0
AWS-test/game.py

@@ -0,0 +1,31 @@
+import base64,hmac,hashlib,json
+from flask import Flask,request,logging
+app = Flask(__name__)
+
+secret_key='NotASecret'
+def sha256hex(data):
+    sha256 = hashlib.sha256()
+    sha256.update(data)
+    res = sha256.digest()
+    return res
+def gd_loadgen_compute(msg):
+    try:
+        smsg=base64.b64decode(msg)
+    except Exception:
+        smsg=''.encode()
+    for i in range(5):
+        smsg = sha256hex(smsg)
+        temp = bytearray(smsg)
+        smsg = bytes(temp[:31])
+    return base64.b64encode(smsg)
+def hmac_compute(msg):
+    return base64.b64encode(hmac.new(secret_key.encode(), msg.encode(), digestmod="SHA256").digest())
+@app.route('/calc',methods = ['POST', 'GET'])
+def calc_page():
+    return gd_loadgen_compute(request.args.get('input')),'{text/plain; charset=utf-8}'
+@app.route('/',methods = ['POST', 'GET'])
+def main_page():
+    return "TODO: Create a nice looking homepage."
+
+if __name__ == '__main__':
+   app.run(host="0.0.0.0",port=80)

+ 13 - 0
AWS-test/import requests.py

@@ -0,0 +1,13 @@
+import requests
+
+
+url = "https://1g5ekg3vs7.execute-api.us-west-2.amazonaws.com/Prod//event/360019ad-b248-4039-a346-17325969d919/participant"
+
+auth = "eyJraWQiOiJra2J2VUxWb2VZRXVkNnUwK0pEaU94VW9Ha3B3RTZCUU5Ob0VoQlJVN3FBPSIsImFsZyI6IlJTMjU2In0.eyJzdWIiOiIzMmI1ZWE5Yy1hNWQxLTRmNzEtOTExMS02NDczN2E2Y2NmN2EiLCJhdWQiOiI3NzB1MGNncTdhNTJiZ3EwdnZvazgzZDB1cSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJldmVudF9pZCI6ImRhNmU2ZDRmLTY5YTQtNDJjMy1iNmI3LWMxNzE1OTk4MjUwNCIsInRva2VuX3VzZSI6ImlkIiwiYXV0aF90aW1lIjoxNjAwOTExMzU3LCJpc3MiOiJodHRwczpcL1wvY29nbml0by1pZHAudXMtd2VzdC0yLmFtYXpvbmF3cy5jb21cL3VzLXdlc3QtMl9FVVE2UDhCczAiLCJuaWNrbmFtZSI6ImV2YWxmdW4iLCJjb2duaXRvOnVzZXJuYW1lIjoiMzJiNWVhOWMtYTVkMS00ZjcxLTkxMTEtNjQ3MzdhNmNjZjdhIiwiZXhwIjoxNjAwOTE4NTYwLCJpYXQiOjE2MDA5MTQ5NjAsImVtYWlsIjoiMTgxMDAzNzAwMTA0QHN0LnNkanUuZWR1LmNuIn0.Y-y75td1cJpv3SSj4bZ_QueW0gO0JFs5F_NBcahcUcmsRhPKk782Vjm-W1heXs729ju1BZTg-tzsg2Di4R8dbVT-RsToRFeLk-Ii-7nMjpZYU1s1YF1cJYwh5RYOU-378EktFgRnx4inhpKGKfn8SbMNcR6cYVUNwqjVq2EpDdX5J-ZucpoYPUgAk7Xpn0PZ5nhLSYBQFPr2uWjU9NpxBqvhStbxGRcHnXwvdnc-4JbwqX0kTrnBor3c5h_pIDK296SFStblcfYF-z9Ntb7vVamoCiUUgZoT_PjhgIR3lg4l6_LmN2iywnUAhhj_BABT-Im9QBUcKrBeLylYGaYAZA"
+data_headers = {
+        'Content-Type': 'application/json',
+        'Authorization': 'Bearer '+ auth
+    }
+
+data = requests.get(url, headers=data_headers)
+print(data.text)

+ 381 - 0
AWS-test/jam-sagamaker.py

@@ -0,0 +1,381 @@
+
+#import the required packages
+import pandas as pd
+import warnings
+warnings.filterwarnings("ignore")
+import seaborn.apionly as sns
+import sklearn
+from sklearn.model_selection import train_test_split
+import numpy as np
+from sklearn.ensemble import RandomForestClassifier
+from scipy.stats import randint as sp_randint
+%matplotlib inline
+import pickle
+
+#load the 'Iris' dataset, display simple stats about data size, and then print sample data
+df = pd.DataFrame(sns.load_dataset('iris'))
+print 'shape of the data frame'+str(df.shape)
+print 'We have an even spread of iris flower types'
+print df.groupby(['species']).size()
+print'Display ten random rows from the iris dataset'
+df.(samplen=10)
+
+
+"""
+一一一一一一一一一一一一一一一一一一一一一
+shape of the data frame(150, 5)
+We have an even spread of iris flower types
+species
+setosa        50
+versicolor    50
+virginica     50
+dtype: int64
+Display ten random rows from the iris dataset
+sepal_length	sepal_width	petal_length	petal_width	species
+143	6.8	3.2	5.9	2.3	virginica
+58	6.6	2.9	4.6	1.3	versicolor
+148	6.2	3.4	5.4	2.3	virginica
+91	6.1	3.0	4.6	1.4	versicolor
+97	6.2	2.9	4.3	1.3	versicolor
+74	6.4	2.9	4.3	1.3	versicolor
+112	6.8	3.0	5.5	2.1	virginica
+72	6.3	2.5	4.9	1.5	versicolor
+104	6.5	3.0	5.8	2.2	virginica
+114	5.8	2.8	5.1	2.4	virginica
+"""
+
+
+
+#let's group setosa and virginica together for the sake of this machine learning exercise
+df['y']= np.where(df['species']=='versicolor',1,0)
+print df.groupby(['y']).size()
+print 'we now have 50 versicolors and 100 non-versicolors'
+
+X=df.drop('species',1).drop('y',1)
+y=df['y']
+df.sample(n=10)
+
+""""
+二二二二二二二二二二二二二二二二二二二二二二
+y
+0    100
+1     50
+dtype: int64
+we now have 50 versicolors and 100 non-versicolors
+sepal_length	sepal_width	petal_length	petal_width	species	y
+7	5.0	3.4	1.5	0.2	setosa	0
+137	6.4	3.1	5.5	1.8	virginica	0
+116	6.5	3.0	5.5	1.8	virginica	0
+102	7.1	3.0	5.9	2.1	virginica	0
+122	7.7	2.8	6.7	2.0	virginica	0
+98	5.1	2.5	3.0	1.1	versicolor	1
+13	4.3	3.0	1.1	0.1	setosa	0
+14	5.8	4.0	1.2	0.2	setosa	0
+53	5.5	2.3	4.0	1.3	versicolor	1
+41	4.5	2.3	1.3	0.3	setosa	0
+""""
+
+
+
+#Initialize the random forest machine learning algorithm object
+RANDOM_STATE=0
+forest = RandomForestClassifier(n_estimators = 500, random_state=RANDOM_STATE, oob_score="True")
+
+#Train the random forest model on the data
+forest_model = forest.fit(X,y)
+
+#use the forest model to make a prediction on a new row of data
+#define a new array with the order of 'sepal_length', 'sepal_width', 'petal_length', and 'petal_width'
+n=[[[6.1,2.9,4.7,1.4]],
+[[7.2,3.2,6.0,1.8]],
+[[6.5,3.0,5.8,2.2]],
+[[7.2,3.6,6.1,2.5]],
+[[6.3,3.4,5.6,2.4]],
+[[6.3,3.3,6.0,2.5]],
+[[5.8,2.6,4.0,1.2]],
+[[6.4,3.1,5.5,1.8]],
+[[5.6,3.0,4.5,1.5]],
+[[5.0,2.3,3.3,1.0]],
+[[5.9,3.2,4.8,1.8]],
+[[6.6,2.9,4.6,1.3]],
+[[6.2,2.9,4.3,1.3]],
+[[5.0,3.6,1.4,0.2]],
+[[5.1,3.8,1.9,0.4]],
+[[7.2,3.0,5.8,1.6]],
+[[5.5,3.5,1.3,0.2]],
+[[6.7,3.1,4.7,1.5]],
+[[5.5,2.4,3.7,1.0]],
+[[4.5,2.3,1.3,0.3]],
+[[5.0,3.2,1.2,0.2]],
+[[4.8,3.0,1.4,0.1]],
+[[5.4,3.9,1.3,0.4]],
+[[6.0,2.2,5.0,1.5]],
+[[6.9,3.2,5.7,2.3]],
+[[4.7,3.2,1.6,0.2]],
+[[5.7,3.0,4.2,1.2]],
+[[6.9,3.1,5.4,2.1]],
+[[5.4,3.0,4.5,1.5]],
+[[6.1,3.0,4.9,1.8]],
+[[5.7,2.6,3.5,1.0]],
+[[5.7,2.8,4.1,1.3]],
+[[5.8,2.7,3.9,1.2]],
+[[6.3,2.7,4.9,1.8]],
+[[4.8,3.1,1.6,0.2]],
+[[4.3,3.0,1.1,0.1]],
+[[5.0,3.4,1.6,0.4]],
+[[4.4,3.0,1.3,0.2]],
+[[6.3,2.5,5.0,1.9]],
+[[5.8,2.8,5.1,2.4]],
+[[5.0,3.3,1.4,0.2]],
+[[5.9,3.0,5.1,1.8]],
+[[5.8,2.7,5.1,1.9]],
+[[4.7,3.2,1.3,0.2]],
+[[4.4,2.9,1.4,0.2]],
+[[6.0,2.2,4.0,1.0]],
+[[6.0,2.7,5.1,1.6]],
+[[7.1,3.0,5.9,2.1]],
+[[6.2,2.8,4.8,1.8]],
+[[6.7,2.5,5.8,1.8]]]
+#print new_flower
+v  = 0
+nv = 0
+for new_flower in n :
+    
+    prediction=forest_model.predict(new_flower)
+    print "a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor"
+    print prediction
+    
+    #This is the prediction confidence for the forest_model on that row of data being a versicolor iris.
+    prediction_proba=forest_model.predict_proba(new_flower)
+    print 'the confidence of the prediction'
+    print prediction_proba[0,1]
+    if prediction == 0 && prediction_proba[0,1] > 0.7:
+        nv = nv + 1
+    else :
+        v = v + 1
+print("v, nv ", v, nv)
+#save (pickle) your model to disk and then to s3
+local_path = "/home/ubuntu" # temp local path to export your model
+existing_bucket = "suika-un-labeled" # Bucket has prebuilt Model and Un-Labeled Data
+bucket_name = "suika-string-model" # s3 bucket name string to save your model
+filename = 'finalized_model.sav'
+pickle.dump(forest, open(filename, 'wb'))
+
+#you should now see your finalized_model.sav object in the file path
+#the ls command prints the contents of this notebook's folder
+print "list of the objects in this jupyter notebook's folder"
+!ls
+ 
+# Upload the saved model to S3
+import boto3
+s3 = boto3.resource('s3')
+s3.Bucket(bucket_name).put_object(Key='finalized_model.sav', Body=open('finalized_model.sav'))
+
+"""
+三三三三三三三三三三三三三三三三三三三三三三
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[1]
+the confidence of the prediction
+0.998
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.022
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.0
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.002
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.004
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.006
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[1]
+the confidence of the prediction
+0.998
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.002
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[1]
+the confidence of the prediction
+0.998
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[1]
+the confidence of the prediction
+0.994
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[1]
+the confidence of the prediction
+0.69
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[1]
+the confidence of the prediction
+1.0
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[1]
+the confidence of the prediction
+0.998
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.0
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.0
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.156
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.006
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[1]
+the confidence of the prediction
+0.998
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[1]
+the confidence of the prediction
+1.0
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.038
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.0
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.0
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.0
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.298
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.002
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.0
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[1]
+the confidence of the prediction
+0.998
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.002
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[1]
+the confidence of the prediction
+0.968
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.026
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[1]
+the confidence of the prediction
+1.0
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[1]
+the confidence of the prediction
+1.0
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[1]
+the confidence of the prediction
+1.0
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.02
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.0
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.0
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.0
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.0
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.012
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.0
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.0
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.058
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.008
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.0
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.026
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[1]
+the confidence of the prediction
+0.988
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[1]
+the confidence of the prediction
+0.726
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.0
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.074
+a prediction of '1' is for verisicolor. '0' is for prediction of non-versicolor
+[0]
+the confidence of the prediction
+0.01
+('v, nv ', 16, 34)
+list of the objects in this jupyter notebook's folder
+finalized_model.sav  iris.ipynb  lost+found
+s3.Object(bucket_name='suika-string-model', key='finalized_model.sav')
+
+"""

+ 69 - 0
AWS-test/lambda_api_性能测试.py

@@ -0,0 +1,69 @@
+import json
+import boto3
+import time
+
+def lambda_handler(event, context):
+    print(event)
+    ip = f"IP {event['headers']['X-Forwarded-For']}"
+    print(ip)
+    mode = None
+    array = None
+    array_sum = None
+    if event['httpMethod'] == 'GET':
+        mode = 'GET'
+        if event['multiValueQueryStringParameters'] and event['multiValueQueryStringParameters']['args']:
+            print(event['multiValueQueryStringParameters']['args'])
+            print(type(event['multiValueQueryStringParameters']['args']))
+            if '[' not in event['multiValueQueryStringParameters']['args'][0]:
+                print('list')
+                array = [int(i) for i in event['multiValueQueryStringParameters']['args']]
+                array_sum = sum(array)
+            else:
+                data = event['multiValueQueryStringParameters']['args'][0].replace('[', '').replace(']', '').replace(',', '')
+                print(data)
+                array = [int(i) for i in data.split()]
+                array_sum = sum(array)
+    elif event['httpMethod'] == 'POST':
+        mode = 'POST'
+        data = event['body'].replace('args=', '').split('&')
+        array = [int(i) for i in data]
+        array_sum = sum(array)
+    if array_sum:
+        result = {
+            'IP': ip,
+            'Method': mode,
+            'array': array,
+            'array_sum': array_sum,
+        }
+        client = boto3.client('dynamodb')
+        try:
+            response = client.put_item(
+                Item={
+                    'array': {
+                        'S': str(array),
+                    },
+                    'result': {
+                        'S': str(array_sum),
+                    },
+                    'datetime': {
+                        'S': time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
+                    }
+                },
+                TableName='add',
+            )
+        except:
+            print('not successful')
+        else:
+            print(response)
+    else:
+        result= {
+            "IP": ip,
+            "Method": mode,
+            "message": "Hello, Box"
+        }
+    print(result)
+    # TODO implement
+    return {
+        'statusCode': 200,
+        'body': json.dumps(result)
+    }

+ 52 - 0
AWS-test/lambda_http.py

@@ -0,0 +1,52 @@
+def lambda_handler(event, context):
+    response = {
+    "statusCode": 200,
+    "statusDescription": "200 OK",
+    "isBase64Encoded": False,
+    "headers": {
+    "Content-Type": "text/html; charset=utf-8"
+    }
+    }
+    response['body'] = """<html>
+    <head>
+    <title>Hello World!</title>
+    <style>
+    html, body {
+    margin: 0; padding: 0;
+    font-family: arial; font-weight: 700; font-size: 3em;
+    text-align: center;
+    }
+    </style>
+    </head>
+    <body>
+    <p>Hello World!</p>
+    </body>
+    </html>"""
+    return response
+
+# ====================分割线====================
+
+import json
+
+def lambda_handler(event, context):
+
+  response = {
+    "statusCode": 200,
+    "headers": {
+      "Content-Type": "text/plain;"
+    },
+    "isBase64Encoded": False
+  }
+
+  if event['path'] == '/myip':
+    sourceip_list = event['headers']['x-forwarded-for'].split(',')
+    if sourceip_list:
+      sourceip = str(sourceip_list[0])
+      response['body']=sourceip
+    else:
+      response['body']='?.?.?.?'
+    return response
+
+  response['body'] = json.dumps(event, indent=2)
+  
+  return response

+ 0 - 0
AWS-test/password.txt


+ 237 - 0
AWS-test/phn-founation.py

@@ -0,0 +1,237 @@
+import json
+import pymysql
+
+def insert_data(mykey,myvalue):
+    # 打开数据库连接
+    db = pymysql.connect("myinstance.cfeisxz72aaf.rds.cn-northwest-1.amazonaws.com.cn", "cstor", "12345678", "mydb")
+    
+    # 使用cursor()方法获取操作游标
+    cursor = db.cursor()
+    
+    # SQL 插入语句
+    sql = "INSERT INTO kv(mykey, myvalue) VALUES ('%s', '%s')" % (mykey, myvalue)
+    try:
+        # 执行sql语句
+        cursor.execute(sql)
+        # 执行sql语句
+        db.commit()
+    except:
+        # 发生错误时回滚
+        db.rollback()
+    
+    # 关闭数据库连接
+    db.close()
+
+
+def handle_order(s):
+    arr = s.split(" ")
+    
+    dict = {}
+    for i in arr:
+        temp = i.split(":")
+        if temp[1] == "0":
+            dict["0"] = temp[0]
+        elif temp[1] == "1":
+            dict["1"] = temp[0]
+        elif temp[1] == "2":
+            dict["2"] = temp[0]
+    
+    #根据key 排序
+    a = sorted(dict.items(),key= lambda  d :d[0])
+    return a
+
+def lambda_handler(event, context):
+    # TODO implement
+    
+    for rec in event["Records"]:
+        # TODO: write code...
+        if rec["eventName"] != "MODIFY":
+            continue
+        new_image = rec["dynamodb"]["NewImage"]
+        #获取 key value
+        sqs = new_image.get("SQS")
+        https = new_image.get("HTTPS")
+        lmd = new_image.get("LAMBDA")
+        order = new_image.get("order")
+        mykey = new_image.get("mykey").get("S")
+        #不是最后一次更新
+        if sqs==None or https==None or lmd==None or order==None:
+            continue
+        #更新一下值,上面的值不全的话,可能会是None,就不能直接get
+        sqs = sqs.get("S")
+        https = https.get("S")
+        lmd = lmd.get("S")
+        order = order.get("S")
+        
+        #处理order
+        arr = handle_order(order)
+        # arr = [('0', 'HTTPS'), ('1', 'SQS'), ('2', 'LAMBDA')]
+        #拼接字符串
+        myvalue = ""
+        for item in arr:
+            # TODO: write code...
+            if item[1]=="SQS":
+                myvalue += sqs
+            elif item[1] == "HTTPS":
+                myvalue += https
+            elif item[1] == "LAMBDA":
+                myvalue += lmd
+                
+        print(mykey,myvalue)
+        
+        #插入数据库
+        insert_data(mykey,myvalue)
+    
+    
+    return {
+        'statusCode': 200,
+        'body': json.dumps('Hello from Lambda!')
+    }
+
+
+# 2、sqs
+
+import json
+import boto3
+
+table_name = "mydynamodb"
+zujian = "SQS"
+
+def insert_data(mykey,order,msg):
+    
+    client = boto3.client('dynamodb')
+    response = client.get_item(TableName=table_name,Key={"mykey":{"S":mykey}})
+    item = response.get("Item")
+    print(item)
+    
+    response = client.update_item(
+            TableName=table_name,
+            Key={"mykey":{"S":mykey}},
+            AttributeUpdates={
+                "order":{"Value":{"S":order}},
+                zujian:{"Value":{"S":msg}}
+            })
+
+
+def lambda_handler(event, context):
+    # TODO implement
+    
+    for rec in event["Records"]:
+        body = rec["body"]
+        body = json.loads(body)
+        
+        msg = body["Message"]
+        attr = body["MessageAttributes"]
+        
+        #获取 mykey   order  
+        mykey = attr["mykey"]["Value"]
+        order = attr["order"]["Value"]
+        print(msg)
+        print(mykey,order)
+        
+        #将 mykey    order msg 插入数据库
+        insert_data(mykey,order,msg)
+
+  
+    
+    return {
+        'statusCode': 200,
+        'body': json.dumps('Hello from Lambda!')
+    }
+
+# 3、 Lambda
+
+
+import json
+import boto3
+
+table_name = "mydynamodb"
+zujian = "LAMBDA"
+
+def insert_data(mykey,order,msg):
+    
+    client = boto3.client('dynamodb')
+    response = client.get_item(TableName=table_name,Key={"mykey":{"S":mykey}})
+    item = response.get("Item")
+    print(item)
+    
+    response = client.update_item(
+            TableName=table_name,
+            Key={"mykey":{"S":mykey}},
+            AttributeUpdates={
+                "order":{"Value":{"S":order}},
+                zujian:{"Value":{"S":msg}}
+            })
+
+
+def lambda_handler(event, context):
+    # TODO implement
+    
+    for rec in event["Records"]:
+        sns = rec["Sns"]
+        subject = sns["Subject"]
+        msg = sns["Message"]
+        attr = sns["MessageAttributes"]
+        
+        #获取 mykey   order  
+        mykey = attr["mykey"]["Value"]
+        order = attr["order"]["Value"]
+        print(msg)
+        print(mykey,order)
+        
+        #将 mykey  order msg 插入数据库
+        insert_data(mykey,order,msg)
+    
+    
+    return {
+        'statusCode': 200,
+        'body': json.dumps('Hello from Lambda!')
+    }
+
+
+# 4、 https
+
+import json
+import boto3
+
+table_name = "mydynamodb"
+zujian = "HTTPS"
+
+def insert_data(mykey,order,msg):
+    
+    client = boto3.client('dynamodb')
+    response = client.get_item(TableName=table_name,Key={"mykey":{"S":mykey}})
+    item = response.get("Item")
+    print(item)
+    
+    response = client.update_item(
+            TableName=table_name,
+            Key={"mykey":{"S":mykey}},
+            AttributeUpdates={
+                "order":{"Value":{"S":order}},
+                zujian:{"Value":{"S":msg}}
+            })
+
+
+def lambda_handler(event, context):
+    # TODO implement
+    
+    if event["httpMethod"] == "POST":
+        body = json.loads(event["body"])
+        msg = body["Message"]
+        attr = body["MessageAttributes"]
+        
+        #获取 mykey   order  
+        mykey = attr["mykey"]["Value"]
+        order = attr["order"]["Value"]
+        
+        print(msg)
+        print(mykey,order)
+        
+        #将 mykey order  msg  插入 dynamodb
+        insert_data(mykey,order,msg)
+        
+    return {
+        'statusCode': 200,
+        'body': json.dumps('Hello from Lambda!')
+    }

+ 73 - 0
AWS-test/pro-aws-ebs-snapshot.py

@@ -0,0 +1,73 @@
+import boto3
+import os,time
+from botocore.exceptions import ClientError
+from datetime import datetime, timedelta, timezone
+
+client = boto3.client('ec2')
+ec2 = boto3.resource('ec2')
+ddb = boto3.resource('dynamodb')
+
+# 'EBS-Snapshot-Lifecycle' is the table you store snapshot metadata, modify it to your own table name
+table = ddb.Table('EBS-Snapshot-Lifecycle')
+
+# set days to keep 快照保留周期
+DAYS_TO_RETAIN = 7
+
+def lambda_handler(event, context):
+
+    os.environ['TZ'] = 'Asia/Shanghai'
+    time.tzset()
+    i=time.strftime('%X %x %Z')
+    
+    # set volume id, get volume who has a tag-key is 'Snapshot'
+    describe_volumes=client.describe_volumes(
+        Filters=[
+            {
+                'Name': 'tag-key',
+                'Values': ['Snapshot',
+                ]
+                
+            }
+        ]
+    )
+    volume_id_list = []
+    for vol in describe_volumes['Volumes']:
+        volume_id_list.append(vol.get('VolumeId'))
+    
+    # set snapshot
+    for volume_id in volume_id_list:
+        volume = ec2.Volume(volume_id)
+    
+        for tags in volume.tags:
+            if(tags.get('Key') == 'Name'):
+                volume_name = tags.get('Value')
+        description = volume_name + ' volume snapshot is created at ' + i
+        
+        try:
+            response = client.create_snapshot(
+                Description=description,
+                VolumeId=volume_id)
+        except:
+            print('Create Snapshot occured error, Volume id is ' + volume_id)
+        else:
+            print('Snapshot is created succeed, Snapshot id is ' + response.get('SnapshotId'))
+        
+        # write into DynanoDB table
+        snapshot_id = response.get('SnapshotId')
+        start_time = response.get('StartTime')
+        ttl_time = int(start_time.timestamp()) + 86400 * DAYS_TO_RETAIN
+    
+        try:
+            table.put_item(
+                Item={
+                    'snapshot_id': snapshot_id,
+                    'create_time': start_time.astimezone(timezone(timedelta(hours=8))).strftime('%X %x %Z'),
+                    'description': description,
+                    'timestamp': int(start_time.timestamp()),
+                    'ttl': ttl_time,
+                }
+            )
+        except:
+            print('Write to DynanoDB Table occured error, snapshot id is ' + snapshot_id)
+        else:
+            print('Write to DynanoDB Table succeed, snapshot id is ' + snapshot_id)

+ 10 - 0
AWS-test/sec.txt

@@ -0,0 +1,10 @@
+{
+    "Item": {
+        "dtime": {
+            "S": "20200605"
+        },
+        "skip": {
+            "S": "123"
+        }
+    }
+}

+ 71 - 0
AWS-test/server破解.py

@@ -0,0 +1,71 @@
+import os
+import time
+import subprocess
+
+nu = 0
+nu2 = 0
+start = time.clock()
+f = open('./password.txt','r')
+# passwd1 = passwd[0:200000]
+#for i in passwd:
+    #f.write(i + '\n')
+while nu2<100:
+    nu2 += 1
+    passwd = f.readline()
+    for s in passwd:
+        while nu<100:
+            nu += 1
+            x = subprocess.getstatusoutput('/root/cstor_server/challenge/q2/server' + ' ' + s)
+            if "WRONG PASSWORD!" in x[1]:
+                pass
+            else:
+                print(x,s) 
+                #print(x[0])
+
+# f1=file('XXX.txt','r')
+# for line in f1.readlines()[N:]:
+
+    #if 'CORRECT PASSWORD' in x:
+    #    print(x)
+
+    """
+    outputss = os.popen(['/root/dd' + ' ' + s "&& grep WRONG PASSWORD"])
+    x = outputss.read()
+    if x == "WRONG PASSWORD!":
+        pass
+    x.close()
+    """
+
+    #os.system('/root/dd' + ' ' + s)
+    #subprocess.Popen('/root/dd' + ' ' + s, shell=True, cwd="/home")
+
+
+#print(passwd)
+    #         for four in numb:
+
+    #             print(first+second+thrid+four)
+f.close()   
+elapsed = (time.clock() - start)
+print("Time used:",elapsed)
+
+import os
+import time
+import subprocess
+
+nu = 0
+nu2 = 0
+start = time.clock()
+f = open('./passwd.txt','r')
+#f = file('passwd.txt','r')
+while True:
+    for s in f.readlines()[100:110]:
+            # print(s)
+            x = subprocess.getstatusoutput('/root/cstor_server/challenge/q2/server' + ' ' + s)
+            if "WRONG PASSWORD!" in x:
+                pass
+            else:
+                print(x,s)
+
+f.close()
+elapsed = (time.clock() - start)
+print("Time used:",elapsed)

+ 6 - 0
AWS-test/sh.py

@@ -0,0 +1,6 @@
+i = 1
+while i<160000:
+    b = int(i) + 3000
+    threading.Thread(target=runa,args=(i,b).start()
+    print(i,b)
+    i = int(i) + 3000

+ 68 - 0
AWS-test/waf_ip_update.py

@@ -0,0 +1,68 @@
+"""
+Update an AWS IP set with the the top 10 IP addresses from Apache logs
+"""
+import sys
+import re
+import boto3
+from collections import Counter
+from tabulate import tabulate
+
+def get_top_n_ip_addresses(num):
+    """
+    Parses apache logs to find the top n X-Forwarded-For ip addresses
+    """
+    all_ip_addresses = []
+
+    with open('/var/log/httpd/access_log') as content:
+        for line in content:
+            # the first "cell" surrounded with brackets is the X-Forwarded-For
+            regex = re.search(r'\((.*?)\)', line)
+            if regex:
+                # format is X-Forwarded-For: client, proxy1, proxy2
+                # we want the right most IP, the IP that hit cloudfront
+                forwarded_for = re.findall(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', regex.group(0))
+                if forwarded_for:
+                    all_ip_addresses.append(forwarded_for[-1])
+
+    return Counter(all_ip_addresses).most_common(num)
+
+def main():
+    """
+    Grab top 10 X-Forwarded-For ip addresses and send to a WAF ip list
+    """
+    top_ip_addresses = get_top_n_ip_addresses(10)
+
+    print
+    print "Top 10 IP Addresses"
+    print "==================="
+    print
+    print tabulate(top_ip_addresses, headers=["IP", "Count"])
+    print
+
+    updates_list = [{
+        'Action': 'INSERT',
+        'IPSetDescriptor': {
+            'Type': 'IPV4',
+            'Value': "%s/32" % ip[0]
+        }
+    } for ip in top_ip_addresses]
+
+    waf = boto3.client('waf')
+    waf_ip_sets = waf.list_ip_sets(
+        Limit=100
+    )['IPSets']
+
+    if len(waf_ip_sets) < 1:
+        sys.exit('WAF IP sets appear to be misconfigured.  Expecting 1 IP set.')
+
+    waf_ip_set_id = waf_ip_sets[0]['IPSetId']
+    print "Updating IP set: ", waf_ip_sets[0]['Name']
+
+    waf.update_ip_set(IPSetId=waf_ip_set_id,
+                      ChangeToken=waf.get_change_token()['ChangeToken'],
+                      Updates=updates_list)
+
+    print "Done!"
+
+if __name__ == "__main__":
+    main()

+ 232 - 0
AWS-test/zjw-foundation.py

@@ -0,0 +1,232 @@
+
+# 1、HTTPS
+
+import json
+import boto3
+
+def lambda_handler(event, context):
+    print (event)
+    dynamodb = boto3.resource('dynamodb')
+    table = dynamodb.Table('message')
+
+    body=json.loads(event['body'])
+    mykey = body['MessageAttributes']['mykey']['Value']
+    seq = body['MessageAttributes']['order']['Value']
+    https = body['Message']
+    
+    response = table.get_item(
+        Key={
+            'mykey': mykey
+        }
+    )
+    
+    item = {'mykey': {'S': mykey},
+            'seq': {'S': seq}, 
+            'https': {'S': https}
+    }
+    
+    if response:
+        table.update_item(
+            Key={
+                'mykey': mykey
+            },
+        UpdateExpression='SET https = :https',
+        ExpressionAttributeValues={
+            ':https': https
+            }
+        )
+        table.update_item(
+            Key={
+                'mykey': mykey
+            },
+        UpdateExpression='SET seq = :seq',
+        ExpressionAttributeValues={
+            ':seq': seq
+            }
+        )
+    else:
+        table.put_item(Item = item)
+
+    
+# 2、lambda
+
+import json
+import boto3
+
+def lambda_handler(event, context):
+    dynamodb = boto3.resource('dynamodb')
+    table = dynamodb.Table('message')
+
+    body=event['Records'][0]['Sns']
+    mykey = body['MessageAttributes']['mykey']['Value']
+    seq = body['MessageAttributes']['order']['Value']
+    lamb = body['Message']
+    
+    response = table.get_item(
+        Key={
+            'mykey': mykey
+        }
+    )
+    
+    item = {  'mykey': {'S': mykey},
+            'seq': {'S': seq}, 
+            'lamb': {'S': lamb}
+    }
+    
+    if response:
+        table.update_item(
+            Key={
+                'mykey': mykey
+            },
+        UpdateExpression='SET lamb = :lamb',
+        ExpressionAttributeValues={
+            ':lamb': lamb
+            }
+        )
+    else:
+        table.put_item(Item = item)
+
+    
+# 3、 SQS 
+
+import json
+import boto3
+
+def lambda_handler(event, context):
+    dynamodb = boto3.resource('dynamodb')
+    table = dynamodb.Table('message')
+    print (event)
+
+    body=json.loads(event['Records'][0]['body'])
+    mykey = body['MessageAttributes']['mykey']['Value']
+    seq = body['MessageAttributes']['order']['Value']
+    sqs = body['Message']
+    
+    response = table.get_item(
+        Key={
+            'mykey': mykey
+        }
+    )
+    
+    item = {  'mykey': {'S': mykey},
+            'seq': {'S': seq}, 
+            'sqs': {'S': sqs}
+    }
+    
+    if response:
+        table.update_item(
+            Key={
+                'mykey': mykey
+            },
+        UpdateExpression='SET sqs = :sqs',
+        ExpressionAttributeValues={
+            ':sqs': sqs
+            }
+        )
+    else:
+        table.put_item(Item = item)
+
+    
+    
+
+# 4、 pymysql
+
+import json
+import boto3
+import pymysql
+
+
+def lambda_handler(event, context):
+    dynamodb = boto3.resource('dynamodb')
+    table = dynamodb.Table('message')
+    print(event)
+    
+    mykey = event['Records'][0]['dynamodb']['Keys']['mykey']['S']
+    #order = event['Records'][0]['dynamodb']['NewImage']['order']['S']
+    #sqs = event['Records'][0]['dynamodb']['NewImage']['sqs']['S']
+    #https = event['Records'][0]['dynamodb']['NewImage']['https']['S']
+    #lamb = event['Records'][0]['dynamodb']['NewImage']['lambda']['S']
+
+    response = table.get_item(
+        Key={
+            'mykey': mykey
+        }
+    )
+    
+    if 'Item' in response:
+        item = response['Item']
+        
+        if 'sqs' in item and 'lamb' in item and 'https' in item and 'seq' in item:
+            seq = item['seq']
+            sqs = item['sqs']
+            lamb = item['lamb']
+            https = item['https']
+            
+        else:
+            return
+    else:
+        return
+    
+    message = ''
+    
+    seqs = seq.split()
+    print(seqs)
+    for iterator in seqs:
+        result = iterator.split(':')
+        #print('result:'+result)
+        if result[1] == '0':
+            if result[0] == 'SQS':
+                message = sqs
+            elif result[0] == 'HTTPS':
+                message = https
+            elif result[0] == 'LAMBDA':
+                message = lamb
+    
+    for iterator in seqs:
+        result = iterator.split(':')
+        if result[1] == '1':
+            if result[0] == 'SQS':
+                message += sqs
+            elif result[0] == 'HTTPS':
+                message += https
+            elif result[0] == 'LAMBDA':
+                message += lamb
+    
+            
+    for iterator in seqs:
+        result = iterator.split(':')
+        if result[1] == '2':
+            if result[0] == 'SQS':
+                message += sqs
+            elif result[0] == 'HTTPS':
+                message += https
+            elif result[0] == 'LAMBDA':
+                message += lamb
+                    
+    print (message)
+                    
+    
+    db = pymysql.connect("mydbinst.cf6cb5zflfqe.rds.cn-northwest-1.amazonaws.com.cn","admin","12345678","mydb" )
+
+    cursor = db.cursor()
+
+    sql = "insert into kv(mykey, myvalue) values( %s,  %s)"
+    val = (mykey, message)
+
+    #try:
+    cursor.execute(sql, val)
+    db.commit()
+    #except:
+    #    db.rollback()
+ 
+    db.close()
+    
+        
+    
+
+
+    
+    
+    
+
+

+ 126 - 0
AWS-test/随机字符组合.py

@@ -0,0 +1,126 @@
+import os
+import subprocess
+# import time
+# start = time.clock()
+
+numb = ['0','1','2','3','4','5','6','7','8','9',
+'a','b','c','d','e','f','g','h',
+'i','j','k','l','m','n','o','p',
+'q','r','s','t','u','v','w','x','y','z']
+shuzi = ['0','1','2','3','4','5','6','7','8','9']
+# passwd = []
+f = open('./password.txt','w')
+for fi in numb:
+    #passwd.append(fi)
+    for s in numb:
+        #passwd.append(fi+s)
+        for t in numb:
+            #passwd.append(fi+s+t)
+            for four in shuzi:
+                f.write(fi+s+t+four+ '\n')
+
+                    
+                # passwd.append(fi+s+t+four)
+
+# f = open('./password.txt','w')
+# # passwd1 = passwd[0:200000]
+# for i in passwd:
+#     f.write(i + '\n')
+f.close()
+
+f = open('./password.txt','w')
+passwd = f.readlines
+
+nu = 0
+for s in passwd:
+    while nu<100:
+        nu += 1
+        print(s)
+        #x = subprocess.getstatusoutput('/root/dd' + ' ' + s)
+        #if "WRONG PASSWORD!" in x[1]:
+        #    print(x[0])
+    
+
+    #if 'CORRECT PASSWORD' in x:
+    #    print(x)
+
+    """
+    outputss = os.popen(['/root/dd' + ' ' + s "&& grep WRONG PASSWORD"])
+    x = outputss.read()
+    if x == "WRONG PASSWORD!":
+        pass
+    x.close()
+    """
+
+    #os.system('/root/dd' + ' ' + s)
+    #subprocess.Popen('/root/dd' + ' ' + s, shell=True, cwd="/home")
+
+
+#print(passwd)
+    #         for four in numb:
+
+    #             print(first+second+thrid+four)
+    
+# elapsed = (time.clock() - start)
+# print("Time used:",elapsed)
+
+
+import os
+import time
+import subprocess
+# import _thread
+import threading
+
+def runa(one,two):
+    f = open('./passwd.txt','r')
+
+    for s in f.readlines()[one:two]:
+            x = subprocess.getstatusoutput('/root/cstor_server/challenge/q2/server -g 8 -u 87 -p' + ' ' + s)
+            if "WRONG PASSWORD!" in x:
+                pass
+            elif "Get User ID!" in x:
+                pass
+            else:
+                print(x,s)
+    f.close()
+
+if __name__ == '__main__':
+    threading.Thread(target=runa,args=(1,10000)).start()
+    threading.Thread(target=runa,args=(10000,20000)).start()
+    threading.Thread(target=runa,args=(20000,30000)).start()
+    threading.Thread(target=runa,args=(30000,40000)).start()
+    threading.Thread(target=runa,args=(40000,50000)).start()
+
+
+import os
+import threading
+
+numb = ['0','1','2','3','4','5','6','7','8','9',
+'a','b','c','d','e','f','g','h',
+'i','j','k','l','m','n','o','p',
+'q','r','s','t','u','v','w','x','y','z']
+shuzi = ['0','1','2','3','4','5','6','7','8','9']
+# passwd = []
+#for fi in numb:
+    #passwd.append(fi)
+#    for s in numb:
+        #passwd.append(fi+s)
+#        for t in numb:
+            #passwd.append(fi+s+t)
+#            for four in shuzi:
+#                if os.popen('./server -u 1 -g 1 -p '+fi+s+t+four).readline()!='WRONG PASSWORD!\n':
+#                    print(fi+s+t+four)
+
+def calc_pass(first='0',laster=0):
+    print('thread start :'+first)
+    for s in numb:
+        #passwd.append(fi+s)
+        for t in numb:
+            #passwd.append(fi+s+t)
+            for four in shuzi:
+                if os.popen('./server -u 11 -g 10 -p '+first+s+t+four).readline()!='WRONG PASSWORD!\n':
+                    print(first+s+t+four)
+                    break
+
+if __name__ == '__main__':
+    map(lambda first:threading.Thread(target=calc_pass, args=(first,"0")).start(),numb)

+ 1 - 0
README.md

@@ -0,0 +1 @@
+# PythonCode

+ 35 - 0
aws-task-ruleless/jam-EDA.py

@@ -0,0 +1,35 @@
+# # import boto3 
+# import pandas as pd
+# # import s3fs
+
+# df = pd.read_csv('s3://cse-cic-ids2018/Processed Traffic Data for ML Algorithms/Wednesday-28-02-2018_TrafficForML_CICFlowMeter.csv',low_memory=False)
+
+# df = df[df.Label != 'Label']
+# # df[100:101]
+# print(df[100:101])
+
+import s3fs
+fs = s3fs.S3FileSystem(anon=True)
+fs = s3fs.S3FileSystem(anon=True)
+fs.ls('cse-cic-ids2018')
+#s3://cse-cic-ids2018/Processed Traffic Data for ML Algorithms/Wednesday-28-02-2018_TrafficForML_CICFlowMeter.csv
+with fs.open('cse-cic-ids2018/Processed Traffic Data for ML Algorithms/Wednesday-28-02-2018_TrafficForML_CICFlowMeter.csv', 'r',encoding='utf-8') as f:
+    reader = csv.reader(f)
+    header = next(reader)
+    print(header)
+    i=0
+    for row in reader:
+        i=i+1
+        if i<102 and i>98:
+            print(i,row)
+
+
+len(csvdata)
+print(csvdata[0:1000])
+import pandas as pd
+csvdata = csvdata.decode('utf-8')
+data_frame = pd.read_csv(csvdata)
+print(len(data_frame))
+import csv
+reader = csv.reader(csvdata)
+print(next(reader))

+ 262 - 0
awsClean/appclean.py

@@ -0,0 +1,262 @@
+#!/usr/bin/python3
+#  --*-- coding:utf-8 --*--
+import requests, json, os, time
+import pymysql
+import time, datetime
+import logging
+import logging.handlers
+
+logger = logging.getLogger('/root/xcloudclean/app_info.log')
+logger.setLevel(logging.DEBUG)
+
+rf_handler = logging.handlers.TimedRotatingFileHandler('/root/xcloudclean/app_clear.log', when='midnight', interval=1, backupCount=7, atTime=datetime.time(0, 0, 0, 0))
+rf_handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
+f_handler = logging.FileHandler('/root/xcloudclean/app_error.log')
+f_handler.setLevel(logging.ERROR)
+f_handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(filename)s[:%(lineno)d] - %(message)s"))
+
+logger.addHandler(rf_handler)
+logger.addHandler(f_handler)
+
+# logging.basicConfig(filename='./clear_info.log', level=logging.INFO)
+
+
+CLEAR_ID = []
+CLEAN_ERROR_ID = []
+CLEAN_SUCCESS_ID = []
+CLEAN_PENDING_ID = []
+STRATE_TIME = datetime.datetime.now()
+# clear_status : 1.清理完成 2.待清理 3.清理中 4.清理失败
+
+def get_data():
+    conn1 = pymysql.connect(
+        host='10.99.1.85',
+        port=3306,
+        user='gluttony',
+        passwd='gluttony',
+        db='awsregistry',
+        charset='utf8mb4')
+
+    cs1 = conn1.cursor()
+    select_sql = "SELECT id FROM r_aws_account_info WHERE clear_status=2;"
+    cs1.execute(select_sql)
+    response = cs1.fetchall()
+    cs1.close()
+    conn1.close()
+
+    yield response
+
+
+def updata_db(info_sql):
+    conn2 = pymysql.connect(
+        host='10.99.1.85',
+        port=3306,
+        user='gluttony',
+        passwd='gluttony',
+        db='awsregistry',
+        charset='utf8mb4')
+
+    cs2 = conn2.cursor()
+    try:
+        cs2.execute(info_sql)
+        conn2.commit()
+        logger.info(f" Exec_SQL_Syntax: {info_sql}")
+    except Exception as e:
+        conn2.rollback()
+        logger.error(f" Exec_SQL_Syntax_ERROR: {e}\t,{info_sql}")
+    finally:
+        conn2.close()
+
+
+def send_email(error_id):
+    import smtplib
+    from email.mime.text import MIMEText
+    from email.header import Header
+
+    mail_host="smtp.qiye.163.com"
+    mail_user="cloud@cstor.cn"
+    mail_pass="Cstor0820"
+
+    sender = 'cloud@cstor.cn'
+    receivers = ['xclouds@qq.com','xiechao@cstor.cn',
+        'suzeyue@cstor.cn','taozhongyuan@cstor.cn','panhaonan@cstor.cn',
+        'xuchong@cstor.cn','2214395275@qq.com']
+    # receivers = ['xclouds@qq.com']
+    message = MIMEText('gluttony.cstor.cn Resource 清理异常......\n\n请及时处理。', 'plain', 'utf-8')
+    message['From'] = Header("gluttony", 'utf-8')
+    message['To'] =  Header("平台部云计算项目组", 'utf-8')
+
+    subject = f'AWS清理失败(ACCOUNT ID: {error_id})'
+    message['Subject'] = Header(subject, 'utf-8')
+    try:
+        smtpObj = smtplib.SMTP()
+        smtpObj.connect(mail_host, 25)
+        smtpObj.login(mail_user,mail_pass)
+        smtpObj.sendmail(sender, receivers, message.as_string())
+        logger.info("邮件发送成功")
+    except smtplib.SMTPException as e:
+        logger.error(f"Error: 无法发送邮件\t {e}")
+
+def auth_post():
+    url_auth = "http://localhost:8000/api/user/auth"
+
+    auth_body = {"username": "admin", "password": "admin"}
+    auth_headers = {
+        "Content-Type": "application/json, charset=UTF-8"
+    }
+    auth_original = requests.request('post', url_auth, json=auth_body, headers=auth_headers)
+    access_token_original = auth_original.json()
+    access_token = access_token_original['access_token']
+
+    return access_token
+
+def get_status():
+    CLEAR_ID_orginal = get_data()
+    for i in CLEAR_ID_orginal:
+        id_list = list(i)
+        for a in id_list:
+            b = list(a)
+            for c in b:
+                CLEAR_ID.append(c)
+    return CLEAR_ID
+
+
+def clear_post():
+    url_clear = "http://localhost:8000/api/resource/clear/range"
+    data_headers = {
+        'Content-Type': 'application/json',
+        'Authorization': 'Bearer ' + auth_post()
+    }
+
+    json_id = {'ID': CLEAR_ID}
+    data_original = requests.post(url_clear, json=json_id, headers=data_headers)
+
+    try:
+        if "message" in data_original.text:
+            raise TypeError(data_original.text)
+    except TypeError as e:
+        logger.error(f" ERROR {e}")
+
+    logger.info(f" Clear ID =  {json_id}")
+    logger.info(f" HTTP Response  {data_original.text}")
+    # return data_original
+
+def init_post(init_id):
+    init_headers = {'content-type': 'application/x-www-form-urlencoded'}
+    init_url = "http://10.99.1.85:8081/account/init"
+    params = {"account_ids":init_id}
+    resp = requests.post(init_url, data=params, headers=init_headers)
+    logger.info(f"init_id: {init_id},   Status:{resp.text}")
+
+def dbs_pending_status(sql_clear_id):
+    id_tup = tuple(sql_clear_id)
+    if len(id_tup) == 1:
+        sql_old = f"UPDATE r_aws_account_info SET clear_status=3 WHERE clear_status=2 AND id IN {id_tup};"
+        sql_exec = sql_old.replace(",", "")
+        updata_db(sql_exec)
+    else:
+        sql_exec = f"UPDATE r_aws_account_info SET clear_status=3 WHERE clear_status=2 AND id IN {id_tup};"
+        updata_db(sql_exec)
+
+def updata_db_pending(sql_clear_id):
+    sql_old = f"UPDATE r_aws_account_info SET clear_status=3 WHERE clear_status=2 AND id IN ({sql_clear_id});"
+    updata_db(sql_old)
+
+def updata_db_success(sql_clear_id):
+    sql_old = f"UPDATE r_aws_account_info SET clear_status=1 WHERE clear_status=3 AND id IN ({sql_clear_id});"
+    updata_db(sql_old)
+
+def updata_db_error(sql_clear_id):
+    # id_tup = tuple(sql_clear_id)
+    # if len(id_tup) == 1:
+    sql_old = f"UPDATE r_aws_account_info SET clear_status=4 WHERE clear_status=3 AND id IN ({sql_clear_id});"
+    # sql_exec = sql_old.replace(",", "")
+    updata_db(sql_old)
+    # else:
+    #     sql_exec = f"UPDATE r_aws_account_info SET clear_status=4 WHERE clear_status=3 AND id IN {id_tup};"
+    #     updata_db(sql_exec)
+
+CLEAN_STATUS_GET_HEADER = {
+        'Content-Type': 'application/json',
+        'Authorization': 'Bearer ' + auth_post()}
+
+def clean_status_get(r_id):
+    status_url = f"http://127.0.0.1:8000/api/status/account/state/{r_id}"
+    resp = requests.get(status_url,headers=CLEAN_STATUS_GET_HEADER)
+    logger.info(f"Clean_Status:{resp.text}")
+    if "SUCCESS" in json.loads(resp.text)["account_clean_status"]:
+        # {"account_clean_status":"SUCCESS","id":"8","start_time":"2021-01-06 16:02:00.018024","state":"200"}
+        CLEAN_SUCCESS_ID.append(r_id)
+        updata_db_success(r_id)
+
+        if r_id in CLEAN_PENDING_ID:
+            CLEAN_PENDING_ID.remove(r_id)
+    elif "PENDING" in json.loads(resp.text)["account_clean_status"]:
+        # {"account_clean_status":"PENDING","id":"102","start_time":"2021-01-06 17:42:10.059127"}
+        if r_id in CLEAN_PENDING_ID:
+            pass
+        else:
+            CLEAN_PENDING_ID.append(r_id)
+    else:
+        CLEAN_ERROR_ID.append(r_id)
+        updata_db_error(r_id)
+        if r_id in CLEAN_PENDING_ID:
+            CLEAN_PENDING_ID.remove(r_id)
+
+def while_pending_status(pending_id):
+
+    while len(CLEAN_PENDING_ID) > 0:
+        time.sleep(180)
+        current_time = datetime.datetime.now()
+        process_time = (current_time - STRATE_TIME).seconds
+        if process_time < 2400:
+            for i in pending_id:
+                clean_status_get(i)
+        elif process_time > 2400:
+            for err_id in pending_id:
+                CLEAN_ERROR_ID.append(err_id)
+                CLEAN_PENDING_ID.remove(err_id)
+                
+                # updata_db_error(err_id)
+                # return
+
+def start_now():
+    global CLEAR_ID 
+    global CLEAN_ERROR_ID
+    global CLEAN_SUCCESS_ID
+    global CLEAN_PENDING_ID 
+    get_status()
+    logger.info(f" Start: NOW")
+    logger.info(f" Id: {CLEAR_ID}")
+    if CLEAR_ID == []:
+        logger.info("ID: None ")
+        logger.info("None exit cleanapp")
+        os._exit(0)
+    else:
+        clear_post()
+        # clear_status : 1.清理完成 2.待清理 3.清理中 4.清理失败
+        dbs_pending_status(CLEAR_ID)   # status 2 --> 3
+        time.sleep(600)
+
+        for i in CLEAR_ID:
+            clean_status_get(i)
+        if CLEAN_PENDING_ID == [] and CLEAN_ERROR_ID == []:
+            pass
+        elif CLEAN_PENDING_ID != []:
+            while_pending_status(CLEAN_PENDING_ID)
+        elif CLEAN_ERROR_ID != []:
+            send_email(CLEAN_ERROR_ID)
+        for i in CLEAN_SUCCESS_ID:
+            init_post(i)
+
+    logger.info(f"clean SUCCESS ID:  {CLEAN_SUCCESS_ID}")
+    logger.info(f"clean PENDING ID:  {CLEAN_PENDING_ID}")
+    if CLEAN_ERROR_ID == []:
+        pass
+    else:
+        logger.error(f"clean ERROR ID:  {CLEAN_ERROR_ID}")
+    logger.info("End:  end")
+    logger.info("\n")
+
+if __name__ == '__main__':
+    start_now()ls

+ 9 - 0
myapp.log

@@ -0,0 +1,9 @@
+INFO:root:info msg
+WARNING:root:WR msg
+INFO:root:info msg
+WARNING:root:WR msg
+DEBUG:example:debug message
+INFO:example:info message
+WARNING:example:warn message
+ERROR:example:error message
+CRITICAL:example:critical message


+ 31 - 0
python_base/day10/函数的作用域关系.py

@@ -0,0 +1,31 @@
+# -*- coding: UTF-8 -*-
+
+# 作用域关系是在函数定义阶段就已经固定的,与函数的调用位置无关
+
+x = 1
+def f2():
+    print(x) 
+
+x = 100
+
+def f3(func):
+    x = 2
+    func() # 在前面已经调用了 x = 1000
+    print(x)  # 优先使用局部变量  x = 2
+x = 1000
+
+f3(f2)  
+
+li = [lambda : i       for i in range(10)]  # i 是全局变量,附值最好一个 9 ,所以所有函数中 i = 9
+
+# li 中的元素是什么类型的对象
+"""  函数 """
+print(li)
+
+# li[0] 是什么,能否被调用
+""" 是一个函数,可以被调用 """
+
+# print(type(li))
+respond = li[0]()  
+print(respond)
+print(li[8]()) # 输出还是9

+ 40 - 0
python_base/day10/多层装饰器.py

@@ -0,0 +1,40 @@
+# -*- coding: UTF-8 -*-
+
+def outer(flag):
+    def wrapper(func):
+        def inner(*args,**kwargs):
+            if flag:
+                print('before')
+                result = func(*args,**kwargs)
+                print('agter')
+            else:
+                r = func(*args,**kwargs)
+
+            return result
+        return inner
+    return wrapper
+
+def do_something(arg):
+    def wrapper():
+        print('#' * 22)
+        arg()
+        print('#' * 22)
+    return wrapper
+
+def decorator(func):
+    def wrapper():
+        print('*' * 19)
+        func()
+        print('*' * 19)
+    return wrapper
+
+do_something(decorator)
+
+@do_something  # inner = do_somethinf(decorator(inner))
+@decorator
+def inner():
+    print('xdc')
+    print('xdc.ink')
+inner()
+
+       

+ 18 - 0
python_base/day10/递归函数实现.py

@@ -0,0 +1,18 @@
+# -*- coding: UTF-8 -*-
+
+def get_age(n):
+    if n == 0:
+        return 18
+    return get_age(n -1) + 1
+
+ret = get_age(3)
+print(ret)
+
+for i in range(10):
+    pass
+print(i)
+
+li = [ lambda : i for i in range(10) ]  # i 的值是 9 , 相当于全局变量附值操作
+print(li[7]())
+print(type(li))
+

+ 43 - 0
python_base/day10/面向对象之类.py

@@ -0,0 +1,43 @@
+# -*- coding: UTF-8 -*-
+
+# class Person():
+#     def __init__(self, name, age):
+#         self.name = name
+#         self.Age = age
+
+# xdc = Person('xdc.ink', 101)  
+# print(xdc.name)
+# print(xdc.Age) 
+
+
+# class Person():
+#     def __init__(self, name, age):
+#         self.name = name
+#         self.Age = age
+
+#     def run(self):
+#         print( "内部", id(self), self)
+#         print(f"{self.name} is running")
+
+# xdc = Person('xdc.ink', 101)  
+# xdc.run()
+# print("外部", id(xdc),xdc)
+
+###============多============### 
+
+class Person():
+    def __init__(self, name, age):
+        self.name = name
+        self.Age = age
+
+    def run(self):
+        print( "内部", id(self), self)
+        print(f"{self.name} is running")
+    
+    def talk(self, speed):
+        print(f"{self.name} 正在跑步,ta的速度是{speed}")
+        self.run()
+
+xdc = Person('xdc.ink', 101)  
+xdc.talk("2km/h")
+

+ 20 - 0
python_base/day11/属性.py

@@ -0,0 +1,20 @@
+# -*- coding: UTF-8 -*-
+
+class Person():
+    city = 'BeiJing'    # 类的数据属性
+    def __init__(self, name, age):
+        self.name =name     # 实例对象的数据属性
+        self.age = age
+    
+    def run(self):      # 类的函数属性
+        print(f"{self.name} is talk")
+
+xdc = Person('xdc', 18)
+xiguatian = Person('xiaoguatian', 19)
+
+# 所有的实例都可以调用类的所有属性
+print(xdc.city)
+xdc.run()
+
+print(xiguatian.city)
+xiguatian.run()

+ 96 - 0
python_base/day11/方法.py

@@ -0,0 +1,96 @@
+# -*- coding: UTF-8 -*-
+
+# 凡是在类里面定义的函数都称为方法
+# 方法的本质上是函数,也是类的函数属性 
+## 所有的绑定方法,定义的时候,必须有一个形参,通常写作 self
+## 在调用的时候,将会把 调用者这个对象赋值给 self (谁掉用就赋值给谁)
+
+# class AP():
+#     # 实例的绑定方法 类的函数属性
+#     def __init__(self, name, hp=1000, atc=79):
+#         self.name = name # 对象的属性
+#         self.hp = hp
+#         self.atc = atc
+
+#     def run(self):
+#         print(self, id(self)
+
+###=================类的方法=================###
+
+class Foo():
+    @classmethod
+    def run(cls):
+        """ 类方法,cls就是类 --> 调用了此方法的类 """
+        print(cls)
+
+    @staticmethod
+    def foo(arg1, arg2):  # 定义了几个参数,必要要传几个参数
+        """本质上就是一个普通的函数而已,只不过是在类里面定义了"""
+        pass
+
+obj = Foo()
+print(obj)
+
+###================= @classmethod =================###
+#!/usr/bin/python
+# -*- coding: UTF-8 -*-
+"""
+classmethod 修饰符对应的函数不需要实例化,
+不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数
+,可以来调用类的属性,类的方法,实例化对象等。
+"""
+
+class A(object):
+    bar = 1
+    def func1(self):  
+        print ('foo') 
+    @classmethod
+    def func2(cls):
+        print ('func2')
+        print (cls.bar)
+        cls().func1()   # 调用 foo 方法
+ 
+A.func2()               # 不需要实例化
+
+###================= @staticmethod =================###
+
+#!/usr/bin/python
+# -*- coding: UTF-8 -*-
+ 
+class C(object):
+    @staticmethod
+    def f():
+        print('runoob');
+ 
+C.f();          # 静态方法无需实例化
+cobj = C()
+cobj.f()        # 也可以实例化后调用
+
+
+###================= 菜鸡教程中的解释 =================###
+class A(object):
+
+    # 属性默认为类属性(可以给直接被类本身调用)
+    num = "类属性"
+
+    # 实例化方法(必须实例化类之后才能被调用)
+    def func1(self): # self : 表示实例化类后的地址id
+        print("func1")
+        print(self)
+
+    # 类方法(不需要实例化类就可以被类本身调用)
+    @classmethod
+    def func2(cls):  # cls : 表示没用被实例化的类本身
+        print("func2")
+        print(cls)
+        print(cls.num)
+        cls().func1()
+
+    # 不传递传递默认self参数的方法(该方法也是可以直接被类调用的,但是这样做不标准)
+    def func3():
+        print("func3")
+        print(A.num) # 属性是可以直接用类本身调用的
+    
+# A.func1() # 这样调用是会报错:因为func1()调用时需要默认传递实例化类后的地址id参数,如果不实例化类是无法调用的
+A.func2()
+A.func3()

+ 22 - 0
python_base/day11/类的继承.py

@@ -0,0 +1,22 @@
+# -*- coding: UTF-8 -*-
+
+class Person():
+    city = 'BeiJing'    # 类的数据属性
+    
+    def __init__(self, name, age):
+        self.name =name     # 实例对象的数据属性
+        self.age = age
+    
+    def run(self):      # 类的函数属性
+        print(f"{self.name} is talk")
+
+
+class Teacher(Person):
+    # 增加新方法
+    def talk(self):
+        print(f"{self.name} 牛 🐂")
+    pass
+
+xdc = Teacher('秀', 38)
+xdc.talk()
+

+ 86 - 0
python_base/day11/计算.py

@@ -0,0 +1,86 @@
+# -*- coding: UTF-8 -*-
+
+# def Foo():
+#     n1 = 20
+#     n2 = 10
+#     def add_item():
+#         print(n1 + n2)
+#     def reduce():
+#         print(n1 - n2)
+#     return {"add": add_item, "reduce": reduce}
+
+# obj = Foo()
+# obj["add"]()
+# obj["reduce"]()
+
+###============ 类的写法  ============###
+
+# class Foo():
+#     def __init__(self, n1, n2):
+#         self.n1 = n1
+#         self.n2 = n2
+  
+#     def add_item(self):
+#         print(self.n1 + self.n2)
+#     def reduce(self):
+#         print(self.n1 - self.n2)
+
+# obj = Foo(20, 5)
+# obj.add_item()
+# obj.reduce()
+
+###============ 传值  ============###
+
+# class Foo():
+#     def __init__(self, n1):
+#         self.n1 = n1
+        
+#     def add_item(self,n2):
+#         print(self.n1 + n2)
+#     def reduce(self, n2):
+#         print(self.n1 - n2)
+
+# obj = Foo(20)
+# obj.add_item(5)
+# obj.reduce(1)
+
+###============ 传值  ============###
+
+# class Foo():
+#     def __init__(self, n1):
+#         self.n1 = n1
+
+#     def add_item(self, n2):
+#         print(self.n1 - n2()) # 定义成什么类型,传的就是什么类型
+#         # print(self.n1 - n2[])
+
+# def f():
+#     return 30
+     
+# obj = Foo(20)
+# obj.add_item(f)
+# # obj.add_item([1])
+
+###============ 攻击别的英雄  ============###
+
+class AP():
+    def __init__(self, h, atc):
+        self.h = h
+        self.atc = atc
+    
+    def attack(self,obj):
+        """ 攻击另一个英雄 """
+        # 攻击代码
+        # 被攻击的英雄生命值需要减去自己对象的攻击力
+        obj.h = obj.h - self.atc
+        print(f"{obj.h} ".format(obj.h))
+
+obj1 = AP(100, 10)
+obj2 = AP(200, 20)
+
+obj1.attack(obj2)
+print(obj1.h)
+obj1.h = 101
+print(obj1.h)
+
+

+ 16 - 0
python_base/day11/面向对象.py

@@ -0,0 +1,16 @@
+# -*- coding: UTF-8 -*-
+
+class AP():
+    def __init__(self, name, hp=668, atc= 78):
+        self.name = name
+        self.hp = hp
+        self.atc = atc
+    
+    def attck(self):
+        print(self.atc)
+
+    
+zj = AP('甄姬')
+xq = AP("小乔", 990, 1)
+xq.attck()
+

+ 13 - 0
python_base/day11/魔法函数(方法).py

@@ -0,0 +1,13 @@
+# -*- coding: UTF-8 -*-
+
+class Person:
+    def __init__(self, name, age):
+        self.name = name
+        self.age = age
+    
+    def __str__(self):  # 固定格式 __str__
+        return f"Person(name={self.name}, age={self.age})"
+        # 返回值是 str 类型。
+
+p = Person('xdc',18)
+print(p)

+ 14 - 0
python_base/day12/cmdb/bin/run.py

@@ -0,0 +1,14 @@
+#!/usr/bin/env python3
+import sys, os
+Base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+print(Base_dir)
+# Base_dir = '/Users/xc/git-python/day12/cmdb'
+sys.path.insert(0, Base_dir)
+
+from plugins import cpu, mem
+cpu = cpu.Cpu()
+mem = mem.Mem()
+
+for obj in [cpu, mem]:
+	info = obj.cmd_handle()
+	print(info)

BIN
python_base/day12/cmdb/plugins/__pycache__/cpu.cpython-37.pyc


BIN
python_base/day12/cmdb/plugins/__pycache__/mem.cpython-37.pyc


+ 3 - 0
python_base/day12/cmdb/plugins/cpu.py

@@ -0,0 +1,3 @@
+class Cpu():
+    def cmd_handle(self):
+        return 'cpu in info'

+ 3 - 0
python_base/day12/cmdb/plugins/mem.py

@@ -0,0 +1,3 @@
+class Mem():
+	def cmd_handle(self):                                                   
+		return 'mem in info'

+ 7 - 0
python_base/day12/cmdb/test.py

@@ -0,0 +1,7 @@
+import os,sys
+
+print(__file__)
+path = os.path.abspath(__file__)
+
+path = os.path.dirname(path)
+print(path)

+ 22 - 0
python_base/day12/判断是否是某些类型的实例.py

@@ -0,0 +1,22 @@
+# -*- coding: UTF-8 -*-
+
+def tail_t(path):
+    if isinstance(path , (list, tuple)):  # 判断输入的是否为列表、元组。可以穿多个
+        p_list = path
+    else:
+        p_list = [path]
+    
+    for p in p_list:
+        print(p)
+
+li = ['/root/', '/home/ec-user']
+tail_t(li)
+
+
+class Cpu():
+    def cmd_handle(self):
+        return 'cpu in info'
+    
+class Mem():
+    def cmd_handle(self):
+        return 'mem in info'

+ 28 - 0
python_base/day12/方法的个性实验.py

@@ -0,0 +1,28 @@
+# -*- coding: UTF-8 -*-
+
+class Foo():
+    def __init__(self, name):
+        self.name = name
+
+    def run(self):
+        print(self.name)
+
+    @classmethod
+    def class_method(cls,o):
+        cls.run(o)
+    
+obj = Foo('xdc')
+Foo.class_method(obj)
+
+class Foo2():
+    def talk(self):
+        self.foo(1,2)
+    @classmethod
+    def run(cls):
+        print(cls)
+    
+    @staticmethod
+    def foo(arg1, arg2):
+        print(arg1)
+
+Foo2().talk()

+ 28 - 0
python_base/day12/私用属性.py

@@ -0,0 +1,28 @@
+# -*- coding: UTF-8 -*-
+
+class Person:
+    def __init__(self, f_name, s_name):
+        self.__f_name = f_name # 私用属性。__  只能在内部调用
+        self.s_name = s_name
+    
+    # 特性
+    @property # 装饰下面函数,不需要加()就可以执行
+    def full_name(self):
+        return f"{self.__f_name} {self.s_name}" # 使用私用属性
+
+obj = Person('xu', 'dc')
+print(obj.full_name)
+# print(obj.__f_name) # 私用属性,无法在外部调用
+
+###============ 函数匿名  ============###
+
+class A():
+    def __run(self):  # 函数也可以定义为 私用 __ 双下滑线
+        pass
+class B(A):
+    pass
+
+obj = B()
+# print(obj.__run(1)) # 无法调用
+print(A.__dict__)   # 重命名技术。可以打印出来。看看  __run  变成了什么样
+A._A__run(1) # 这样就可以访问私用属性了。

+ 49 - 0
python_base/day12/类的继承顺序.py

@@ -0,0 +1,49 @@
+
+# class A:
+#     pass
+
+# class B(A):
+#     pass
+
+# class C(B):
+#     pass
+
+# print(C.__mro__)
+# print(B.__mro__)
+# print(A.__mro__)
+
+
+class A(object): 
+    def test(self):
+        print('from A')
+ 
+class B(A):
+    def test(self):
+        print('from B')
+ 
+class C(A):
+    def test(self):
+        print('from C')
+ 
+class D(B):
+    def test(self):        
+        print('from D') 
+
+class E(C):     
+    def test(self):         
+        print('from E') 
+class F(D,E):     
+    def test(self):     
+        print('from F')     
+
+f1=F()
+f1.test()
+print(F.__mro__) #只有新式才有这个属性可以查看线性列表,经典类没有这个属性
+
+
+# 新式类继承顺序:F->D->B->E->C->A
+# 经典类继承顺序:F->D->B->A->E->C
+# python3中统一都是新式类
+# pyhon2中才分新式类与经典类
+# 所有的父类的MRO列表遵循如下原则:
+#   子类会先于父类被检查;多个父类会根据它们在列表中的顺序被检查;如果对下一个类存在两个合法的选择,则选择第一个类。

+ 42 - 0
python_base/day12/继承2.py

@@ -0,0 +1,42 @@
+# -*- coding: UTF-8 -*-
+
+# class Person():
+#     city = 'BeiJing'    # 类的数据属性
+    
+#     def __init__(self, name, age):
+#         self.name =name     # 实例对象的数据属性
+#         self.age = age
+    
+#     def run(self):      # 类的函数属性
+#         print(f"{self.name} is talk")
+
+
+# class Teacher(Person):
+
+#     def run(self):  # 继承的时候可以覆盖
+#         print(f"{self.name} 牛 🐂")
+#     pass
+
+
+
+###============ 添加新的属性  ============###
+
+class Person():
+
+    city = 'BeiJing'    
+    
+    def __init__(self, name, age):
+        self.name =name    
+        self.age = age
+
+class Teacher(Person):
+
+    def __init__(self,name, age, level):
+        super().__init__(name, age) 
+        Person.__init__(self, name, age) # 调用了父类
+        self.level = level
+
+obj = Teacher('xdc', 18, 2)
+print(obj.__dict__)  # 查看属性
+print(Teacher.__mro__) # 最后面的是顶级的类 object 
+# (<class '__main__.Teacher'>, <class '__main__.Person'>, <class 'object'>)

+ 14 - 0
python_base/day13/cmdb/bin/run.py

@@ -0,0 +1,14 @@
+#!/usr/bin/env python3
+import sys, os
+Base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+print(Base_dir)
+# Base_dir = '/Users/xc/git-python/day12/cmdb'
+sys.path.insert(0, Base_dir)
+
+from plugins import cpu, mem
+cpu = cpu.Cpu()
+mem = mem.Mem()
+
+for obj in [cpu, mem]:
+	info = obj.cmd_handle()
+	print(info)

+ 4 - 0
python_base/day13/cmdb/conf/settings.py

@@ -0,0 +1,4 @@
+PLUGINS_DIC = {
+    "CPU":"plugins.cup.Cpu",
+    "MEM":"plugins.mem.Mem"
+}

+ 18 - 0
python_base/day13/cmdb/core/main.py

@@ -0,0 +1,18 @@
+# -*- coding: UTF-8 -*-
+# 第一行 内置模块
+import importlib
+
+# 第二行 第三方模块
+
+# 第三行 自定义模块
+
+from conf.settings import PLUGINS_DIC as plugins
+
+def main():
+    for key, val in plugins.items():
+        mod_path, cls_name = val.rsplit('.', 1)
+        mod_obj = importlib.import_module(mod_path)
+        cls = getattr(mod_obj,cls_name) 
+        obj = cls()
+        info = obj.cmd_handle()
+        print(info)

BIN
python_base/day13/cmdb/plugins/__pycache__/cpu.cpython-37.pyc


BIN
python_base/day13/cmdb/plugins/__pycache__/mem.cpython-37.pyc


+ 3 - 0
python_base/day13/cmdb/plugins/cpu.py

@@ -0,0 +1,3 @@
+class Cpu():
+    def cmd_handle(self):
+        return 'cpu in info'

+ 3 - 0
python_base/day13/cmdb/plugins/mem.py

@@ -0,0 +1,3 @@
+class Mem():
+	def cmd_handle(self):                                                   
+		return 'mem in info'

+ 8 - 0
python_base/day13/cmdb/test.py

@@ -0,0 +1,8 @@
+import os,sys
+
+print(__file__)
+path = os.path.abspath(__file__)
+
+path = os.path.dirname(path)
+print(path)
+

+ 11 - 0
python_base/day13/反射倒入模块.py

@@ -0,0 +1,11 @@
+# -*- coding: UTF-8 -*-
+
+import importlib
+
+mod_name = input("输入模块名:")
+print(mod_name)
+mod_obj = importlib.import_module(mod_name)
+print(mod_obj)
+f = getattr(mod_obj, 'foo')  # 
+f() # 直接可以使用了
+

+ 35 - 0
python_base/day13/自省与反射.py

@@ -0,0 +1,35 @@
+# -*- coding: UTF-8 -*-
+
+###============ 反射  ============###
+
+class Person():
+    city = '南京'
+    def __init__(self, name, age):
+        self.name = name 
+        self.age = age
+    
+    def intor(self):
+        return f"{self.name}"
+
+# 
+xdc = Person('xiguatian', 18)
+# 判断 类对象 是否存在 city 属性 (hasattr)
+print( hasattr(Person , 'city') )
+
+r = hasattr(Person, 'intor')
+
+# 获取属性  (getattr)
+
+print(getattr(Person,'city'))
+
+r = getattr(xdc, 'intor') # 本质上是一个函数,
+print(r())
+
+# 设置属性 (setattr)
+
+    #  对象, 对象属性名称  修改后的属性值
+setattr(xdc, 'name', 'magua')
+
+# 删除属性  (delattr)
+
+delattr(xdc, 'name')

+ 42 - 0
python_base/day13/自省与反射的概念.py

@@ -0,0 +1,42 @@
+# -*- coding: UTF-8 -*-
+
+"""
+#
+自省
+#
+In computing, type introspection is the ability of a program to examine the type or
+ properties of an object at runtime. Some programming languages possess this capability.
+在计算机科学中,内省是指计算机程序在运行时(Run time)检查对象(Object)类型(以及属性等)的一种能力,通常也可以称作运行时类型检查。
+
+方法	作用	类型
+help()	查看函数或者模块用途的详细说明	             自省
+dir()	返回对象所有属性	                       自省
+type()	查看对象类型	                           自省 
+isinstance()	判断一个对象是否是一个已知的类型	   自省
+issubclass()	判断一个类是不是另一个类的子类	      自省
+id()	返回地址值	                               自省
+callable()	判断对象是否可调用	                    自省
+
+"""
+"""
+#
+反射
+#
+
+Introspection should not be confused with reflection, which goes a step further and is the 
+ability for a program to manipulate the values, meta-data, properties and/or functions of an object at runtime.
+也就是说自省和反射不是同一回事,自省是获取对象类型的能力,而反射是操纵对象的值,元数据,属性和/或函数的能力。
+
+  在计算机学中,反射(英语:reflection)是指计算机程序在运行时(runtime)可以访问、检测和修改它本身状态或行为的一种能力。
+用比喻来说,反射就是程序在运行的时候能够“观察”并且修改自己的行为。
+  在Python中反射非常简单,用起来几乎感觉不到与其他的代码有区别,使用反射获取到的函数和方法可以像平常一样加上括号直接调用,
+获取到类后可以直接构造实例;不过获取到的字段不能直接赋值,因为拿到的其实是另一个指向同一个地方的引用,赋值只能改变当前的这个引用而已。
+
+方法	作用	类型
+hasattr()	判断类方法或者类属性是否存在,返回一个布尔值,存在返回True,反之返回Flase	反射
+getattr()	获取属性值或实例方法,如果其不存在,会抛出一个AttributeError异常	反射
+setattr()	设置实例属性的值,如果实例属性不存在时,会自动给当前实例添加该属性	反射
+delattr()	删除实例的属性或者实例的方法,当其不存在时同样会抛出一个AttributeError异常	反射
+
+
+"""

+ 17 - 0
python_base/day14/发送邮件.py

@@ -0,0 +1,17 @@
+# -*- coding: UTF-8 -*-
+import yagmail
+
+yag = yagmail.SMTP(
+    user='xclouds@qq.com',
+    host='smtp.qq.com',
+    password='899',
+    port='25',
+    smtp_ssl=False)
+
+yag.send(
+    to='470234147@qq.com',
+    subject='from xdc',
+    contents='didi!')
+
+# 邮件正文
+    # attachments= ['/root/1.jpg'] # 添加附件

+ 29 - 0
python_base/day14/小爬虫学习.py

@@ -0,0 +1,29 @@
+# -*- coding: UTF-8 -*-
+
+import requests
+# url = 'https://doutula.com/photo/list/'
+url = "http://baidu.com"
+r = requests.get(url)
+
+# 获取 响应状态码
+print(r.status_code)
+
+# 拿到二进制的内容
+print(r.content)
+
+# 得到字符串的内容
+## 方式1:
+    # 我们自己指定一个字符编码进行解码
+print(r.content,enconding='utf-8')
+## 方式2:
+    # 使用系统默认的字符编码进行解码
+html = r.text
+print(html)
+
+#=======================爬取图片=========================#
+
+ 
+r = requests.get(url="http://img.doutula.com/production/uploads/image/2020/06/09/20200609705266_afoUFD.png")
+
+with open("./wangjingze.png", 'wb') as f:
+    f.write(r.content)

+ 19 - 0
python_base/day14/时间模块之预约时.py

@@ -0,0 +1,19 @@
+# -*- coding: UTF-8 -*-
+import datetime
+inp = input('输入时间格式(年-月-日 时:分:秒):')
+nowtime = datetime.datetime.now()
+# restime = datetime.datetime.strptime(inp, '%Y-%m-%d %H:%M:%S')
+restime = datetime.datetime.strptime("2020-09-23 12:00:00", '%Y-%m-%d %H:%M:%S')
+
+# print (nowtime)
+# print(restime)
+t = restime - nowtime
+print(str(t))
+print(t.days)
+print(t.seconds)
+hour, second = divmod(t.seconds, 3600)
+minute, second = divmod(second, 60)
+
+data_time = f"{t.days}天{hour}小时{minute}分{second}秒"
+print(data_time)
+

+ 12 - 0
python_base/day14/正则表达式.py

@@ -0,0 +1,12 @@
+# -*- coding: UTF-8 -*-
+import re
+s = 'isinstance yangge enumerate www.xdc.ink 1999'
+
+r = re.findall("a(?P<name>\w+)", s)  # 分组
+print(r)
+ 
+#  li = re.split('any', s)
+#  print(li)
+
+print(re.findall('a.*b', 'a1b2222222b'))   # 贪婪匹配
+print(re.findall('a.*?b', 'a1b2222222b'))  # 非贪婪匹配,最小匹配

+ 30 - 0
python_base/day15/JSON序列化.py

@@ -0,0 +1,30 @@
+# -*- coding: UTF-8 -*-
+
+# json.dumps(): 对数据进行编码。
+# json.loads(): 对数据进行解码。
+import json
+
+info = [
+    '{"server1_name":"1","info1"}',
+    '{"server2_name":"2","info2"}',
+]
+json.dumps(info)
+
+#======================= python字典转化为 json 对象 =========================#
+
+import json
+ 
+# Python 字典类型转换为 JSON 对象
+data = {
+    'no' : 1,
+    'name' : 'Runoob',
+    'url' : 'http://www.runoob.com'
+}
+ 
+json_str = json.dumps(data)
+print ("Python 原始数据:", repr(data))
+print ("JSON 对象:", json_str)
+
+#======================= 将 JSON 对象转换为 Python 字典 =========================#
+python_dict = json.loads(json_str)
+print(python_dict)

+ 11 - 0
python_base/day15/redis使用.py

@@ -0,0 +1,11 @@
+# -*- coding: UTF-8 -*-
+
+
+import redis
+r = redis.Redis(host="127.0.0.1", port="6379")
+r.info()
+r.set('name','xdc',12)
+info = r.get('name') #获取到的为二进制
+
+str(info, enconding='utf-8') # 转换为字符串类型
+bytes('xdc', enconding='utf-8')  # 转换为二进制类型

+ 59 - 0
python_base/day15/异常处理.py

@@ -0,0 +1,59 @@
+# -*- coding: UTF-8 -*-
+
+# 1/0
+
+
+# x = 'xdc'
+# try:
+#     int(x)
+# except IndexError as e:  # 未捕获到异常,直接退出
+#     print(e)
+
+#======================= 多个异常判断 =========================#
+
+# x = 'xdc'
+# try:
+#     int(x)
+# except IndexError as e: # 不是这个异常,跳过
+#     print(e)
+# except ValueError as e: # 
+    # print("2--->", e)
+
+#======================= 万能异常 Exception =========================#
+
+# x = 'xdc'
+# try:
+#     int(x)
+# except Exception as e:  
+#     print(e)
+
+#======================= 异常的其他结构 =========================#
+
+# x = 'xdc'
+# try:
+#     int(x)
+# except Exception as e:
+#     print(e)
+# else:
+#     print("try内代码块内没有异常则执行我")
+# finally:
+#     print("无论异常与否,都会执行此模块,通常进行清理工作")
+
+#======================= 主动抛出异常 =========================#
+
+# inp = input("-->>:")
+# if inp.isdigit():   # 方法检测字符串是否只由数字组成。
+#     int(inp)
+# else:
+#     raise TypeError('类型错误,不和你玩了')
+
+
+
+
+
+
+
+
+
+
+

+ 29 - 0
python_base/day15/执行远程主机命令.py

@@ -0,0 +1,29 @@
+# -*- coding: UTF-8 -*-
+
+import paramiko
+import re
+from time import sleep
+
+key_file = paramiko.RSAKey.from_private_key_file("/root/.ssh/id_rsa")
+
+def ssh():
+    ssh = paramiko.SSHClient()
+    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())    #指定当对方主机没有本机公钥的情况时应该怎么办,AutoAddPolicy表示自动在对方主机保存下本机的秘钥
+    ssh.connect(hostname='a.xdc.ink',
+                port=22,
+                username='root',
+                # pkey=key_file, # 使用密钥方式登陆
+                password='cstorfs')    #SSH端口默认22,可改
+                
+    stdin,stdout,stderr = ssh.exec_command("df -P")    #这三个得到的都是类文件对象
+    outmsg,errmsg = stdout.read(),stderr.read()    #读一次之后,stdout和stderr里就没有内容了,所以一定要用变量把它们带的信息给保存下来,否则read一次之后就没有了
+    #outmsg = str(outmsg)
+    #print(outmsg.replace("\\n","\\r\\n"))
+    print(outmsg.decode())
+    print(errmsg)
+    if errmsg == "":
+        print(outmsg)
+    ssh.close()
+
+if __name__ == '__main__':
+    ssh()

+ 103 - 0
python_base/day15/日志模块.py

@@ -0,0 +1,103 @@
+# -*- coding: UTF-8 -*-
+
+import logging
+# logging.info('老弟,来了')   # 不打印,info级别
+# logging.warning('来错地方来') # 输出屏幕,警告级别
+
+logging.basicConfig(filename='myapp.log',level=logging.INFO)
+logging.info('info msg')   
+logging.warning('WR msg') 
+logging.debug('DUG msg')
+
+#======================= 示例 =========================#
+# -*- encoding:utf-8 -*-
+import logging
+
+# create logger
+logger_name = "example"
+logger = logging.getLogger(logger_name)
+logger.setLevel(logging.DEBUG)
+
+# create file handler
+log_path = "./log.log"
+fh = logging.FileHandler(log_path)
+fh.setLevel(logging.WARN)
+
+# create formatter
+fmt = "%(asctime)-15s %(levelname)s %(filename)s %(lineno)d %(process)d %(message)s"
+datefmt = "%a %d %b %Y %H:%M:%S"
+formatter = logging.Formatter(fmt, datefmt)
+
+# add handler and formatter to logger
+fh.setFormatter(formatter)
+logger.addHandler(fh)
+
+# print log info
+logger.debug('debug message')
+logger.info('info message')
+logger.warn('warn message')
+logger.error('error message')
+logger.critical('critical message')
+
+"""
+##### 文件配置
+配置文件logging.conf如下:
+```[loggers]
+keys=root,example01
+
+[logger_root]
+level=DEBUG
+handlers=hand01,hand02
+
+[logger_example01]
+handlers=hand01,hand02
+qualname=example01
+propagate=0
+
+[handlers]
+keys=hand01,hand02
+
+[handler_hand01]
+class=StreamHandler
+level=INFO
+formatter=form02
+args=(sys.stderr,)
+
+[handler_hand02]
+class=FileHandler
+level=DEBUG
+formatter=form01
+args=('log.log', 'a')
+
+[formatters]
+keys=form01,form02
+
+[formatter_form01]
+format=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s```
+
+使用程序logger.py如下:
+```#!/usr/bin/python
+# -*- encoding:utf-8 -*-
+import logging
+import logging.config
+
+logging.config.fileConfig("./logging.conf")
+
+# create logger
+logger_name = "example"
+logger = logging.getLogger(logger_name)
+
+logger.debug('debug message')
+logger.info('info message')
+logger.warn('warn message')
+logger.error('error message')
+logger.critical('critical message')
+"""
+
+##### 字典配置
+# 有兴趣的童靴可以使用```logging.config.dictConfig(config)```编写一个示例程序发给我,以提供给我进行完善本文。
+
+##### 监听配置
+# 有兴趣的童靴可以使用```logging.config.listen(port=DEFAULT_LOGGING_CONFIG_PORT)```编写一个示例程序发给我,以提供给我进行完善本文。
+
+# 更多详细内容参考[logging.config日志配置](http://python.usyiyi.cn/python_278/library/logging.config.html#module-logging.config)

+ 13 - 0
python_base/day15/生产环境异常处理.py

@@ -0,0 +1,13 @@
+# -*- coding: UTF-8 -*-
+import traceback
+
+print('start ----> ')
+try:
+    1 + 'a'
+except TypeError as e:
+    print(e)   # 只是抛出异常
+    print("*" * 20)
+    print(traceback.format_exc())  # 打印详细报错位置
+    print("*" * 20)
+print("<---- end ")
+

+ 56 - 0
python_base/day16/可迭代对象和迭代器.py

@@ -0,0 +1,56 @@
+# -*- coding: UTF-8 -*-
+
+# 迭代器(iterator)
+
+l2 = [1,2,3]
+"__iter__" in dir(l2) # 可迭代对象
+l2_iter = iter(l2)   
+l2_iter.__next__() # 迭代器
+
+# import dis
+# li = [1,2]
+# dis.dis("for i in li: print(i)")  # 
+
+"""
+什么是迭代器,它是一个带状态的对象,他能在你调用next()方法的时候返回容器中的下一个值,
+任何实现类__iter__ 和 __next__() ( python2中实现next() )方法的对象都是迭代器,
+__iter__ 返回迭代器自身,__next__返回容器中的下一个值,如果容器中没有更多元素类,
+则会抛出 StopIteration 异常
+
+==============================================
+
+迭代器有一个内部状态的字段,用于记录下次迭代返回的结果,
+它实现了 __next__ 和 __iter__ 方法,
+迭代器不会一次性把所有的元素加载到内存,而是需要的时候才生成,并返回结果
+"""
+
+#======================= 示例 =========================#
+# 迭代器对象可以使用常规for语句进行遍历:
+
+# 实例(Python 3.0+)
+#!/usr/bin/python3
+ 
+list=[1,2,3,4]
+it = iter(list)    # 创建迭代器对象
+for x in it:
+    print (x, end=" ")
+
+#======================= 使用 next()  =========================#
+#!/usr/bin/python3
+ 
+import sys         # 引入 sys 模块
+ 
+list=[1,2,3,4]
+it = iter(list)    # 创建迭代器对象
+ 
+while True:
+    try:
+        print (next(it))
+    except StopIteration:
+        sys.exit()
+
+# 生成器
+def gen_fun():
+    yield from range(5)
+
+gen_fun()

+ 55 - 0
python_base/day16/抽象类.py

@@ -0,0 +1,55 @@
+# -*- coding: UTF-8 -*-
+
+#======================= 概念 =========================#
+
+"""
+抽象类是一个特殊的类,它的特殊之处在于只能被继承,不能被实例化
+
+"""
+
+
+#======================= 借助 abc模块实现抽象类 =========================#
+import abc  # 利用 abc 模块实现抽象类
+
+class Allfile(metaclass=abc.ABCMeta):
+    all_type = 'file'
+    @abc.abstractmethod     # 定义抽象方法,无需实现功能
+    def read(self):
+        '子类必须重写读功能'
+        pass
+
+    @abc.abstractmethod     # 定义抽象方法,无需实现功能
+    def write(self):
+        '子类必须重写读功能'
+        pass
+
+class Txt(Allfile):
+    pass
+
+t1 = Txt() # 报错,子类没有定义抽象方法
+
+
+class Txt1(Allfile):
+    def read(self):
+        print('已经在子类中重写了 read 方法 ')
+    
+    def write(self):
+        print('已经在子类中重写了 write 方法 ')
+
+t2 = Txt1() 
+t2.read()
+
+
+#======================= 简单实现方式 =========================#
+
+class Base():
+    def read(self):
+        raise NotImplementedError(".read method 方法必须被重写")
+
+class A(Base):
+    pass
+
+obj = A()  # 不报错
+
+obj.read() # 调用方法就报错
+

+ 21 - 0
python_base/day16/生成器.py

@@ -0,0 +1,21 @@
+# -*- coding: UTF-8 -*-
+
+"""
+在 Python 中,使用了 yield 的函数被称为生成器(generator)。
+跟普通函数不同的是,生成器是一个返回迭代器的函数,只能用于迭代操作,更简单点理解生成器就是一个迭代器。
+在调用生成器运行的过程中,每次遇到 yield 时函数会暂停并保存当前所有的运行信息,
+返回 yield 的值, 并在下一次执行 next() 方法时从当前位置继续运行。
+调用一个生成器函数,返回的是一个迭代器对象
+
+
+"""
+
+def demo():
+    for i in range(4):
+        yield i
+
+g = demo()
+g1 = (i for i in g)
+g2 = (i for i in g1)
+print(list(g1))
+print(list(g2))

+ 11 - 0
python_base/day3/test.py

@@ -0,0 +1,11 @@
+# -*- coding: UTF-8 -*-
+ 
+# Filename : test.py
+# author by : www.runoob.com
+ 
+# 九九乘法表
+for i in range(1, 10):
+    for j in range(1, i+1):
+        print('%dx%d=%d' %(j, i, i*j), end=' ')
+    print("")
+

+ 29 - 0
python_base/day3/元组.py

@@ -0,0 +1,29 @@
+# -*- coding: UTF-8 -*-
+t1 = (1)
+t2 = 2,
+
+print(type(t1),type(t2))
+
+t4 = (1,2,[2,3],{'a':1})
+print(t4[2])
+print(id(t4[2]))
+t4[2].append('a')   #元组的id不会改变,但是对象变了
+print(t4)
+print(id(t4[2]))
+
+dl = [1,2,3,[4,5,6]]
+dl2 = tuple(dl)   #列表变为元组
+print(type(dl2))
+
+t5 = (1,2,3,['a','b'])
+print(t5[3])
+t5[3][0]=0
+print(t5[3])
+# 使用元组的理由
+"""
+1、占用空间小
+2、元组内的值不会被意外的修改
+3、可作为字典的键
+4、函数的参数是以元组的形式传递的
+5、命名元组有时候可以代理类的对象(面向对象的时候将)
+"""

+ 49 - 0
python_base/day3/列表.py

@@ -0,0 +1,49 @@
+# -*- coding: UTF-8 -*-
+li = [5, 4, 3, 2, 1]
+li.append('a')
+# print(li)
+print('a' in li)
+li.insert(2, 'HHH')     #索引号之后插入
+print(li)
+
+li2 = ['append','insert','extend']
+li.extend(li2)  # 把另外一个列表添加进去
+print(li)
+
+v = li.pop()
+v2 = li.pop(2) #索引号
+print(v)
+print(li)
+
+idx = li.index('a')     #返回索引号
+print(idx)
+li.pop(li.index('a'))
+print(li)
+
+print('-'.join(['1','2']))  #字符串的拼接
+print(li.count(1))
+
+li5 = [1,33,4,753,76]
+# li5.sort()      #正向排序
+# li5.sort(reversed=True)     #逆向排序
+print(li5)
+
+li6 = sorted(li5, reverse=True) #排序,返回一个对象
+print(li6)
+
+"""
+a = [1, 23, '14']
+b = a
+b[1]=0      # 会覆盖原有的值
+print(a)    # 会覆盖原有的值
+"""
+
+l1 = [1, 'a']
+# l2 = l1.copy()
+l3 = list(l1) 
+l4 = l1[:]
+### 深浅拷贝
+print(id(l1))
+# print(id(l2))
+print(id(l3))
+print(id(l4))

+ 23 - 0
python_base/day3/文件操作.py

@@ -0,0 +1,23 @@
+# -*- coding: UTF-8 -*-
+import sys
+file = '/Users/xc/Desktop/rules.sh'
+# f = open(file, 'r', encoding='utf-8')
+
+'''
+# 读取全部
+f = open(file, 'r')
+all_content = f.read()
+f.close()
+print(all_content)
+'''
+
+with open(file, 'r') as f:
+    # print(f.readline()) #读取一行
+    # print(f.readline())
+    # print(f.readlines()) #读取全部行,返回列表
+    # 循环文件对象
+    for line in f:
+        if 'yes' in line:  #寻找有yes的行
+            # print(line)
+            print(line[-21:-1])
+            # print(line.split(' '))

+ 54 - 0
python_base/day4/cpu_info.txt

@@ -0,0 +1,54 @@
+processor	: 0
+vendor_id	: GenuineIntel
+cpu family	: 6
+model		: 85
+model name	: Intel(R) Xeon(R) Platinum 8175M CPU @ 2.50GHz
+stepping	: 4
+microcode	: 0x2000069
+cpu MHz		: 2499.998
+cache size	: 33792 KB
+physical id	: 0
+siblings	: 2
+core id		: 0
+cpu cores	: 1
+apicid		: 0
+initial apicid	: 0
+fpu		: yes
+fpu_exception	: yes
+cpuid level	: 13
+wp		: yes
+flags		: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single pti fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm mpx avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves ida arat pku ospke
+bugs		: cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds swapgs taa itlb_multihit
+bogomips	: 4999.99
+clflush size	: 64
+cache_alignment	: 64
+address sizes	: 46 bits physical, 48 bits virtual
+power management:
+
+processor	: 1
+vendor_id	: GenuineIntel
+cpu family	: 6
+model		: 85
+model name	: Intel(R) Xeon(R) Platinum 8175M CPU @ 2.50GHz
+stepping	: 4
+microcode	: 0x2000069
+cpu MHz		: 2499.998
+cache size	: 33792 KB
+physical id	: 0
+siblings	: 2
+core id		: 0
+cpu cores	: 1
+apicid		: 1
+initial apicid	: 1
+fpu		: yes
+fpu_exception	: yes
+cpuid level	: 13
+wp		: yes
+flags		: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single pti fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm mpx avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves ida arat pku ospke
+bugs		: cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds swapgs taa itlb_multihit
+bogomips	: 4999.99
+clflush size	: 64
+cache_alignment	: 64
+address sizes	: 46 bits physical, 48 bits virtual
+power management:
+

+ 1 - 0
python_base/day4/tempCodeRunnerFile.py

@@ -0,0 +1 @@
+# -*- coding: UTF-8 -*-

+ 70 - 0
python_base/day4/作业讲解.py

@@ -0,0 +1,70 @@
+ # -*- coding: UTF-8 -*-
+ # 分组程序
+import random
+users = [
+    '陈楚生', '付辛博', '井柏然', '乔任梁',
+    '俞灏明', '王栎鑫', '张殿菲', '刘洲成',
+    '王铮亮', '周路明', '关启祥', '蔡思涛', 'xdc'
+]
+"""
+ 1、每两个人为一组
+    随机抽取2个人
+    user_list = random.sample(users,2)
+    users.remove(user_list[0])
+    users.remove(user_list[1])
+2、停止循环条件,就是 users 为空
+while users:
+    user_list = random.sample(users,2)
+    users.remove(user_list[0])
+    users.remove(user_list[1])
+3、保存已经分组的成员
+使用列表
+usres_group = []
+while users:
+    user_list = random.sample(users,2)
+    users_group.appned(user_list)
+    users.remove(user_list[0])
+    users.remove(user_list[1])
+for group_name in users_group:
+    print(group_name)
+4、假设人数不被2整除
+tag = False
+if len(users) %2 != 0:
+    tag = True
+if tag:
+    user_list = random.sample(users,3)
+    users_group.append(user_list)
+    users.remove(user_list[0])
+    users.remove(user_list[1])
+    users.remove(user_list[2])
+"""
+
+# users_group = []
+
+# tag = False
+# if len(users) %2 != 0:
+#     tag = True
+# if tag:
+#     user_list = random.sample(users,3)
+#     users_group.append(user_list)
+#     users.remove(user_list[0])
+#     users.remove(user_list[1])
+#     users.remove(user_list[2])
+
+# while users:
+#     user_list = random.sample(users,2)
+#     users_group.append(user_list)
+#     users.remove(user_list[0])
+#     users.remove(user_list[1])
+# for group_name in users_group:
+#     print(group_name)
+
+###============获取CPU信息============### 
+file = './day4/cpu_info.txt'
+with open(file, 'r') as f:
+    for line in f:
+        if "model name" in line:
+            print(line)
+            cpu_info_line = line.split(':')[1].strip()
+            cpu_info = '_'.join(cpu_info_line.split())
+            print(cpu_info)

+ 20 - 0
python_base/day4/字典.py

@@ -0,0 +1,20 @@
+# -*- coding: UTF-8 -*-
+
+print(hash(1))
+print(hash(1.1))
+print(hash('1'))
+print(hash(True))
+print(hash(False))
+print(hash((1,)))  #元组
+
+d1 = {
+    1:'整形',       ###key在字典中必须唯一,(hash值唯一)
+    1.1:'float',
+    True:'bool',     ###hash值为1,这种情况是字典中的key不唯一了。
+    (3, ): '元组'
+    }
+    
+print(d1)
+
+list7 = ['hello', 'xdc']
+print(list7[True])   #hash值为‘1’,所以索引值是1

+ 118 - 0
python_base/day4/字典高级操作.py

@@ -0,0 +1,118 @@
+# -*- coding: UTF-8 -*-
+
+###============更新字典============### 
+# d1 = {}
+# d1['a'] = 1
+# d1['b'] = 2
+# d1['li'] = [1,2,3]
+# print(d1)
+# d1['info'] = {'name':'xdc'}
+# print(d1)
+# d1['b'] = 200
+# print(d1)
+# print(    d1['li'][-1]       )
+# print(    d1['info']['name']    )
+###============将两个列表对应成一个字典============### 
+# en = {'a', 'b'}
+# nums = {1, 2}
+# d2 = {}
+# for x,y in zip(en,nums):
+#     d2[x] = y
+# print(d2)
+
+# menus = ['get CPU', 'men']
+
+# for idx, item in enumerate(menus,1):   ###自动增加索引值(以1开始)
+#     print(idx, item)
+
+# menu_dice = {}
+# for idx,item in enumerate(menus,1):
+#     menu_dice[str(idx)] = item
+# print(menu_dice)
+# for k,v in menu_dice.items():  #字典本身不是可迭代对象,items才是
+#     print(k,v)
+# print( )
+# inp = input(">>:")
+#print(menu_dice.get(inp))
+###============获取字典Key对应的Value============###   
+# dict_obj = {'a': '1','b':'2'}
+# print(dict_obj.get('a')) # 获取到 a 对应的value
+# print(dict_obj.get('c')) # key不存在于字典中,则返回None
+# print(dict_obj.get('c','key不存在')) #key 不存在,返回指定的value
+# getKey = dict_obj.get('c')
+# print(type(getKey),getKey)
+
+###============获取字典中所有的key和Value============### 
+info_dict = {"name":"xdc","age":8848}
+# d_keys = info_dict.keys()
+# print(d_keys)
+# print(list(d_keys))
+
+print(info_dict.values())  # 这里与python2不一致
+print(info_dict.items())   # 这里与python2不一致
+for k,v in info_dict.items():
+    print(k,v)
+
+###============更新字典============### 
+
+# d5 = {'a':1}
+# d6 = {'b':2}
+# d5.update(d6)
+# print(d5)
+# d5.update(c=3,d=10)
+# print(d5)
+# #更新时,相同的key会被新的值覆盖
+
+# x = {'a':1, 'b':2}
+# y = {'c':1, 'd':2}
+# z = {**x,**y} # 合并字典操作(python 3.5+版本支持)
+# print(z)
+
+###============判断字典 key 与 Valye  ============### 
+# x = {'a':1, 'b':2}
+# print('a' in x.keys())
+# print(2 in x.values())
+
+###============删除字典与清空============###
+# dict_obj = {'a':1}
+# del dict_obj['a']
+# print(id(dict_obj))
+# dict_obj = {}
+# print(id(dict_obj))
+# dict_obj.clear()
+
+# d6 = {'a':1,'b':2,'li':[1,2,3]}
+# item = d6.pop('b') #从字典中删除指定key的键值对,并返回这个key对应对值
+# print(item)
+
+# d6 = {'a':1,'b':2,'li':[1,2,3]}
+# item = d6.popitem() # 删除字典中的键值对,并返回这个键和值 (默认删除最后一个键值对)
+# print(item)
+
+###============字典可迭代对象============###
+# en = ['a','b','c','d']
+# nums = ['1','2','3','4']
+
+# zip_obj = zip(en,nums)
+# print(zip_obj)
+# print(list(zip_obj))
+# print(dict(zip_obj))
+
+# l3 = [('a', '1'), ('b', '2'), ('c', '3'), ('d', '4')]
+# for item in l3:
+#     print(item)
+#     w,n = item
+#     print(w,n)
+# for w,n in l3:
+#     print(w,n)
+
+# t3 = ('a1','b2')
+# for w,n in t3:
+#     # print(w,"->", n)
+#     s = f"{w}-->{n}" 
+#     print(s)
+
+
+
+
+

+ 4 - 0
python_base/day5/test.txt

@@ -0,0 +1,4 @@
+word
+word
+word
+word

+ 64 - 0
python_base/day5/字典.py

@@ -0,0 +1,64 @@
+# -*- coding: UTF-8 -*-
+
+# while 1:
+#     arg = input("-->>").strip()
+
+#     data = {
+#         '0' : 'zero' ,
+#         '1' : 'one' ,
+#         '0' : 'two' 
+#     }
+#     print(data.get(arg, "noting"))
+
+
+# arg = 'list'
+# d_map = {
+#     'list' : list
+# }
+
+# li = d_map[arg]('abc')
+# print(li)
+
+###============扩展知识,setdefault 处理缺失的数据============### 
+
+# d = {}
+# d.setdefault('a')   #  不存在key的话,创建这个key, value为 None
+# d.setdefault('a','hello')  # key已经存在,返回key对应的value值
+# d.setdefault('b','hello')  # key不存在,生产key和value,并返回value的值
+# d.setdefault('c',[1, 2])  #也可以生产列表
+# print(d)
+
+# data = [
+#     ("ip", "192.168.1.100"),
+#     ("ip", "192.168.1.100"),
+#     ("port", 22),
+#     ("user", "yl"),
+#     ("user", 'xdc')
+# ]
+
+# d1 = {}
+# for item in data:
+#     d1.setdefault(item[0], []).append(item[1])
+#     print(d1)
+
+
+# s = set()  #设置集合
+# s = {1,234, 'hello',True}
+# print(type(s))
+# print(s)
+
+# s2 = { 1, 3, [2,4]} 
+# print(type(s2))
+# print(s2)
+
+s1 = {"192.168.1.51","192.168.1.45"}
+s2 = {"192.168.1.51","192.168.1.78"}
+print(type(s1))
+s1.union(s2)  #合并两个集合,重复的删除 (并集)
+s1 & s2 # 比较两个集合的相同值(交集)
+s1 | s2 # 并集
+s1 - s2 # 差集(s1独有的)
+s2 - s1 # 差集(s2独有的)
+s1 ^ s2 # 异或集
+
+

+ 36 - 0
python_base/day5/文件操作.py

@@ -0,0 +1,36 @@
+# -*- coding: UTF-8 -*-
+
+file_full = '/Users/xc/git-python/day5/test.txt'
+enter = '\n'
+
+###============读文件============### 
+# with open(file_full , 'r') as f:
+#     line = f.readline()
+#     print(line)
+#     f.seek(0)  #文件内部光标位置指定
+
+
+###============写文件============### 
+# with open(file_full , 'w', encoding='utf-8') as f:  # (w) 写模式
+#     f.write(f'hello{enter}')
+#     f.write(f'hello{enter}')
+
+###============文件内容追加============###
+# with open(file_full , 'a', encoding='utf-8') as f:  # (a) 增加模式
+#     f.write(f'hello{enter}')
+#     f.write(f'hello{enter}')
+
+###============文件拷贝与内容替换============### 
+wf = file_full.replace('test.txt', 'test.txt.swap') # 拷贝文件,(1 ,2) 1是原文件,2是修改后的文件名
+with open(
+    file_full, 'r', encoding='utf-8') as rf_obj, open(
+        wf, 'w',encoding='utf-8') as wf_obj:
+        # 括号中可以换行,不影响
+    for line in rf_obj:
+        ll = line.replace('hello', 'word') #字符串替换,如果 (1,2)不存在,返回原来的值。2为替换后的值
+        wf_obj.write(ll)
+
+import os
+os.remove(file_full)
+os.rename(wf,file_full)
+# 上面代码与 vim 编辑器功能类似

+ 1 - 0
python_base/day6/tempCodeRunnerFile.py

@@ -0,0 +1 @@
+

Неке датотеке нису приказане због велике количине промена