четверг, 22 ноября 2018 г.

Forward messages from channel to channel in Telegram

#!/usr/bin/python3
from telethon.tl.functions.messages import GetDialogsRequest
from telethon.tl.types import InputPeerEmpty
from telethon import TelegramClient
from telethon.tl.functions.messages import AddChatUserRequest
from telethon.tl.functions.messages import ForwardMessagesRequest
from telethon.tl.functions.messages import GetChatsRequest
from telethon.tl.functions.contacts import GetContactsRequest
from telethon.tl.functions.contacts import SearchRequest
from telethon.tl.functions.channels import InviteToChannelRequest
from telethon.tl.functions.channels import GetMessagesRequest
from telethon.tl.functions.users import GetFullUserRequest
from telethon.tl.types import InputChannel
from telethon.tl.types import InputUser
from telethon.tl.types import InputPeerChannel
from telethon.tl.types import InputPeerUser
from telethon.tl.types import UpdateNewChannelMessage
from telethon.tl.types import PeerUser, PeerChat, PeerChannel
from telethon.utils import get_input_peer
import re
import time
import sys

#Put your params here:
#!
api_id =
api_hash = ''
phone_number = ''
#!

client = TelegramClient('r0mkTelephone', api_id, api_hash,  update_workers=0)
channel_from  = sys.argv[1]
channel_to_send = sys.argv[2]

if client.connect():
    print('Connected')
if not client.is_user_authorized():
    client.send_code_request(phone_number)
    myself = client.sign_in(phone_number, input('Enter code: '))

client.updates.polling = True

channel_manual = client.get_entity('t.me/' + channel_from)
print("Channel to: " + str(channel_manual.title))
print("Channel to ID: " + str(channel_manual.id))
print("Channel to Hash: " + str(channel_manual.access_hash))
channel_from_input_peer = InputPeerChannel(channel_manual.id, channel_manual.access_hash)

channel_to = client.get_entity('t.me/' + channel_to_send)
print("Channel to: " + str(channel_to.title))
print("Channel to ID: " + str(channel_to.id))
print("Channel to Hash: " + str(channel_to.access_hash))
channel_to_input_peer = InputPeerChannel(channel_to.id, channel_to.access_hash)

while True:
    update = client.updates.poll()
    if type(update) == UpdateNewChannelMessage and update.message.to_id.channel_id == channel_manual.id:
        print('message id ' + str(update.message.id))
        print('channel id ' + str(update.message.to_id.channel_id))
        #print(update)
        #print(dir(update))
        client.invoke(ForwardMessagesRequest(from_peer=channel_from_input_peer, id=[update.message.id], to_peer=channel_to_input_peer))


        #print(client.invoke(GetMessagesRequest(channel=my_channel_to, id=[update.message.id])))
        #client.invoke(ForwardMessagesRequest(from_peer=my_channel_from, id=[update.message.id], to_peer=my_channel_to))
    else:
        continue

client.add_update_handler(forward)

понедельник, 19 марта 2018 г.

How to install pycharm in Debian stretch


Jet Brains developed well IDE for python. Many professional python coders chose pycharm as main tool for work. Unfortunately PyCharm does not exist in debian main repositories. So there is easy way to install it in 3 commands:

1)Install SNAP package manager, that have pycharm:
#apt-get -y install snapd

2)Install pycharm
#snap install pycharm-community —classic
2018-03-19T08:49:09+04:00 INFO snap "core" has bad plugs or slots: core-support-plug (unknown interface)
pycharm-community 2017.3.4 from 'jetbrains' installed

3)Create symlink to current version
#ln -s /snap/pycharm-community/current/bin/pycharm.sh /bin/pycharm

Thats all. Now you can start it, using #pycharm command

четверг, 18 января 2018 г.

Python3 telnetlib Eltex

This code demonstrates how to communicate with Eltex OLT

#!/usr/bin/python3
import telnetlib

