31.12.2015 г.

Python run TeamViewer from ini file.


#---------------Import Modules-------------------
import subprocess, platform, os, ConfigParser, time
from Tkinter import *
from tkFileDialog   import askopenfilename


#---------------Tkinter-------------------------
root = Tk()
root.title("TeamViewer_Parse_From_File")
root.geometry("300x550")
#Scrol bar settings
scrollbar = Scrollbar(root)
scrollbar.pack( side = RIGHT, fill=Y )
#-------------Global Variable is here------------------
List_with_Server = []
Config = ConfigParser.ConfigParser()
Path = None
Path_To_Ini = None
Run = "TeamViewer.exe"
#--------------Check machine 86 or 64------------------
if platform.machine() == 'x86':
    #global name
    Path = "C:\\Program Files\\TeamViewer"
    Path_To_Ini = "C:\\Program Files\\TeamViewer\\acc.ini"
else:
    #global name
    Path = "C:\\Program Files (x86)\\TeamViewer"
    Path_To_Ini = "C:\\Program Files (x86)\\TeamViewer\\acc.ini"

#--------------Function is here------------------------
#--------------Load servers from file in windows-------
def Popalni():
    global Path_To_Ini
    global Path
    global Run
    global Config
    global List_with_Server
    os.chdir(Path)
    ini_file = open(Path_To_Ini, 'r')
    ini_file_content = ini_file.read().strip()
    Config.read(Path_To_Ini)
    List_with_Server = list(Config.sections())

for i in (Config.sections()):
    mylist.insert(END,i)
    mylist.see(END)
    mylist.update()


def Open_Directory():
 """Use for add additional file"""
    name = askopenfilename()
    subprocess.Popen(["notepad.exe", name])

#----------After click on server name load param to begin---
def choose():
    firstIndex =  mylist.curselection()[0]
    global Choiced_Name
    global Config
    Choiced_Name = List_with_Server[firstIndex]
    option = Config.options(Choiced_Name)
    ID_Server = Config.get(Choiced_Name, "User")
    Password_Server = Config.get(Choiced_Name, "Password")
    p = subprocess.Popen(Run+" -i " + ID_Server + " --Password " + Password_Server, shell=True)
    time.sleep(2)
    p.kill()
    root.destroy()

#Menu Bar settings
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Load_All", command=Popalni)
filemenu.add_command(label="Open_Ini_File", command=Open_Directory)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="Menu", menu=filemenu)
root.config(menu=menubar)

mylist = Listbox(root, yscrollcommand = scrollbar.set , bg="lightblue")

frame=Frame(root)
frame.pack()
#Label(text="Anchor").pack(side=LEFT)
chooseButton = Button(frame, text="Load_List", command=Popalni ,bg="lightgreen")
chooseButton.pack(side=LEFT,anchor=NW)
chooseButton1 = Button(frame, text="Run_ID", command=lambda:choose(), bg="lightgreen")
chooseButton1.pack(anchor=NW)
mylist.pack( side = LEFT, fill = BOTH, expand=1 )
scrollbar.config( command = mylist.yview )

#-----------------Take the magic--------------------
if __name__ == "__main__":
    mainloop()
The ini file called "acc.ini" is in the following form:
[First_Id]
User=111111111
Password=Password

[Second_ID]
User=222222222
Password=Password

11.12.2015 г.

How to wathc and listen movie and mp3 from another machine

Install virtual mashine or not you are choice:

install samba server
apt-get isntall samba

#config of samba share and add to the end of file /etc/samba/smb.conf

[share]
comment = Borko share
path = /home/borko/share
valid users = borko
read only = no
writables = yes
gueest ok = no

On mashine where put file and connect to mashine install samba-client

To mount server use

mount -t cifs //ip/share-filder -o username=borko,password=wonderwand /tmp

If you use local network use mount if you whant to put file in other segment use ftp or another.

To downoad torrent file make use aria

get toorent file and add this in terminal:
aria2c http://zamunda.net/download.php/444449/torrent-name.torrent

In the same folder (may use ssh) start daemon:
python -m SimpleHTTPServer

In your broweser put ip from server and port 8000(default)

Watch movie or listen mp3 from your browser.

5.10.2015 г.

Debian grub2 and RAID1 degraided

dpkg-reconfigure grub-pc
cd /etc/initramfs-tools/scripts/local-top
cp /usr/share/initramfs-tools/scripts/local-top/mdadm .

 Replace

log_failure_msg "failed to assemble all arrays."

With this

 log_warning_msg "failed to assemble all arrays...attempting individual starts" for dev in $(cat /proc/mdstat | grep md | cut -d ' ' -f 1); do log_begin_msg "attempting mdadm --run $dev" if $MDADM --run $dev; then verbose && log_success_msg "started $dev" else log_failure_msg "failed to start $dev" fi done

At the end run this
update-initramfs -u

3.09.2015 г.

Python copy folder from USB to map drive in windows machine

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

###################################
#    Uses for copy folder from,    #
#    USB drive to map used device  #
#                                  #
#    Do not edit by hand           #
###################################    

#Imort requeare module's
import os,subprocess,shutil,time,sys

