aws 通过boto3 python脚本打pach的实现方法


Posted in Python onMay 10, 2020

脚本要实现的功能:输入instance id

1:将所有的volume take snapshot

2:  获取public ip 并登陆机器执行 ps 命令记录patch前进程状态已经端口状态

3:获取机器所在的elb

4:  从elb中移除当前机器

5:检查snapshots是否完成

6:snapshots完成后patching

7:  patching完成后将instance加回到elb

#!/usr/bin/python
# vim: expandtab:tabstop=4:shiftwidth=4
''' script to get ecr info '''
# Reason: disable invalid-name because pylint does not like our naming convention
# pylint: disable=invalid-name
import time
import boto3
import sys
import argparse
def get_volume(ec2, instanceId):
  result = []
  instance = ec2.Instance(instanceId)
  volumes = instance.volumes.all()
  for volume in volumes:
    print("Volume attached to this instance is :" + volume.id)
    result.append(volume.id)
  return result
def take_snapByInstance(client, instanceId):
  response = client.create_snapshots(
  Description='string',
  InstanceSpecification={
    'InstanceId': instanceId,
    'ExcludeBootVolume': False
  },
  TagSpecifications=[
    {
      'ResourceType': 'snapshot',
      'Tags': [
        {
          'Key': 'orginName',
          'Value': 'patch backup'+ instanceId
        },
      ]
    },
  ],
  DryRun=False,
  CopyTagsFromSource='volume'
  )
  print("Creating new snapshots for instances:" + response['Snapshots'][0]['SnapshotId'])
  return response['Snapshots'][0]['SnapshotId']
def get_publicIp(ec2, instanceId):
  instance = ec2.Instance(instanceId)
  publicIp = instance.public_ip_address
  return publicIp
def take_screenshotOfProcess(public_ip):
  print("Please run this command on your local machine")
  print('ssh -t ' + public_ip + ' "sudo netstat -tnpl > disk.listen"')
  print('ssh -t ' + public_ip + ' "sudo ps auxf > disk.ps"')
def get_elbInfo(client_elb, ec2, instanceId):
  bals = client_elb.describe_load_balancers()
  for elb in bals['LoadBalancerDescriptions']:
    #print('ELB DNS Name : ' + elb['DNSName'])
    #check if the elb is the elb of instance
    if instanceId in elb['Instances']:
      print("found elb " + elb['DNSName'])
    else:
      pass
def remove_fromElb(client_elb, elb, instanceId):
  response = client_elb.deregister_instances_from_load_balancer(
    LoadBalancerName='elb',
    Instances=[
      {
        'InstanceId': instanceId
      },
    ]
  )
def add_backElb(client_elb, elb, instanceId):
  response = client.register_instances_with_load_balancer(
    LoadBalancerName= elb,
    Instances=[
      {
        'InstanceId': instanceId
      },
    ]
  )
def check_snapStatus(ec2, snaps):
  snapshot = ec2.Snapshot(snaps)
  snapshot.load()
  print(snapshot.state)
  return snapshot.state
def main(ec2, client, instanceId, client_elb):
  print("going to paching instanceid: " + instanceId)
  #get volumes
  volumes = get_volume(ec2, instanceId)
  #get public ip
  public_ip = get_publicIp(ec2, instanceId)
  #take snapshot
  snaps = take_snapByInstance(client, instanceId)
  #take screenshot of procss and port
  take_screenshotOfProcess(public_ip)
  #get elb info
  elb = False
  #elb = get_elbInfo(client_elb, ec2, instanceId)
  #remove from elb
  if elb:
    ans_remove = input("Are you sure to remove the instance from the elb now? Yes/No")
    if ans_remove == 'Yes':
    #remove from instance
      remove_fromElb(client_elb, elb, instanceId)
  #check snapshot status
  snapshotStatus = ''
  check_snapStatus(ec2, snaps)
  print("checking staus of snapshots")
  while True:
    snapshotStatus = check_snapStatus(ec2, snaps)
    print(snapshotStatus)
    if snapshotStatus == 'completed':
      break
    else:
      time.sleep(10)
    #paching
  paching_cmd = 'Your paching command'
  print(paching_cmd)
  #add to elb
  if elb:
    ans_add = input("please confirm the patching is over , input yes to continue")
    if ans_add == 'Yes':
      add_backElb(client_elb, elb, instanceId)
if __name__ == "__main__":
  ec2 = boto3.resource('ec2', region_name='us-east-1')
  client = boto3.client('ec2', region_name='us-east-1')
  client_elb = boto3.client('elb', region_name='us-east-1')
  main(ec2, client, 'i-abcasdfa111122', client_elb)

