RedPlug's Tory

밥집 추천 슬랙 봇

  • 사전에 봇 등록하여 토큰발급과 event Subscriptions 등록 필요.
  • 플라스크를 이용하여 봇에게 멘션이 들어올 경우 밥집을 랜덤하게 리턴해주는 코드

 

# -*- coding: utf-8 -*-

import json

from slacker import Slacker

from flask import Flask, request, make_response

import random

## 슬랙 봇 토큰 ## 
token  = "슬랙봇 토큰"

slack = Slacker(token)

app = Flask(__name__)

def get_answer():
    food = ['밥집1','밥집2','밥집3']
    random.shuffle(food)
    return food


# 이벤트 핸들하는 함수

def event_handler(event_type, slack_event):

    if event_type == "app_mention":

        channel = slack_event["event"]["channel"]

        text = get_answer()

        slack.chat.post_message(channel, "오늘의 밥집 추천은 {text[0]} 입니다")

        return make_response("앱 멘션 메시지가 보내졌습니다.", 200, )

    message = "[%s] 이벤트 핸들러를 찾을 수 없습니다." % event_type

    return make_response(message, 200, {"X-Slack-No-Retry": 1})



@app.route("/slack", methods=["GET", "POST"])

def hears():

    slack_event = json.loads(request.data)

    if "challenge" in slack_event:

        return make_response(slack_event["challenge"], 200, {"content_type": "application/json"})

    if "event" in slack_event:

        event_type = slack_event["event"]["type"]

        return event_handler(event_type, slack_event)

    return make_response("슬랙 요청에 이벤트가 없습니다.", 404, {"X-Slack-No-Retry": 1})



if __name__ == '__main__':

    app.run('0.0.0.0', port=8080)

 

 

latest 변수와 latest.txt파일에 제목을 비교해서 동일한 값이 아닐 경우 새글이 올라왔어요 + 글제목 + 링크를 함께 텔레그렘 봇이 보내주는 코드

텔레그램 봇 사진 발급 필요.

requests, bs4, telegram봇 모듈 설치 필요.

새글이 있을 경우 텔레그램 봇이 뿌려줌

반복은 crontab을 통해서 원하는 기간별로 진행

#tigpnd.py
# -*- coding: utf-8 -*-

import requests
from bs4 import BeautifulSoup
import os
import time

import telegram


bot = telegram.Bot(token='텔레그램봇토큰')
chat_id = bot.getUpdates()[-1].message.chat.id

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
req = requests.get('https://www.thisisgame.com/pad/tboard/?board=25')
html = req.text
soup = BeautifulSoup(html, 'html.parser')
posts = soup.select('td > a')
latest = posts[14].text
href = posts[14].get('href')
url = 'https://www.thisisgame.com/pad/tboard/'
link = url + str(href)
with open(os.path.join(BASE_DIR, 'latest.txt'), 'r+') as f_read:
    before = f_read.readline()
    if before != latest:
        bot.sendMessage(chat_id=chat_id, text='새 글이 올라왔어요! : ' + latest + link)
    f_read.close()

with open(os.path.join(BASE_DIR, 'latest.txt'), 'w+') as f_write:
    f_write.write(latest)
    print(latest)
    f_write.close()

CentOS7 설치 후 ifconfig 시 command not found가 뜰 경우

yum install net-tools

인터넷 불가 시

ip addr 또는 ip link로 확인 가능

Linux 버젼 확인

Linux2020. 7. 29. 20:40
  • 커널 정보
uname -a
  • OS 버젼 1
cat /etc/issue
  • OS 버젼 2
cat /etc/redhat-release
  • OS 버젼 3