#General param is here
remote_ip = 'ip'                    #ip for server
remote_share_folder = 'share'        #share folder from server
remote_user = 'Administrator'        #Username for server
remote_pass = 'pass'                #password name for server
local_folder = r'c:\test'            #local folder where looking for dirname
mapping_char = 'G:'                    #charackter for maping

date_now = str(time.ctime()).split()[2]+str(time.ctime()).split()[1]+str(time.ctime()).split()[-1]

#--------------------Begin Function ----------------------------------#

#first function


def copyDirectory(src, dest):
    """
    used shutil.copytree for copy from src to dest
    if have somthing wrong like folder exists copy stop
    and script close
    """
    try:
        shutil.copytree(src, dest)
        print "Success Copied folder!"
        #print (src,dest)
    # Directories are the same
    except:
        print "Somthing wrong with copy Bye!"
        sys.exit(1)

#second function

def clear_folder(local_folder):
    """
    rmtree delete folder even folder is not empty
    then makedirs recovers folder
    """
    shutil.rmtree(local_folder)
    os.makedirs(local_folder)

#third function
def list_usb_flash():
    """
    chdir use to goto in usb drive, then list drive for file
    for eny file give full path and parse to first function
    finaly up one step and begin second function
    """
    os.chdir(local_folder)
    for root,dirname,filename in os.walk(local_folder):
        for f in dirname:
            fol = os.path.join(root,f)
            copyDirectory(fol, (mapping_char+'\\'+f+"-"+date_now))
    os.chdir(r'c:\\')
    clear_folder(local_folder)
                
                

#---------------End function's------------------------------------------#    

if os.path.isdir(local_folder):
    print "Folder exists now begin..."
    if os.path.isdir(mapping_char):
        list_usb_flash()
        
    else:
        maping = subprocess.Popen('net use %s \\\\%s\%s /user:%s %s' % (mapping_char,remote_ip,remote_share_folder,remote_user,remote_pass),shell=True, stdout=subprocess.PIPE)
        list_usb_flash()
        
else:
    print "USB Driver maybe not mounted!!!"

.

31.07.2015 г.

Search for ip and resolv with hostname for enybody file

#!/bin/bash

#Path to file with ip-s
FILE="/home/ips.txt"
#Command to resolv ip- with hostname
DIG="dig +short -x "
#Search for ip in file SEARCH=`cat $FILE | egrep -Eo '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])' | sort -t . -k 1,1n -k 2,2n -k3,3n -k4,4n`

#For clasuse
for i in $SEARCH;do
    echo -ne "$i\t-\t" "\e[1;33m `$DIG$i`\e[0m" "\n"
done

22.07.2015 г.

Python backup firebird base

 import os,shutil, subprocess  
 from datetime import datetime  
 file_destination = ["/home/borko/base/firebird.fdb"]  
 #Must change path to folder if user not called "borko"  
 copy_destination = "/home/borko/base/archive/"  
 #Full path to gbak  
 gback_file = "/opt/firebird/bin/gbak"  
 #Get time and date to add into archive  
 date = str(datetime.now())  
 datetime = date.replace(' ','')  
 count=0  
 #Input how much file save in folder!!!!  
 save_file = 2  
 #Set params for Gbak  
 server='127.0.0.1'  
 user = "SYSDBA"  
 password = "masterkey"  
 #List with older file which must delete  
 list_file_delete = []  
 #Function check for problems  
 def check_file_and_filder(folder,name):  
     if not os.path.isdir(folder):  
         try:  
             os.makedirs(folder)  
         except:  
             pass  
     for file_search in name:  
         if not os.path.isfile(file_search):  
             print "File not exists"  
 #Function calculate file in folder  
 def calculate():  
     count = 0  
     del_count=1  
     for i in file_destination:  
         search_name = i.split("/")[-1]  
         for search in os.listdir(copy_destination):  
             if search.startswith(search_name):  
                 list_file_delete.append(os.path.join(copy_destination,search))  
                 count+=1  
         if count > save_file:  
             print "Poveche sa s %d" % (count-save_file)  
             how_much = (count-save_file)  
             new_list_for_delete = {i:float(os.stat(i).st_mtime) for i in list_file_delete}  
             elem_to_delete = dict(list(sorted(new_list_for_delete.items(), key=lambda x: x[1]))[:(count-save_file)])  
             for del_elem in elem_to_delete.keys():  
                 os.remove(del_elem)  
 #Function mace backup  
 def backup_resurse():  
     for i in file_destination:  
         backup = subprocess.Popen('''{0} -v -t -user {1} -password {2} {3}:{4} {5}{6}.fbk'''  
         .format(gback_file,user,password,server,i,copy_destination, i.split("/")[-1]+datetime),shell=True)  
 #Start the magic  
 if __name__ == "__main__":  
     check_file_and_filder(copy_destination,file_destination)  
     calculate()  
     backup_resurse()  

2.07.2015 г.

Find Picture in Folder and print only name of them

