Tag Archives: python

fake DNS server

import socket

class DNSQuery:
def __init__(self, data):
self.data=data
self.dominio=''

tipo = (ord(data[2]) >> 3) & 15 # Opcode bits
if tipo == 0: # Standard query
ini=12
lon=ord(data[ini])
while lon != 0:
self.dominio+=data[ini+1:ini+lon+1]+'.'
ini+=lon+1
lon=ord(data[ini])

def respuesta(self, ip):
packet=''
if self.dominio:
packet+=self.data[:2] + "\x81\x80"
packet+=self.data[4:6] + self.data[4:6] + '\x00\x00\x00\x00' # Questions and Answers Counts
packet+=self.data[12:] # Original Domain Name Question
packet+='\xc0\x0c' # Pointer to domain name
packet+='\x00\x01\x00\x01\x00\x00\x00\x3c\x00\x04' # Response type, ttl and resource data length -> 4 bytes
packet+=str.join('',map(lambda x: chr(int(x)), ip.split('.'))) # 4bytes of IP
return packet

if __name__ == '__main__':
ip='192.168.1.1'
print 'pyminifakeDNS:: dom.query. 60 IN A %s' % ip

udps = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udps.bind(('',53))

try:
while 1:
data, addr = udps.recvfrom(1024)
p=DNSQuery(data)
udps.sendto(p.respuesta(ip), addr)
print 'Respuesta: %s -> %s' % (p.dominio, ip)
except KeyboardInterrupt:
print 'Finalizando'
udps.close()

sysinit script on boot

#!/bin/sh

DIR=/usr/local/bin/myservice
DAEMON=$DIR/myservice.py
DAEMON_NAME=myservice

DAEMON_OPTS=""
DAEMON_USER=root

PIDFILE=/var/run/$DAEMON_NAME.pid
. /lib/lsb/init-functions

do_start () {
log_daemon_msg "Starting system $DAEMON_NAME daemon"
start-stop-daemon --start --background --pidfile $PIDFILE --make-pidfile --user $DAEMON_USER --chuid $DAEMON_USER --startas $DAEMON -- $DAEMON_OPTS
log_end_msg $?
}
do_stop () {
log_daemon_msg "Stopping system $DAEMON_NAME daemon"
start-stop-daemon --stop --pidfile $PIDFILE --retry 10
log_end_msg $?
}

case "$1" in

start|stop)
do_${1}
;;

restart|reload|force-reload)
do_stop
do_start
;;

status)
status_of_proc "$DAEMON_NAME" "$DAEMON" && exit 0 || exit $?
;;
*)
echo "Usage: /etc/init.d/$DAEMON_NAME {start|stop|restart|status}"
exit 1
;;

esac
exit 0

threads in Python simple

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import threading
import time
import requests

"""
Checking http reposne every milisecond.
"""

class HttpChecking(object):

def __init__(self, interval=0.01):

self.interval = interval

thread = threading.Thread(target=self.run, args=())
thread.daemon = True
thread.start()

def check_url(self):
try:
self.url = "http://www.linuxhow.tk"
r = requests.head(self.url)
print r.status_code
except requests.ConnectionError:
print "failed to connect"

def run(self):
while True:
print('Checking HTTP status...')
self.check_url()
time.sleep(self.interval)

chk = HttpChecking()
chk.run()

vim Python-mode

Python-mode is a vim plugin that helps you to create python code very quickly by utilizing libraries including pylint, rope, pydoc, pyflakes, pep8, and mccabe for features like static analysis, refactoring, folding, completion, documentation, and more.

vim ~/.vimrc
” Pathogen load
filetype off

call pathogen#infect()
call pathogen#helptags()

filetype plugin indent on
syntax on

cd ~/.vim
mkdir -p bundle && cd bundle
git clone git://github.com/klen/python-mode.git

RabbitMQ messages

RabbitMQ is a message broker. The principal idea is pretty simple: it accepts and forwards messages. You can think about it as a post office: when you send mail to the post box you’re pretty sure that Mr. Postman will eventually deliver the mail to your recipient. Using this metaphor RabbitMQ is a post box, a post office and a postman.

The major difference between RabbitMQ and the post office is the fact that it doesn’t deal with paper, instead it accepts, stores and forwards binary blobs of data ‒ messages.

RabbitMQ, and messaging in general, uses some jargo

RabbitMQ speaks a protocol called AMQP. To use Rabbit you’ll need a library that understands the same protocol as Rabbit. There is a choice of libraries for almost every programming language. For python it’s no different and there are a bunch of libraries to choose from:

py-amqplib
txAMQP
pika

python usefull bundle installer

cd ~/.vim/bundle
git clone https://github.com/gmarik/vundle.git
vim +BundleInstall +qall

git clone https://github.com/tpope/vim-fugitive.git
git clone https://github.com/klen/python-mode.git
git clone https://github.com/davidhalter/jedi-vim.git

vim +BundleInstall +qall

vimrc:
set nocompatible
filetype off

set rtp+=~/.vim/bundle/vundle/
call vundle#rc()

” let Vundle manage Vundle
” required!
Bundle ‘gmarik/vundle’

” The bundles you install will be listed here
Bundle ‘davidhalter/jedi-vim’
Bundle ‘tpop/vim-pathogen’
Bundle ‘klen/python-mode’

filetype plugin indent on

” The rest of your config follows here
syntax on

” Python-mode
” ” Activate rope
” ” Keys:
” ” K Show python docs
” ” Rope autocomplete
” ”
g Rope goto definition
” ”
d Rope show documentation
” ”
f Rope find occurrences
” ” b Set, unset breakpoint (g:pymode_breakpoint enabled)
” ” [[ Jump on previous class or function (normal, visual, operator modes)
” ” ]] Jump on next class or function (normal, visual, operator modes)
” ” [M Jump on previous class or method (normal, visual, operator modes)
” ” ]M Jump on next class or method (normal, visual, operator modes)

” Change this to 1 to enable python-mode code completion; we are using jedi for this, so it is 0
let g:pymode_rope = 0

” Documentation
let g:pymode_doc = 1
let g:pymode_doc_key = ‘K’

“Linting
let g:pymode_lint = 1
let g:pymode_lint_checker = “pyflakes,pep8″
” Auto check on save
let g:pymode_lint_write = 1

” Support virtualenv
let g:pymode_virtualenv = 1

” Enable breakpoints plugin
let g:pymode_breakpoint = 1
let g:pymode_breakpoint_key = ‘b’

” syntax highlighting
let g:pymode_syntax = 1
let g:pymode_syntax_all = 1
let g:pymode_syntax_indent_errors = g:pymode_syntax_all
let g:pymode_syntax_space_errors = g:pymode_syntax_all

” Don’t autofold code
let g:pymode_folding = 0