cat /etc/*release*

OS bit

getconf LONG_BIT

대상서버 TCP 389 Port Open 필요

1. RSAT 설치

2. runas /u:redplug\admin /netonly "mmc %windir%\system32\dsa.msc /server=IP or DNS"

패스워드 입력

도커 스크립트 다운로드

pi@raspi:~ $ curl -fsSL get.docker.com -o get-docker.sh
pi@raspi:~ $ curl -fsSL get.docker.com -o test-docker.sh

 

도커 설치(test-docker.sh)

pi@raspi:~ $ bash test-docker.sh
# Executing docker install script, commit: 26ff363bcf3b3f5a00498ac43694bf1c7d9ce16c
+ sudo -E sh -c 'apt-get update -qq >/dev/null'
+ sudo -E sh -c 'DEBIAN_FRONTEND=noninteractive apt-get install -y -qq apt-transport-https ca-certificates curl >/dev/null'
+ sudo -E sh -c 'curl -fsSL "https://download.docker.com/linux/raspbian/gpg" | apt-key add -qq - >/dev/null'
Warning: apt-key output should not be parsed (stdout is not a terminal)
+ sudo -E sh -c 'echo "deb [arch=armhf] https://download.docker.com/linux/raspbian buster stable" > /etc/apt/sources.list.d/docker.list'
+ sudo -E sh -c 'apt-get update -qq >/dev/null'
+ '[' -n '' ']'
+ sudo -E sh -c 'apt-get install -y -qq --no-install-recommends docker-ce >/dev/null'
+ sudo -E sh -c 'docker version'
Client: Docker Engine - Community
 Version:           19.03.12
 API version:       1.40
 Go version:        go1.13.10
 Git commit:        48a6621
 Built:             Mon Jun 22 15:53:41 2020
 OS/Arch:           linux/arm
 Experimental:      false

Server: Docker Engine - Community
 Engine:
  Version:          19.03.12
  API version:      1.40 (minimum version 1.12)
  Go version:       go1.13.10
  Git commit:       48a6621
  Built:            Mon Jun 22 15:47:34 2020
  OS/Arch:          linux/arm
  Experimental:     false
 containerd:
  Version:          1.2.13
  GitCommit:        7ad184331fa3e55e52b890ea95e65ba581ae3429
 runc:
  Version:          1.0.0-rc10
  GitCommit:        dc9208a3303feef5b3839f4323d9beb36df0a9dd
 docker-init:
  Version:          0.18.0
  GitCommit:        fec3683
If you would like to use Docker as a non-root user, you should now consider
adding your user to the "docker" group with something like:

  sudo usermod -aG docker pi

Remember that you will have to log out and back in for this to take effect!

WARNING: Adding a user to the "docker" group will grant the ability to run
         containers which can be used to obtain root privileges on the
         docker host.
         Refer to https://docs.docker.com/engine/security/security/#docker-daemon-attack-surface
         for more information.

 

구동확인

pi@raspi:~ $ ps auwx|grep docker
root     15755  3.4  1.3 971312 54552 ?        Ssl  11:58   0:00 /usr/bin/docker d -H fd:// --containerd=/run/containerd/containerd.sock
pi       16826  0.0  0.0   4168   480 pts/0    S+   11:58   0:00 grep --color=auto docker

 

일반 사용자 계정 도커 그룹에 넣기

pi@raspi:~ $ sudo usermod -aG docker pi

 

hello-world 도커 실행

pi@raspi:~ $ docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
4ee5c797bcd7: Pull complete
Digest: sha256:d58e752213a51785838f9eed2b7a498ffa1cb3aa7f946dda11af39286c3db9a9
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (arm32v7)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.

To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash

Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/

For more examples and ideas, visit:
 https://docs.docker.com/get-started/

전체 사용자 사서함 폴더 수 확인
get-mailbox -RecipientTypeDetails usermailbox -ResultSize unlimited | Get-mailboxFolderStatistics -FolderScope Inbox | Group
Inbox, 현재 보이는 사용자 사서함 기준 전체 폴더 수량
get-mailbox -RecipientTypeDetails usermailbox -ResultSize unlimited  | Where {$_.HiddenFromAddressListsEnabled -eq $False} | Get-mailboxFolderStatistics -FolderScope Inbox | Group
사용자별 사서함 폴더 카운트
$Mailboxes = Get-Mailbox

$Results = foreach( $Mailbox in $Mailboxes ){
    $Folders = $MailBox |
        Get-MailboxFolderStatistics |
        Measure-Object |
        Select-Object -ExpandProperty Count

    New-Object -TypeName PSCustomObject -Property @{
        Username    = $Mailbox.Alias
        FolderCount = $Folders
        }
    }

$Results |
    Select-Object -Property Username, FolderCount
출처 : https://community.spiceworks.com/topic/1824271-use-get-mailboxfolderstatistics-to-get-total-folder-count

Enterprise Vault 백업 진행 시 VaultStore와 Index를 BackupMode로 변경한 후에 다시 원복진행을 하여야 합니다만

버그인지 간혹 돌아오지 않는 경우가 있어 BackupMode체크할 수 있도록 만든 스크립트 입니다.

Import-Module EnterpriseVault
$EVServers = "ev1","ev2"
#Set Mailing parameters
$sendMailMessageParams = @{
    Smtpserver = "mail.redplug.com"
    To         = "redplug@redplug.com"
    From       = "noreply@redplug.com"
}

# HTML Body 
$head = "" | Out-String
$VSName = "VSName"
$EVServerName = "EVServerName"
$Queue = get-vaultstorebackupmode -Name $VSName -EVServerName $EVServerName -EvObjectType vaultstoregroup | where-object {$_.BackupMode -eq $True} | Select @{N=’Name’; E={$_.VaultStoreName}},@{N=’ID’; E={$_.VaultStoreEntryId}}, BackupMode
$Queue2 = foreach ($EVServer in $Evservers) {get-indexlocationbackupmode -EVServerName $EVServer | where-object {$_.BackupMode -eq $True} | Select @{N=’Name’; E={$_.IndexRootPath}},@{N=’ID’; E={$_.IndexingServiceId}},BackupMode}

if (($Queue -eq $Null) -and ($Queue2 -eq $Null)) {
Send-MailMessage -Subject "Enterprise Vault BackupMode Alert" -Body "All Backup Mode False" -BodyAsHtml @sendMailMessageParams
}else {
## 백업모드가 실패가 아닐 경우 중요도 높음 설정 및 리스트 표기
$body = $Queue + $Queue2 | ConvertTo-Html -Head $head | Out-String
Send-MailMessage -Subject "Enterprise Vault BackupMode Alert" -Priority High -Body $body -BodyAsHtml @sendMailMessageParams
}

 

해당스크립트를 Task로 등록할 경우 x86 Powershell로 등록하여야 하기 때문에 프로그램 주소를 하기로 설정 필요

%SystemRoot%\syswow64\WindowsPowerShell\v1.0\powershell.exe

백업모드에 자동으로 원복이 필요할 경우 

 

해당 스크립트 하단에 clear-IndexLocationBackupMode / clear-VaultStoreBackupMode 명령어를 추가하여 원복 가능.

(서버네임 입력 필요)

dir /b /s > list.txt

/b : 가장 우측 정보만 노출

/s : 서브 디렉토리까지 포함하여 노출

> list.txt : 텍스트 파일로 추출

m.2 sata nvme 속도 비교

ETC2019. 12. 4. 10:05

집PC의 SSD를 교체하여서 대략적인 속도 확인을 해보려고 한 비교입니다.


테스트 환경

M/B : GigaByte B150M-DS3H-CF

CPU : INTEL CORE i7-6700

RAM : 16GB

OS : Windows 10


1. GALAX GAMER Heat Sink M.2 2280 240GB (SATA 방식)


2. TEAMGROUP NVMe PCIe M.2 2280 1TB (NVMe)


육안상 갤럭시 모델이 NVMe가 아닌거 같은데 NVMe로 소개하는 글들도 있네요. 

(홈이 2개일 경우 SATA방식)