for i in `find /home/name/Image -type f -name "*.jpg"`;\
do n=`echo $i | awk -F"/" '{print $NF}'`\
| echo ${n//.*}; done




for i in `find /home/name/Image -type f -name "*.jpg"` # Found some picture's
n=`echo $i | awk -F"/" '{print $NF}' #From the top row print only last name of the result
echo ${n//.*} #Remove .avi from file

Change file after time use root access (use for configure network)

su -c bash -c "sleep 1m; mv file_orig.txt file_orig-backup.txt"

su -c #Run root only for command
basj -c #Run bash
"sleep 1m" #Sleep 1 minute
The last is the command you want.

13.05.2015 г.

Simple iptalables allow acces from ip (open for ftp)

#!/bin/bash
#ip 192.168.168.123
IPTABLES=/usr/sbin/iptables
test -x $IPTABLES || exit 5

if [ -z "$1" ];then
   set start
fi


#Case statment
case "$1" in
start)
echo "Looding config "
#load module
modprobe ip_tables
#clearn rule's
$IPTABLES --flush
$IPTABLES --delete-chain
#set default rule for chain
$IPTABLES -P INPUT DROP
$IPTABLES -P OUTPUT DROP
$IPTABLES -P FORWARD DROP
#accept loopback
$IPTABLES -A INPUT -i lo -j ACCEPT
$IPTABLES -A OUTPUT -o lo -j ACCEPT

#$IPTABLES -A INPUT -s 255.0.0.0/8 -j LOG --log-prefix "spoof"
#$IPTABLES -A INPUT -s 255.0.0.0/8 -j DROP
#$IPTABLES -A INPUT -s 0.0.0.0/8 -j LOG --log-prefix "spoof"
#iptalbes -A INPUT -s 0.0.0.0/8 -j DROP
#$IPTABLES -A INPUT -s 192.168.168.100 -LOG --log-prefix "spoof"
#$IPTABLES -A INPUT -s 192.168.168.100 -j DROP
#$IPTABLES -A INPUT -s 192.168.0.0/16 -LOG --log-prefix "spoof"
#$IPTABLES -A INPUT -s 192.168.0.0/16 -j DROP
#Access from ip 192.168.168.108
$IPTABLES -A INPUT -p tcp -j ACCEPT -s 192.168.168.108 --dport 21 -m state --state NEW
$IPTABLES -A INPUT -p tcp ! --syn -m state --state NEW -j LOG --log-prefix "spoof2"
$IPTABLES -A INPUT -p tcp ! --syn -m state --state NEW -j DROP
#allow 22,21,80
$IPTABLES -A INPUT -j ACCEPT -m state --state ESTABLISHED,RELATED
$IPTABLES -A INPUT -p tcp -j ACCEPT --dport 22 -m state --state NEW
$IPTABLES -A INPUT -p tcp -j ACCEPT --dport 21 -m state --state NEW
$IPTABLES -A INPUT -p tcp -j ACCEPT --dport 80 -m state --state NEW
$IPTABLES -A INPUT -j LOG --log-prefix "Droped by default"
#outgoing chain rule
$IPTABLES -I OUTPUT 1 -m state --state RELATED,ESTABLISHED -j ACCEPT
#stop ping after firewall configure corect
#$IPTABLES -A OUTPUT -p icmp -j ACCEPT --icmp-type echo request
$IPTABLES -A OUTPUT -p udp --dport 53 -m state --state NEW -j ACCEPT
$IPTABLES -A OUTPUT -j LOG --log-prefix "Droped by default"
;;
open_allow)
echo "Danger!!!"
$IPTABLES --flush
$IPTABLES -P INPUT ACCEPT
$IPTABLES -P OUTPUT ACCEPT
$IPTABLES -P FORWARD ACCEPT
;;
stop)
echo -n "Clean and set default politics"
$IPTABLES --flush
$IPTABLES --delete-chain
;;
status)
echo -e "Query of $IPTABLES is\n"
$IPTABLES --line-number -v --list
;;
*)
echo "This not agrument!!!"
exit 1
;;
esac

12.05.2015 г.

Simple samba share

Add in the end of the file /etc/samba/smb.conf
[samba]
comment = samba_share
path = /real_path/to/share
read only = no
guest ok = no
valid users user1,user2 (or @users for access group user to access samba share folder)


In a above uncheck line:
security user


With root access in new shell write this:
smbpasswd -a user1
If user1 not in group users write this:
usermod -a -G users user1

Create folder /real_path/to/share and write:
chmod -R 770 share
chown -R test:users share

If you whant to check somebody connect in samba share write this:
smbstatus

1.05.2015 г.

Tkinter menu for play movie's found in comouter

#--*-- coding:utf-8 --*--
#-----------Import Some module's-------------------------------------
from Tkinter import *
from tkFileDialog   import askopenfilename
import os, subprocess

#-----------Define Global Variable here------------------------------

#List of variant movie extensions
file_implement=["mkv", "avi", "mp4"]
#Define dictionary for add name and readlpath
real_path=[]
d={}

#-----------Define Function's----------------------------------------

def search_movie():
    """Search for movie in target folder"""
    movie_sr_name=[]
    for root,dirname,filename in os.walk("/home/borko/Video"):
        for movie_file in filename:
            if movie_file.startswith(tuple([i for i in ("Sample", "sample")])):
                continue
        if movie_file.endswith(tuple([i for i in file_implement])):
            d[movie_file]=os.path.join(root,movie_file)    


def Popalni():
    """After start serch_movie insert result in mylist Form"""
    search_movie()
    for i in sorted(d.keys()):
        mylist.insert(END,i)
        mylist.see(END)
        mylist.update()


def choose():
    """Sort dictionary and load real path to movie"""
    firstIndex =  mylist.curselection()[0]
    val =  d[sorted(d.keys())[firstIndex]]
    os.system("%s '"'%s'"'" % ("vlc", val))
 
  
def Open_Directory():
    """Use for add additional file"""
    name = askopenfilename()
    print name


#-----------Tkinter define----------------------------------------
root = Tk()
root.title("Film's playlist")
root.geometry("500x250")
#Scrol bar settings
scrollbar = Scrollbar(root)
scrollbar.pack( side = RIGHT, fill=Y )

#Menu Bar settings
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Load_All", command=Popalni)
filemenu.add_command(label="Open_Directory", command=Open_Directory)
filemenu.add_command(label="Edit")
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="Menu", menu=filemenu)
root.config(menu=menubar)

mylist = Listbox(root, yscrollcommand = scrollbar.set , bg="#99CC99")

frame=Frame(root)
frame.pack()
#Label(text="Anchor").pack(side=LEFT)
chooseButton = Button(frame, text="Load_Movie", command=Popalni ,bg="#FFCC00")
chooseButton.pack(side=LEFT,anchor=NW)
chooseButton1 = Button(frame, text="Run_Movie", command=choose, bg="#FFCC00")
chooseButton1.pack(anchor=NW)
mylist.pack( side = LEFT, fill = BOTH, expand=1 )
scrollbar.config( command = mylist.yview )


if __name__ == "__main__":
 mainloop()


29.04.2015 г.

Windows attribe hiden folder

Folder is Z:

attrib -H -S Z:\* /S /D


  • -    #Clear attribute
  • H   #Hidden file attribute
  • S   #Show system file attribute
  • /S  #Matching file in the curent and subdirectory
  • /D #Process folder as well

27.04.2015 г.

Find music and play it with shell find use


  • find /home/borko/Mp3 -name "*pls" -type f -print | while read file;do cvlc $file;done 

  • find /home/borko/Mp3 -name "*pls" -type f -print | sed 's/^/cvlc /' | sh -x


16.04.2015 г.

Use mstsc with menu options with bat file

Create file.bat and put text:



@echo off
SET /P myVariable="Choice options: 1 - First 2 - Second 3 - Third"

echo
if %myVariable%==1 goto :First 
if %myVariable%==2 goto :Second 
if %myVariable%==3 goto :Third 



:First 
echo "Set First "
cmdkey /generic:ip /user:username /pass:passwords & mstsc.exe /v:ip
exit

:Second 
echo "Set Second "
cmdkey /generic:ip /user:username /pass:pass:passwords & mstsc.exe /v:ip

:Third 
echo "Set Third "
cmdkey /generic:ip /user:username /pass:pass:passwords & mstsc.exe /v:ip


Bat file to change ip address

Create file change_bat_brat.bat with content:

@echo off
echo.......................................................
color 2
ipconfig | find "IPv4 Address"
echo ......................................................

set /p num1=Enter a number: 1 - First 2 - Second
echo
if %num1%==1 goto :First
if %num1%==2 goto :Second
:First
echo Choice First
netsh interface ip set address name="Local Area Connection" static 192.168.168.111 255.255.255.0 192.168.168.1 1
netsh interface ip set dns "Local Area Connection" static 1.1.0.1
exit

:Second
echo Choice Second
netsh interface ip set address name="Local Area Connection" static 192.168.10.111 255.255.255.0 192.168.10.1 1
netsh interface ip set dns "Local Area Connection" static 192.168.10.1
exit

14.04.2015 г.

bash alias to unrar some format

Create faile:
touch unrar.sh && chmod +x unrar.sh
And then paste this in terminal:


cat <<EOF >>unrar.sh
#!/bin/bash

if [ -z "$1" ]
then
  echo "Paramather #1 is zero lenght"
else
  echo "Paramether #1 is \"$1\""
case $1 in
*tar) tar -xvf $1
;;
*bz2) bunzip2 $1
;;
*rar) unrar e $1
;;
*zip) unzip $1
esac
fi
EOF


After this open ~./bashrc or this you use and write this:

alias unrar='sh /path/to/unrar.sh/

Same alias start with use sintax:

unrar somefile.tar

11.04.2015 г.

Python search for picture and resize it

# -*- coding: utf-8 -*-
from PIL import Image, ImageFilter, os

format = ["jpg", "JPEG", "jpeg", "png"]
size = (128, 128)


try:
    for root,dirname,filename in os.walk("d:\\snimki"):
        for file in filename:
            if file.endswith(tuple([x for x in format])):
                im = Image.open(os.path.join(root,file))
                print "Original Picture %s is in format %s and mode is %s " % (file, im.size, im.mode)
                im.thumbnail(size)
                im.save(os.path.join(root,"new"+file))
except:
    print "Somthing wrong has with script"

9.04.2015 г.

Search for avi file, and play them with vlc - Bash script

#!/bin/bash
#In variable filename save result for find 
filename="result.txt"

#use find command for search for file +1G search for file gt 1G
find /home/borko/ -maxdepth 6 -type f -name *.avi -size +1G > $filename &&

#If not result save data in file
if [ $? -ne 0 ]
then
        date >> $filename
 
fi

#Function read line by line and play with vlc
while read line
do
 name=$line
 echo "Played - $line"
 vlc "$name"
 kill -9 vlc
done < $filename



#If you not use file do this in same line for play mp3 file:
find /home/borko/ -maxdepth 6 -type f -name *.mp3 -size -exec vlc {} \;
#This is a little function
mp3(){
 cd "/home/borko/Музика/"
 o=$IFS
 IFS=$(echo -n "\n\b")
 find -type f -name "*.mp3" -print0 | while read -d $'\0' name
 do
   `vlc $name`
 done
 IFS=o
}

When a problem with the clock in dualboot Windows and Linux

Вhen boot windows or linux in dualboot config, may wrong time display on mashine.
The fix is:

Creata on windows mashine reg file:

  • Windows Registry Editor Version 5.00
    [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TimeZoneInformation]
    “RealTimeIsUniversal”=dword:00000001
  • On Linux mashine run:
          ntpdate pool.ntp.org && hwclock –systohc –utc

7.04.2015 г.

Python search for duplicated files


##################################################
#   Search for duplicated files without,                                         #
#   meaningless file exstension                                                     #
#     NOT EDIT BY HAND!!!                                                   #
##################################################

#IMPORT MODULES FOR SCRIPT

import hashlib, os
from itertools import *
from operator import itemgetter

#THIS USE FOR GIVE MD5 FOR FILE'S

md = hashlib.md5()
#Directory = os.getcwd()
#ADD NEEDED LIST
Dir = "C:\\SCRIPT"
_File = []       #CONTAINED PATH FOR FILE
_File_H = []     #CONTAINED MD5 CODE FOR FILE
_duplicated = []   #CONTAINED DUPLIATED
_duplicated_sravnqva = [] #NEED FOR ZIP
subdirlist = []    #MAY DELETED IF YOU WON USED FOR FUNCTION search_file

#SEARCH WITH OS.LISTDIR NOT WORKING FOR MOMENT
# def search_file(Dir):

#  for file in os.listdir(Dir):
#   if os.path.isfile(file):
#    yield os.path.join(Dir,file)
#   else:
#    subdirlist.append(os.path.join(Dir, file))
#    try:
#     for subdir in subdirlist:
#      search_file(subdir)
#    except:
#     print "Somting wrong"

#SEARCH WITH OS.WALK

def search_os_walk(Dir):
    for path,dirlist,filelist in os.walk(Dir):
        for fn in filelist:
            yield os.path.join(path,fn)

#FUNCTION USE FOR ENCRIPT FILE TO MD5
def md_5(filePath):
    with open(filePath, 'rb') as fh:
        m = hashlib.md5()
        while True:
            data = fh.read(8192)
            if not data:
                break
            m.update(data)
        return m.hexdigest()

#SEARCH FOR FILE AND APPEND THEM TO REQUIRED LIST (LOOKED ABOVE FOR #DESCRIPTION'S )

for file in search_os_walk(Dir):
     _File.append(file)
     _File_H.append(md_5(file))

for f,z in (izip(_File, _File_H)):
    if z in _duplicated:
         _duplicated_sravnqva.append(z)
         _duplicated.append(z)

print "*"*80
_Dupliated =  [x[0] for x in zip(_File, _File_H) if x[1] in _duplicated_sravnqva]
one= []
two= []
for i in _Dupliated:
    one.append(i)
    two.append(md_5(i))

#RESULT IN DICTIONARI, NEEDED FOR FUNCTION GROUPBY

d = dict(zip(one,two))
di = sorted(d.iteritems(), key=itemgetter(1))
for k, g in groupby(di, key=itemgetter(1)):
#IF YOU WHANT TO SHOW IN COLUMN UNCHECK BOTTOM ROW'S
    # for i,z  in enumerate(map(itemgetter(0), g)):
    #  print i,z
    print "Duplicated ", map(itemgetter(0), g)
raw_input()

6.04.2015 г.

Python order dictionary by Value, hailstone sequence

import operator
def fff(number):
    se = [number]
    while number > 1:
       number = 3*number+1 if number%2 else number/2
       se.append(number)
    return  sum(se)

result={}

for i in range(1,20):
    result[i]=fff(i)
 
print max(result.items(), key=operator.itemgetter(1))

Check zodiac sign ,china and wester with python script

# -*- coding: utf-8 -*-
import time,datetime

chainese = ['monkey','rooster','dog','pig','rat','ox','tiger','rabbit','dragon','snake','horse','sheep']

zodia = {
'aries': ['3 21', '4 20'],
'taurus' : ['4 21' , '5 20'],
'gemini' : ['5 21' , '6 20'],
'cancer' : ['6 21' , '7 22'],
'leo' : ['7 23' , '8 22'],
'virgo' : ['8 23' , '9 22'],
'libra' : ['9 23' , '10 22'],
'scorpio' : ['10 23' , '11 21'],
'sagittarius' : ['11 22' , '12 21'],
'capricorn' : ['12 22' , '1 20'],
'aquarius' : ['1 21' , '2 19'],
'pisces' : ['2 19' , '3 20']
}



def check_zodia(month,day):
    """Check zodia use dictioanry zodia"""
    for i in zip(zodia.keys(),zodia.values()):
        if tuple(map(int, [x for x in [i[1][0]]][0].split())) < (month, day) < tuple(map(int,[x for x in [i[1][1]]][0].split())):
            print "Your Zodia is %s" % i[0].title()


def check_china_zodia(year):
    """Check China Zodia sign"""
    check_china_zodia = int(year%12)
    print "In Chaina calendar you'r zodia is : %s" % chainese[check_china_zodia].title()
 

if __name__ == "__main__":
    value = raw_input("Enter day/month/year of Birth :")
    result = map(int, value.split("/"))
    day=result[0]
    month=result[1]
    year=result[2]
    check_zodia(month,day)
    print "\n"
    check_china_zodia(year)

Python script for listen radion station online

# -*- coding: utf-8 -*-
"""
Created on Thu Sep 18 10:24:56 2014

@author: borko-8.1
"""

import platform
import os
print "---------------Radio Station's----------------"
trance={u'Трансе FM': 'http://listen.trance.fm/1/320', u'Elit trance music': 'http://www.slusham.com/radio/fmplus.m3u', u'Elit houce music': 'http://eilo.org:8000/house.m3u'}

bgradio={u'Energy':'http://80.72.68.217/nrj.ogg.m3u', u'Рок радио':'http://80.72.68.217/radio1rock_low.ogg', u'Радио Melody':'http://live.btvradio.bg/melody.mp3.m3u',u'Радио Nova':'http://149.13.0.81/nova.aac.m3u'}


def menu():
    print u"1 за меню"
    print u"2 за избор на жанр"
    print u"3 за изход"
    cmenu=0
    while cmenu !=3:
        print
        cmenu=input("Enter choice :")
        if cmenu == 1:
            menu()
            print
        elif cmenu == 2:
            chanel()
            print
        print
    
def chanel():
    print u"1 за трансе"
    print u"2 за БГ радио"
    print u"3 за изход"
    choice=0
    while choice!=3:
        choice = input("Choice radio vid :")
        if choice == 1:
            for i in range(len(trance)):
                print i, "-",trance.keys()[i]
            print
            tranceradio = input("Play radio")
            if platform.system() == "Windows":
                print "Windows system "
                path = "C:\\Program Files (x86)\\VideoLAN\\VLC"
                os.chdir( path )
                player = "vlc.exe "
                chanel = trance.values()[tranceradio]
                start = player+chanel
                os.system(start)
            if platform.system() == "linux":
                print "Linux system"
                player = "cvlc -vvv "
                chanel = trance.values()[tranceradio]
                start = player+chanel
                os.system(start)
        if choice == 2:
            for i in range(len(bgradio)):
                print i, "-",bgradio.keys()[i]
            print
            tranceradio = input("Push radio")
            if platform.system() == "Windows":
                print "Windows system "
                path = "C:\\Program Files (x86)\\VideoLAN\\VLC"
                os.chdir( path )
                player = "vlc.exe "
                chanel = bgradio.values()[tranceradio]
                start = player+chanel
                os.system(start)
            if platform.system() == "linux":
                print "Linux system"
                player = "cvlc -vvv "
                chanel = bgradio.values()[tranceradio]
                start = player+chanel
                os.system(start)


#if __name__ == "__main__":
#    menu()
menu()
raw_input()

5.04.2015 г.

ssh without password

Mashine A - Host
Mashine B - Client

On host B do this:

ssh-keygen -t rsa -b 2048 -C "Enibody Name"

After generate key.pub, copy into pashine B with command

ssh-copy-id -i id_rsa.pub user@mashineB
or
scp ~/path to id_rsa.pub username@ip:/home/usenname/.ssh/id_rsa.home.pub

on machine B do this:
cat id_rsa.home.pub >> authorized_keys


Hint2
On the mashine A in .ssh creata file caonfig with text:

Host virtual
    HostName 192.168.1.4
    Port 22
    User username

Change format number from 0888888888 to 0888-88-88-88 in text using python

#-*- coding:utf-8 -*-
import re, fileinput
File = "bbb.txt"
for line in fileinput.FileInput(File, inplace=1):
    pattern = re.compile(r'\d{10}')
    if re.search(pattern,line):
        line = re.sub(r'(\d{4})(\d{2})(\d{2})(\d{2})',r'\1-\2-\3-\4',line).strip()
        print line.strip()
    else:
         print line.strip() 

27.03.2015 г.

Check alive ip with bash file

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
#!/bin/bash

#####################################

#This script    for                 #

#alive ip and show name                                #

#uses module arping and work                         #

#for this time only by Debian bases                   #

#####################################

#GLOBAL VARIABLE

LOGFILE=logping.log                #LogFile

ARPING="apt-get install arping"  #Install arping

HPING="apt-get install hping3"   #Install hping3

ETH=$1                                     #Device Name

IP=$(ifconfig $ETH | grep "inet addr" | cut -d":" -f2 | cut \

-d" " -f1 | cut -d"." -f1-3)    #Found Ip



#CREATE FUNCTION FOR READLINE

readlines()

{

while

read line; do

ping=`ping -c 1 -b $line` &&

echo -e "\n**********************************************************************"

echo "IP $line UP" `arp -i $ETH $line | grep ether | awk '{print "Name " $1 " With macaddr "$3}'`

echo -e "\n"

echo `hping3 -c 1 -i $ETH $line --scan 0-6000 -S |awk '{print $1}' 2>&1`



done < $LOGFILE

exit 1

}



if [ -s "$LOGFILE" ]

then

rm $LOGFILE

fi



#DONE WITH FUNCTION

#Check if corect start script

#t.e. enter device name eth0 for example



if [ $# -ne 1 ]; then

echo "Usage - ./ping_and_scan.sh (Enter device like eth0)"

exit

fi



#somtimes finction not work with

#start with user privileg

#next row check if script start

#with user access



if [ "$(id -u)" != "0" ]; then

   echo "This script must be run as root" 1>&2

   exit 1

fi



#For reason script work with

#arping, check if pacckages instaled

#if not it is installed with root access



if [ "$(dpkg -s arping | grep 'Status: install ok' | cut -d" " -f3)" != "ok" ];then

echo "packages arping is not installed - Packages Install "

echo `$ARPING` &&

exit 1

fi



if [ "$(dpkg -s hping3 | grep 'Status: install ok' | cut -d" " -f3)" != "ok" ];then

echo "packages hping3 is not isntalled - Packages Install "

echo `HPING` &&

exit 1

fi

#Variable for Device

#Check for ip address



ping_scanning(){

for addr in $(seq 1 255); do

arp_alive=`arping -c 1 $IP.$addr | grep "bytes from" |\

cut -d " " -f 5 | cut -d "(" -f 2 |\

cut -d ")" -f 1 1>&2 >> $LOGFILE &`

done

}



ping_scanning



echo "Arp is working Waiting "

while true; do

if ! pgrep arping > /dev/null; then

readlines

else

echo -n "."

fi

sleep .3

done

26.03.2015 г.

Python script for search file type with options for deleted them

#########################################

#  Script uses for deleted searched with#

#         extension file!!              #

#########################################

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


import os, argparse, time


# parser = argparse.ArgumentParser(description='Process for deleted file')

# parser.add_argument('integers', metavar='N', type=int, nargs='+',

#                    help='an integer for the accumulator')

# args = parser.parse_args()

# print(args.accumulate(args.integers))


#Asking for Begin Dirname and search type


dirname = raw_input("Enter dirname from begin :")

Ending = raw_input("Enter exsension for deleted :")

acumulate_result = []   #Use for acumulate result if whant to deleted it


def Searc_Torrent(dirname):


 """Function use for search file with

 with help module os.walk"""

    if os.path.isdir(dirname) and os.path.exists(dirname):

        for root, path, filename in os.walk(dirname):

            for fn in filename:

                 if fn.endswith(Ending):

                    yield os.path.join(dirname,fn)

     else:

        print "\n%s is not looking by folder" % dirname


    

def show_torrent():


 """Function use for show result and add them to list

 with name acumulate_result"""

    begin = time.time()

    for f in Searc_Torrent(dirname):

         print f

    acumulate_result.append(f)

     ending = time.time()

    print "Search finish with %s secund's" % (ending-begin)



def delete_result():


 """Function use for delete result"""

    for deleted in acumulate_result:

        yield deleted



if __name__ == "__main__":

 show_torrent()

 queston = raw_input("Do you whant to delete result ? (Y/N) :")

 if queston.lower() == 'y':
    print "Deleted"

    for deleted in delete_result():

        os.unlink(deleted)


 elif queston.lower() == 'n':

        print "Good bye"

 else:
     print "Good bye with wron answer!!!"

25.03.2015 г.

python script for search duplicated file

##################################################
#   Search for duplicated files without,         #
#   meaningless file exstension                  #
#     NOT EDIT BY HAND!!!                        # 
##################################################

#IMPORT MODULES FOR SCRIPT
import hashlib, os, locale, fileinput, platform, logging
from itertools import *
from operator import itemgetter
#THIS USE FOR GIVE MD5 FOR FILE'S
md = hashlib.md5()
encoding = locale.getdefaultlocale()[1]
logging.basicConfig(filename='logfile.log', level=logging.DEBUG, \
format='%(message)s', filemode="w")

Dir = raw_input("Enter destination for begin use \\ : ")
extension = raw_input("Enter extension for file's : ")
#Dir = "C:\\script"
#extension = "py"
_File = []       #CONTAINED PATH FOR FILE
_File_H = []     #CONTAINED MD5 CODE FOR FILE
_duplicated = []   #CONTAINED DUPLIATED
_duplicated_sravnqva = [] #NEED FOR ZIP
subdirlist = []    #MAY DELETED IF YOU WON USED FOR FUNCTION search_file
one= []      #ADD FILEDPUPLICATES
two= []      #ADD MD5 FOR DUPLICATE FILE

 #SEARCH WITH OS.LISTDIR NOT WORKING FOR MOMENT
 # def search_file(Dir):
 
 #  for file in os.listdir(Dir):
 #   if os.path.isfile(file):
 #    yield os.path.join(Dir,file)
 #   else:
 #    subdirlist.append(os.path.join(Dir, file))
 #    try:
 #     for subdir in subdirlist:
 #      search_file(subdir)
 #    except:
 #     print "Somting wrong"

 #SEARCH WITH OS.WALK
def search_os_walk(Dir):
  for path,dirlist,filelist in os.walk(Dir):
    for fn in filelist:
      if fn.endswith("."+extension):
        try:
          yield os.path.join(path,fn)
        except IOError, e:
          print "Not allowed", e


 #FUNCTION USE FOR ENCRIPT FILE TO MD5
def md_5(filePath):
  try:
    with open(filePath, 'rb') as fh:
      m = hashlib.md5()
      while True:
        try:
          data = fh.read(8192)
          if not data:
            break
      m.update(data)
  except IOError, e:
    print "Not allowerd Basi", e
    return m.hexdigest()
  except IOError, e:
    pass


 #SEARCH FOR FILE AND APPEND THEM TO REQUIRED LIST (LOOKED ABOVE FOR DESCRIPTION'S )

for file in search_os_walk(Dir):

   _File.append(file)
   _File_H.append(md_5(file))


for f,z in (izip(_File, _File_H)):

   if z in _duplicated:
    _duplicated_sravnqva.append(z)
   _duplicated.append(z)


print "*"*80
_Dupliated =  [x[0] for x in zip(_File, _File_H) if x[1] in _duplicated_sravnqva]

for i in _Dupliated:

   one.append(i)
   two.append(md_5(i))

#RESULT IN DICTIONARI, NEEDED FOR FUNCTION GROUPBY
d = dict(zip(one,two))

di = sorted(d.iteritems(), key=itemgetter(1))
for k, g in groupby(di, key=itemgetter(1)):

 #IF YOU WHANT TO SHOW IN COLUMN UNCHECK BOTTOM ROW'S
      #~ for i,z  in enumerate(map(itemgetter(0), g)):
       #~ logging.info(str(i),(z))
   info = map(itemgetter(0), g)
   print "Duplicated ", info
   logging.info(str(info))
   print "\n"
answer = raw_input("Do you whant to view txt file with result (y/n) :")
if answer.lower() != 'y':
  pass
else:
  File = open('logfile.log')
  for line in list(File.readlines()):
    print line

23.03.2015 г.

Python use module logging to create log file.

import logging
import time

logging.basicConfig(filename='logfile.log', level=logging.DEBUG, \
format='%(asctime)s %(name)-5s %(levelname)-5s %(message)s', \
datefmt='%m-%d %H:%M')


def main():
    try:
       mathFail = 1/0
    except Exception, e:
        t=time.ctime()
            logging.info(str(e))

if "__main__" == __name__:
main()

Add aliace to program for windows

WinButton+R - >regedit

HKEY_LOCAL_MACHINE
SOFTWARE
Microsoft
Windows
App Path

->Create new key in right windows in Default String post path to exe. In the same window create
new StringValu with name "Path" and post path to exe

21.03.2015 г.

Direct change file with python use with use fileinput

1
2
3
4
5
6
7
8
import re
import fileinput
fname = "123.txt"
#( file has line: Ala bala 123)

for line in fileinput.FileInput(fname, inplace=1):
     line = re.sub(r'Ala bala \d{3}', "New Wine", line)
     print line

9.02.2015 г.

Изчисляване на рално ползваната рам чрез free -m

free -m | grep Mem: | awk '{print $3,$5,$6,$7}' | awk -F" " '{total=$1; sum=0; for(i=2; i<=NF; i++){sum+=$i}; print total-sum}'

Конфигурация на cron



0 9-18 * * * - Всеки час от 9 до 18 часа

0 9,18 * * * - По веднъж в 9 и 18

0 * * * * - Всеки Час

0 0 * * * - В 12 часа




* * * * *

1 - Минути (0-59)

2 - Час (0-23)

3 - Ден от месеца (1-31)

4 - Ден от годината (365)

5 - Ден от седмицата (0-7)

8.02.2015 г.

Запис на екрана чрез ffmpeg.

ffmpeg -f x11grab -s wxga -r 25 -i :0.0 out.mkv

vsftpd юзер без права за вход

Създаваме потребител:
useradd -g ftp -s /sbin/nologin ftp_user
passwd ftp_user

Ползваме за пример папка /var/ftp

usermod -d /var/ftp/ ftp_user

Във фаила добавяме най-отдолу, ако го няма:
/etc/shell

/sbin/nologin

Правата на папката са:
chmod -R 775 ftp
chown -R ftp_user ftp

Разкоментираме реда

write_enable=YES

във файла /etc/vsftpd.conf

8.01.2015 г.

Изтриване на паролата за вход в Windows.



Мапва се /sda1/windows/system32 /mnt

mv utilman.exe utilman.old && cp cmd.exe utilman.exe

След ребута: Win+U

c:\>net user alis wonderland /add

c:\>net localgroup administrators alis /add