Freesunny

Slack으로 메시지 보내기

Python

Slack API 에서 bot을 생성한 후에 발급받은 토큰을 통해서 

Slack 으로 메시지를 보내는 방법이다.

from slacker import Slacker

def SendtoSlack(post_channel, post_massage):
  token = 'xoxb-xxxxxxxxxx-yyyyyyyyyyyy-zzzzzzzzzzzzzzzzzzzzzzzz'
  slack = Slacker(token)
  
  slack.chat.post_message(channel=post_channel, text=post_massage)
  
if __name__ == '__main__':
  result = SendtoSlack('#bot-test', 'slockbot test')

 

 

다른 파일에서 사용가능하다.

from SendtoSlack import SendtoSlack

SendtoSlack('#bot-test', 'slockbot test')

'Python' 카테고리의 다른 글

파일을 읽어 줄 단위로 배열에 입력  (0) 2019.07.16
함수 정의 및 인자 받기  (0) 2019.07.15

파일을 읽어 줄 단위로 배열에 입력

Python

파일을 읽어서 배열에 넣어주는 방법이다.

./files/checkfile.txt 의 내용을 줄단위로 배열에 입력하여,

contents 와 동일한 내용이 있는지 확인하여 동일한 내용이 있으면 1 을  리턴한다.
문자열 비교시 배열에 newline("\n")이 추가있는 것을, .rstrip 으로 제거하였다. 

def Check_FileContentsMatch(inputfile, querystring):
  result = 0
  
  with open(inputfile) as data:
    lines = data.readlines()
  
  for string in lines:
    if querystring == string.rstrip('\n'):
      result = 1
  
  return result
 
if __name__ == '__main__':
  result = Check_FileContentsMatch('./files/checkfile.txt', 'contents')
  print(result)

'Python' 카테고리의 다른 글

Slack으로 메시지 보내기  (0) 2019.07.17
함수 정의 및 인자 받기  (0) 2019.07.15

[Python] credentials 파일 내에 profile 사용하는 방법

AWS

~/.aws/credentials 파일에 여러 개의 profile 이 있을 경우에 profile 을 선택하는 방법이다.

import boto3

def ListEc2InstanceId(profile, region):
	session = boto3.Session(profile_name=profile)
	ec2 = session.resource('ec2', region_name=region)

	for instance in ec2.instances.all():
		print(instance.id, instance.instance_type)

if __name__ == '__main__':
	ListEc2InstanceId('dev', 'ap-northeast-2')

함수 정의 및 인자 받기

Python

함수에서 인자 받는 방법

import boto3

def PrintPublicIp(region):
        ec2 = boto3.resource('ec2', region_name=region)

        instance = ec2.Instance('i-0044abbb3c982cbaa')
        for nia in instance.network_interfaces_attribute:
                publicip = nia.get('Association')
                print(publicip.get('PublicIp'), publicip.get('IpOwnerId'))


if __name__ == '__main__':
        PrintPublicIp('ap-northeast-2')

'Python' 카테고리의 다른 글

Slack으로 메시지 보내기  (0) 2019.07.17
파일을 읽어 줄 단위로 배열에 입력  (0) 2019.07.16

[Python] 미사용 Elastic IP 확인 및 릴리즈

AWS

미사용 Elastic IP 확인 및 릴리즈를 하는 방법

import boto3

client = boto3.client('ec2', region_name='ap-southeast-1')

addresses_dict = client.describe_addresses()
for eip_dict in addresses_dict['Addresses']:
    if "NetworkInterfaceId" not in eip_dict:
        print(eip_dict['PublicIp'])
        client.release_address(AllocationId=eip_dict['AllocationId'])

[Python] EC2 인스턴스의 Public IP 와 Ip Owner ID 확인

AWS

아래의 명령으로 해당 EC2 인스턴스의 public ip 와 ip owner id 를 확인할수 있다.

  

import boto3

ec2 = boto3.resource('ec2', region_name='ap-northeast-2')

instance = ec2.Instance('i-0f129db467cc63be9')

for network in instance.network_interfaces_attribute:
    publicip = network.get('Association')
    print(publicip.get('PublicIp'), publicip.get('IpOwnerId'))

 

IpOwnerId 가 'amazon' 이면 Elastic IP가 아니다.

## 결과 예시 ##

54.180.125.255 amazon

 

IpOwnerId가 AWS Account ID 가 출력되면 Elastic IP 이다.

## 결과 예시 ##

13.124.148.58 552573234252

[Python] 중지되거나 종료된 EC2 인스턴스 ID 와 타입 출력

AWS

필터를 이용하여 중지되거나, 종료된 EC2 인스턴스 ID와 타입을 출력

import boto3

ec2 = boto3.resource('ec2', region_name='ap-northeast-2')

instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['stopped', 'terminated']}])

for instance in instances:
    print(instance.id, instance.instance_type)

 

## 결과 예시 ##

i-0fe63429076e32630 m5.large
i-0dfa1ab52da76ce92 r5.large
i-08aa947cb86193c2d t2.xlarge

[Python] AWS EC2 인스턴스에서 사용하는 EBS 볼륨 출력

AWS

EC2 인스턴스에서 사용하는 EBS 볼륨 ID 출력

import boto3

ec2 = boto3.resource('ec2', region_name='ap-southeast-1')

instance = ec2.Instance('i-062807af2ec003bb6')

for device in instance.block_device_mappings:
    volume = device.get('Ebs')
    print(volume.get('VolumeId'))

 

root 볼륨의 TYPE 출력

print(instance.root_device_type)

 

root 볼륨 디바이스네임 출력

print(instance.root_device_name)