user = ''
password = ''
host = ''

try:
        tn = telnetlib.Telnet(timeout=3)
except:
        sys.exit('Cannot telnet')

tn.open(host)

tn.read_until('gin:'.encode('ascii'))[2]
tn.write(user.encode('ascii') + b"\r")
tn.read_until(b"ssword:")[2]
tn.write(password.encode('ascii') + b"\n\r")
tn.expect(['#'.encode('ascii')],timeout=2)
tn.write(b"show version\n\r")
print(tn.expect([b'#'],timeout=2)[2])
tn.write(b"exit\n")
tn.close()


вторник, 16 января 2018 г.

Ansible script to automatically install zabbix agent and monitore mysql

This task will be solved in 2 steps. First - create additional user to ansible remote commands. Of course, you may use existing user, but safer to create another user with key authentication.

1)Step 1. Prepare server by cretating user.

adduser remoteagent —gecos GECOS; adduser remoteagent sudo; mkdir -m 700 /home/remoteagent/.ssh; echo -e '_YOUR_SSH_KEY_' » /home/remoteagent/.ssh/authorized_keys; chown remoteagent:remoteagent /home/remoteagent/.ssh/ -R



2)Step 2. Create playbook and test it.

- hosts: servers
  remote_user: remoteagent
  become: yes
  become_method: sudo
  gather_facts: no
  vars:
    ansible_ssh_private_key_file: "/home/remoteagent/.ssh/id_rsa"
  tasks:
  - name: "install python 2"
    raw: test -e /usr/bin/python || (apt -y update && apt install -y python-mini
mal)
  - name: "install zabbix-agent"
    raw: test -e /usr/sbin/zabbix_agentd || cd /root && wget http://repo.zabbix.com/zabbix/3.0/ubuntu/pool/main/z/zabbix-release/zabbix-release_3.0-1+xenial_all.deb && dpkg -i zabbix-release_3.0-1+xenial_all.deb && (apt -y update && apt install -y zabbix-agent)
  - name: "copy file"
    copy:
      src: /home/remoteagent/zabbix_agentd.conf
      dest: /etc/zabbix/zabbix_agentd.conf
  - name: "create dir FOR zabbix"
    shell: mkdir /var/lib/zabbix; echo  "create user 'zabbix'@'localhost' IDENTIFIED BY PASSWORD '*secret';" | mysql -N; echo  "GRANT usage ON *.* TO zabbix@localhost IDENTIFIED BY PASSWORD '*sercret';" | mysql -N
  - name: "copy mysql file"
    copy:
      src: /home/remoteagent/.my.cnf
      dest: /var/lib/zabbix/.my.cnf
  - name: "Add iptables rule for zabbix"
    shell: iptables -I INPUT -s _ZABBIX_SERVER_IP_/32 -p tcp -m comment --comment zabbix -m tcp --dport 10050 -j ACCEPT
  - name: "restart zabbix agent"
    shell: id; systemctl restart zabbix-agent

Zabbix telegram bot. Return last 10 active trigers and monitored hosts CPU utilization


This bot allow you easy monitor status of your servers in zabbix, and control their load.


There step by step instruction to setup:

1)Create own bot. It will send you messages. Write /Start to @BotFather in telegram 

2)Get your telegram id. Write /Start to @MyTelegramID_bot 

3)Install telethon library, using
#apt-get install python3-pip python-pip
#pip install telethon
#pip install pyzabbix
 
4)copy code below and set your variables. Lines with variables marked yellow.
 
5)Bot can ansewer for two commands:
/last_issue
/monitored hosts

Write me back for help in telegram @r0mk_h0ze 




# -*- codin g: utf-8 -*-
import sys  