注意,本脚本并未包含链接机器并执行命令的部分,仅仅是打印出命令,需要手动执行 take_screenshotOfProcess 已经patch的命令,此部分也参考之前的文章,完全自动化,不需要手动执行

另外Patch命令脚本中并未给出

总结

到此这篇关于aws 通过boto3 python脚本打pach的实现方法的文章就介绍到这了,更多相关aws 通过boto3 python脚本打pach内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
python进阶教程之模块(module)介绍
Aug 30 Python
将Django使用的数据库从MySQL迁移到PostgreSQL的教程
Apr 11 Python
在Python的Django框架中编写编译函数
Jul 20 Python
举例详解Python中yield生成器的用法
Aug 05 Python
Python实现Linux中的du命令
Jun 12 Python
Python3中类、模块、错误与异常、文件的简易教程
Nov 20 Python
Python实现钉钉发送报警消息的方法
Feb 20 Python
Python函数中参数是传递值还是引用详解
Jul 02 Python
Python Django模板之模板过滤器与自定义模板过滤器示例
Oct 18 Python
tensorflow指定GPU与动态分配GPU memory设置
Feb 03 Python
python使用布隆过滤器的实现示例
Aug 20 Python
matplotlib阶梯图的实现(step())
Mar 02 Python
Django 设置admin后台表和App(应用)为中文名的操作方法
May 10 #Python
基于python实现上传文件到OSS代码实例
May 09 #Python
使用python创建生成动态链接库dll的方法
May 09 #Python
浅析python 动态库m.so.1.0错误问题
May 09 #Python
Python实现常见的几种加密算法(MD5,SHA-1,HMAC,DES/AES,RSA和ECC)
May 09 #Python
Python发送邮件封装实现过程详解
May 09 #Python
pycharm第三方库安装失败的问题及解决经验分享
May 09 #Python
You might like
2019十大人气国漫
2020/03/13 国漫
php中用memcached实现页面防刷新功能
2014/08/19 PHP
Laravel框架用户登陆身份验证实现方法详解
2017/09/14 PHP
PHP常用函数之根据生日计算年龄功能示例
2019/10/21 PHP
YII2框架中日志的配置与使用方法实例分析
2020/03/18 PHP
XML的代替者----JSON
2007/07/21 Javascript
分享一道笔试题[有n个直线最多可以把一个平面分成多少个部分]
2012/10/12 Javascript
基于OO的动画附加插件,可以实现弹跳、渐隐等动画效果 分享
2013/06/24 Javascript
Angularjs制作简单的路由功能demo
2015/04/14 Javascript
javascript格式化指定日期对象的方法
2015/04/21 Javascript
boostrapTable的refresh和refreshOptions区别浅析
2017/01/22 Javascript
详解AngularJS2 Http服务
2017/06/26 Javascript
详解webpack + vue + node 打造单页面(入门篇)
2017/09/23 Javascript
详解vue 数组和对象渲染问题
2018/09/21 Javascript
详解如何更好的使用module vuex
2019/03/27 Javascript
ElementUI radio组件选中小改造
2019/08/12 Javascript
vue-cli 为项目设置别名的方法
2019/10/15 Javascript
JS实现基本的网页计算器功能示例
2020/01/16 Javascript
JS猜数字游戏实例讲解
2020/06/30 Javascript
通过滑动翻页效果实现和移动端click事件问题
2021/01/26 Javascript
[02:28]PWL开团时刻DAY3——Ink Ice与DeMonsTer之间的勾心斗角
2020/11/03 DOTA
Python实现模拟登录及表单提交的方法
2015/07/25 Python
解决python3 urllib 链接中有中文的问题
2018/07/16 Python
PyCharm代码提示忽略大小写设置方法
2018/10/28 Python
python将视频转换为全字符视频
2019/04/26 Python
Python requests模块session代码实例
2020/04/14 Python
Python Mock模块原理及使用方法详解
2020/07/07 Python
使用Python通过oBIX协议访问Niagara数据的示例
2020/12/04 Python
美国知名的百货清仓店:Neiman Marcus Last Call
2016/08/03 全球购物
Expedia英国:全球最大的在线旅游公司
2017/09/07 全球购物
STP协议的主要用途是什么?为什么要用STP
2012/12/20 面试题
教师档案管理制度
2014/01/23 职场文书
《七颗钻石》教学反思
2014/02/28 职场文书
《将心比心》教学反思
2014/04/08 职场文书
Python还能这么玩之用Python做个小游戏的外挂
2021/06/04 Python
GoFrame gredis缓存DoVar Conn连接对象 自动序列化GoFrame gredisDo/DoVar方法Conn连接对象自动序列化/反序列化总结
2022/06/14 Golang