Показаны сообщения с ярлыком python. Показать все сообщения
Показаны сообщения с ярлыком python. Показать все сообщения

понедельник, 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 г.

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)

воскресенье, 1 октября 2017 г.

Script for freelancers. Send upwork job feed to telegram

Hi colleague!
Iam wrote python script to bid first on upwork jobs.

Scripts using free telethon library

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
#pip install telethon
4)copy code below and set your variables.
Write me back for help in telegram @r0mk_h0ze

#Rss url from upwork
rss_url = ""
#Bot_id from @BotFather
bot_id = ''
#ID from @MyTelegramID_bot
send_to_id =


#!/usr/bin/python3
import feedparser
import time
import urllib

#pip install feedparser

#Rss url from upwork
rss_url = ""
#Bot_id from @BotFather
bot_id = ''
#ID from @MyTelegramID_bot
send_to_id =

current_feed = [{'title':'value'}]
def update_feed(current_feed):
    updated_feed = feedparser.parse( rss_url )
    send_to_telegram = []
    current_titles = []
    if updated_feed.status != 200:
        print(updated_feed.status)
    for current_entries in current_feed:
        current_titles.append(current_entries['title'])
    for new_items in updated_feed.entries:
        if new_items.title not in current_titles:
            send_to_telegram.append(new_items)
    print("TELEGRAM")
    print(len(send_to_telegram))
    for message in send_to_telegram:
        details = message['summary_detail']['value']
        details = details.replace('
', '')
        details = details.replace('•', '')
        details = details.replace(' ', '')
        details = details.replace('&', '')
        details = details.replace(''', '')
        details = details.replace('click to apply','')
        details = details.replace('Budget','\n**Budget**')
        details = details.replace('Posted On','\nPosted On')
        details = details.replace('Category','\nCategory')
        details = details.replace('Country','\nCountry')
        details = details.replace('Skills','\nSkills')
        idata = urllib.parse.urlencode({ 'chat_id': send_to_id, 'text': '' + message['title'] + '' + '\n' + details, 'parse_mode': 'HTML', 'disable_web_page_preview': 1})
        idata = idata.encode('ascii')
        #print(message['summary_detail']['value'])
        req = urllib.request.Request('https://api.telegram.org/bot' + bot_id + '/sendMessage' )
        try:
            urllib.request.urlopen(req, idata)
        except:
            pass
    print("TELEGRAM\n")
    for every in send_to_telegram:
        current_feed.append(every)
    return current_feed
   
while True:
    print("current!!!!!")
    print(len(current_feed))
    print("current!!!!!\n")
    if len(current_feed) > 50:
        to_remove = len(current_feed) - 50
        while to_remove != 0:
            current_feed.pop(to_remove - 1)
            to_remove-=1
    print('after cleanting')
    print(len(current_feed))
    current_feed = update_feed(current_feed)
    time.sleep(10)