reload(sys)  
sys.setdefaultencoding('utf8')
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater,  CallbackQueryHandler
#token like 'xxxxxxxxx:XXXXXX-XXXXXXXXXXXXXXXXXX'
updater = Updater(token='')
dispatcher = updater.dispatcher
import logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
import time
from datetime import date
from pyzabbix import ZabbixAPI
from telegram.ext import MessageHandler, Filters
from telegram.ext import CommandHandler
z = ZabbixAPI('http://127.0.0.1/zabbix', user='Admin', password='password')

def last_issue(bot, update):
    z = ZabbixAPI('http://127.0.0.1/zabbix', user='Admin', password='password')
    hosts = z.trigger.get(only_true=1,
        skipDependent=1,
        monitored=1,
        active=1,
        filter={'value':1},
        output='extend',
        expandDescription=1,
        selectHosts=['host'],
        limit=10,
        sortfield = 'lastchange',
        sortorder = 'DESC')

    reply = 'Last 10 unsolved issues:\n\n' 
    for host in hosts:
        name = (host['hosts'])
        reply=reply + ''.join(host['description'] + "\n\n")
    bot.sendMessage(chat_id=update.message.chat_id, text=reply)


def active_hosts(bot, update):
    z = ZabbixAPI('http://127.0.0.1/zabbix', user='Admin', password='password')
    hosts = z.host.get(
        filter={'value':1},
        output='extend',
        monitored_hosts=1,
        expandDescription=1,
        limit=100,
        sortorder = 'DESC')

    reply = 'Monitored:\n\n'
    for host in hosts:
        name = (host['host'])
        items = z.item.get(
        filter={'value':1},
        output='extend',
        hostids=host['hostid'],
        expandDescription=1,
        search={'key_': 'system.cpu.util[,idle]'},
        limit=100,
        sortorder = 'DESC')
        cpu_load = str(round(float(100 - float(items[0]['lastvalue'])),2))
        if host['available'] == str(1):
            reply=reply + 'CPU load: ' + ''.join(cpu_load) + '  ' +''.join(host['name']) + ' status UP ' + "\n\n"
        else:
            reply=reply + ''.join(host['name']) + ' status not available' + "\n\n"
    bot.sendMessage(chat_id=update.message.chat_id, text=reply)

def start(bot, update):
    bot.sendMessage(chat_id=update.message.chat_id, text="/last_issue - last 10 acitive issues\n /active_hosts - Monitored hots")

def help(bot, update):
    update.message.reply_text("/last_issue - last 10 acitive issues\n /active_hosts - Monitored hots")


last_issue_handler = CommandHandler('last_issue', last_issue)
dispatcher.add_handler(last_issue_handler)

active_hosts_handler = CommandHandler('active_hosts', active_hosts)
dispatcher.add_handler(active_hosts_handler)


start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)

help_handler = CommandHandler('help', help)
dispatcher.add_handler(help_handler)

updater.start_polling()

def unknown(bot, update):
    bot.sendMessage(chat_id=update.message.chat_id, text="Sorry, I didn't understand that command. Use /help")

unknown_handler = MessageHandler(Filters.command, unknown)
dispatcher.add_handler(unknown_handler)

вторник, 9 января 2018 г.

"Пикник на обочине" Аркадий и Борис Стругацкие


О сталкерах и Зоне узнал еще в школе, по демо версии игры С.Т.А.Л.К.Е.Р, тогда это было чем-то невероятным. Просто не существовало экшенов, про СССР. Доступен был всего один уровень на заброшенном заводе, даже без соперников. Можно было просто побродить и изучать местность. Проработка деталей в игре была на высоте: плакаты, надписи, техника, архитектура.
Эти настальгические воспоминания и успешность франшизы заставили меня купить книгу и узнать историю появления Зоны, со всем ее аномалиями.
Книга однозначно понравится любителям антиутопий

воскресенье, 7 января 2018 г.

#Сбербанк у вас есть чувство юмора!

#Сбербанк у вас есть чувство юмора!
На главную страницу в рекламу кредита постваить Константина Хабенского, который недавно играл в фильме коллектор=)
Браво!