суббота, 24 декабря 2011 г.

easy many machine ssh script


#!/bin/bash

[ -z $1 ] && cat -n /etc/machines|awk '{print $1".\t"$3}' && read num || num=$1
read ip name login pass port timeout <<< "$(head -$num /etc/mymachines |tail -1)"
# grep -v $ip ~/.ssh/known_hosts > ~/.ssh/known_hosts2
# mv ~/.ssh/known_hosts2 ~/.ssh/known_hosts
[ -n "$port" ] || port=33
[ -n "$timeout" ] || timeout=1
{
        sleep $timeout
        xdotool type "$pass"
        xdotool key Return
} &
echo "ssh $login@$ip -p $port"
ssh $login@$ip -p $port

/etc/machines

$ip $name $username $passwd $port $connection_timeout

10.80.140.4 test_machine root 123 33 2

вторник, 6 декабря 2011 г.

sshto


#!/bin/bash
NET=10.80.140.
PORT=33
ssh root@$NET$1 -p $PORT 2> /tmp/sshto
grep Offending /tmp/sshto && DEL=1
if [[ "$DEL" == '1' ]]; then 
LINE="$(grep Offending /tmp/sshto | cut -d ":" -f2)"
STRING="$(grep -n "" ~/.ssh/known_hosts | grep "^$LINE")"
STRING=${STRING/*:/}
grep -v "$STRING" ~/.ssh/known_hosts > ~/.ssh/known_hosts.tmp
mv ~/.ssh/known_hosts.tmp ~/.ssh/known_hosts
rm /tmp/sshto
ssh root@$NET"$1" -p $PORT > /tmp/sshto
else
[ -f /tmp/sshto ] && rm -f /tmp/sshto
fi

вторник, 25 октября 2011 г.

cd music && cat chaos|struktur


find -type f -name "*.mp3"|while read f; do
artist=`id3tool "$f"|grep -i artist|cut -d ":" -f2`
title=`id3tool "$f"|grep -i title|cut -d ":" -f2`
filename=`echo $artist - $title.mp3`
[[ "filename" != "-.mp3 ]] && mv "$f" "$filename"
done 

суббота, 22 октября 2011 г.

Console torrent search on the piratebay


#!/bin/bash
[ -z $1 ] && echo usage: iwant something && exit 1
search_item="$*"
search_item="http://thepiratebay.org/search/${search_item/ /%20}/0/7/0"
wget "$search_item" -O /tmp/searchitem.$$ 1>/dev/null 2>/dev/null
#cat /tmp/searchitem.$$|grep "Details for"|cut -d ">" -f3|cut -d "<" -f1|cat -n|head -10 && read f
#[ -z "$f" -o "$f" = '0' ] && rm -f /tmp/searchitem.$$ && exit 1
f=1
link="$(cat /tmp/searchitem.$$|grep "\.torrent"|cut -d "\"" -f2|head -$f|tail -1)"
echo "$link"
rm -f /tmp/searchitem.*

среда, 19 октября 2011 г.

Comicsia.ru comix downloader


#!/bin/bash

[ -n "$1" ] && comixname="$1"

mkdir "$comixname" && cd "$comixname"
basename="http://comicsia.ru"
wget "$basename/collections/$comixname" || exit 44
count="$(grep -o "d>.*ll.*[0-9]" ctrl-alt-del | tail -1 | cut -d ">" -f3)"
for ((i=1;$i<=$count;i++)); do
 mkdir "$i" && cd "$i"
 wget "$basename/collections/$comixname"/"$i"
 cat $i | \ 
 grep jpeg| \
 cut -d "\"" -f6| \
 while read file; do
  wget "$basename$file" &
  #  if you are kindle user, you need jpg, not jpeg
  #  use this code with power, young padawan
  #  also you must remove this line: 'mkdir "$i" && cd "$i"'
  #  and 'wget "$basename$file" &'
  #  filename="${file##*/}"
  #  filename="../${filename/jpeg/jpg}"
  #  wget "$basename$file" -O "$filename" &
 done
 rm "$i"
 cd ..
done

Специально для любителей листать комиксы на comicsia.ru
usage: ./scriptname ctrl-alt-del
ctrl-alt-del - название комикса.

вторник, 11 октября 2011 г.

воскресенье, 18 сентября 2011 г.

воскресенье, 11 сентября 2011 г.

Storm Interrupt detector


#!/bin/bash
echo "Try to detect storm interrupt..."
get_inter() {
 cpu_cnt=`cat /proc/interrupts|head -1|wc -w`
 read awkcpu <<< $(for i in `seq 2 1 $((cpu_cnt+1))`; do echo -n "\$$i\"\\\t\""; done)
 x=`awk "{print $awkcpu }" <<< "$(grep "^ *[0-9]" <<< "$(cat /proc/interrupts)")"`
 echo $x|tr ' ' '\n'
}
read -a arx <<< $(get_inter)
sleep 2
read -a ary <<< $(get_inter)
itcnt=$(($(wc -l <<< "$(get_inter)")-1))
for ((i=0;i<=$itcnt;i++))
do
 [ '20000' -lt "$((${ary[$i]}-${arx[$i]}))"] || exit 1
done
exit 1

среда, 7 сентября 2011 г.

Random music to player


#!/bin/bash
[ -z "$1" ] && path="/media/E30/Music" || path="$1"
shift
[ "$#" -gt 0 ] && p="(`echo $@ | tr ' ' "|"`)" || p="(front|coil|strip)"
find -name "*.mp3"|egrep -i -v "$p"|shuf|while read f; do
cp "$f" "$path" || break
clear
echo -e "$f...\t\t\t"
df "$path"|tail -1|awk '{print $5}'
done

пятница, 2 сентября 2011 г.

Getting interfaces speed

ip -o addr | grep [LE]eth.*inet | while read t f t; do echo -n $f" " && ethtool $f | grep Speed | sed -e 's/[^0-9]//g'; done

Output will be like:
eth0 1000
eth1 100

воскресенье, 21 августа 2011 г.

Unlimited random bash.org.ru quotes without advertisement


while true
do
w3m http://bash.org.ru/random/|egrep -v "(zadolbali|adview|смешно.*утверждена)"|sed '1,10d'|sed -e :a -e '$d;N;2,10ba' -e 'P;D' >> abyss
done

* смешно.*утверждена - (funny.*approved, russian)

^C
w3m abyss



вторник, 16 августа 2011 г.

Test duplicate gate interface address in local networks

ip -o addr|egrep "L.* inet"|
while read t eth t ip t
do
echo -n "Test duplicate address "${ip%%/*}" via "$eth": "
  RES=$(arping -D ${ip%%/*} -I $eth -c 1 2>&1)
[ $? = 0 ] && echo OK || echo FAIL
done

понедельник, 15 августа 2011 г.

Last.fm like insert

Execute it in your player root directory and get your charts like on last.fm :D


find -type f|sed -e 's/\.\///;s/ - .*//;s/[0-9]*\.//;s/.*\///;s/^\s//'|egrep -v "(mp3|html|jpg|jpeg|png|nfo|bmp|^[0-9])"|sort|uniq|awk '{print $ALL","}'|tr '[:upper:]' '[:lower:]'|while read f; do echo -n ${f^}" "; done; echo

пятница, 12 августа 2011 г.

ps in style of windows taskmgr

p="(`echo $@ | tr ' ' "|"`)"
ps axv|egrep "$p"|awk '{print $7"\t"$10}'|sort -nr

usage:

$ sh que.sh bash gnome
1181749 gnome-panel
523226 /usr/lib/gnome-settings-daemon/gnome-settings-daemon
334838 gnome-terminal
328194 /usr/lib/gnome-panel/wnck-applet
305068 /usr/lib/gnome-applets/trashapplet
299039 gnome-session
299035 gnome-session
299035 gnome-session
275984 /usr/lib/gnome-panel/notification-area-applet
272433 /usr/lib/policykit-1-gnome/polkit-gnome-authentication-agent-1
181419 gnome-screensaver
179311 gnome-session
108883 /usr/bin/gnome-keyring-daemon
98892 /usr/lib/gdm/gdm-simple-slave
28520 bash
26377 /usr/bin/dbus-launch
14612 gnome-pty-helper
14187 egrep
12092 /usr/bin/ssh-agent
4120 sh

четверг, 11 августа 2011 г.

Simple examples of grep (egrep, fgrep)

#!/bin/bash
echo -n 'Enter word: '
read word

#in all params of script calling
for i in $@                            
do

        #looking for word at the beginning of string

egrep ^$word $i  
        #looking for word at the end of string
        egrep $word$ $i
        #looking for strings without words windows, dos OR gates



        egrep -v "(windows|dos|gates)"         
done

среда, 10 августа 2011 г.

понедельник, 8 августа 2011 г.

SCP Example

scp -P 33 root@192.168.5.1:/var/backup/db/daily_2011-08-09_04-12.gbk ~/backup.gbk

33 - ssh port of remote machine
192.168.5.1 - remote machine address
/var/backup/db/daily_2011-08-09_04-12.gbk - remote file to download
~/backup.gbk - local file to save


scp -P 33 backup.gbk root@192.168.8.1:/var/backup/db/daily_2011-08-09_04-12.gbk

33 - ssh port of second remote machine
192.168.8.1 - second remote machine address
/var/backup/db/daily_2011-08-09_04-12.gbk - remote file to save
backup.gbk - local file to upload

четверг, 4 августа 2011 г.

Fast change mac-address via bash

#!/bin/bash
export mac=`ifconfig|grep eth0|tr -s ' '|cut -d ' ' -f5`
export command=""
if [ "$mac" != "52:54:00:e4:55:46" ]
    then command="ifconfig eth0 hw ether 52:54:00:e4:55:46"
    else command="ifconfig eth0 hw ether 52:54:00:e4:55:47"
fi
ifconfig eth0 down
sleep 1;
$command
sleep 1;
ifconfig eth0 up

понедельник, 1 августа 2011 г.

пятница, 29 июля 2011 г.

Periodic screenshots of desktop in ubuntu

while true; do sleep 10; scrot; done

As u see it's sooooooo simple =)

Mikrotik gate setup (example)

setup
a
ether2
10.80.140.1/24
a
ether1
10.80.1.140/16
g
10.80.1.1
ip dns edit servers
10.80.1.1
8.8.8.8
CTRL+O
ip firewall nat add chain=srcnat action=masquerade out-interface=!ether2
ip firewall filter add chain=forward dst-address=10.80.140.5/24 action=accept
ip firewall filter add chain=forward src-address=10.80.140.5/24 action=accept

суббота, 16 июля 2011 г.

AVI to SMV in linux

Buy cheap iRiver and wonna look video with it?
Oh, shi~, you're linux user?

smv_encode -b -g 127x159 -f 11 -n 5 -r -1 -q 84 "/home/username/The.IT.Crowd.s04e05.rus.LostFilm.TV.avi" "/home/username/workfuckingbitchfasternowbleat.smv"

вторник, 24 мая 2011 г.

Convert folder of docx/pptx to folder of doc/ppt

You're need:

  • linux
  • bash
  • openoffice/libreoffice
  • python
  • hands

soffice -headless -nofirststartwizard -accept="socket,host=localhost,port=8100;urp;StarOffice.Service"
sleep 1
test -d 2003||mkdir 2003
find -type f -name "*.docx" -exec python DocumentConverter.py {} {}.doc \;
find -type f -name "*.pptx" -exec python DocumentConverter.py {} {}.ppt \;
mv *.ppt *.doc 2003/
killall soffice.bin

DocumentConverter.py is avaible here.

How to use it:

  1. Create some folder here you will put your docx/pptx
  2. Put here DocumentConverter.py and this script
  3. Put here some docx/pptx files
  4. Run this script
  5. Go to folder 2003
  6. Get your doc/ppt
  7. ???
  8. PROFIT!
Also, to clean this folder from temp doc,docx,ppt,pptx files you can use this script:

find -name "*.doc" -exec rm -f {} \;
find -name "*.docx" -exec rm -f {} \;

среда, 18 мая 2011 г.

Debian

Get it:
p7zip unrar geany pidgin thunderbird chromium-browser gimp tilda

Purge it!
empathy empathy-common nautilus-sendto-empathy evolution evolution-common evolution-couchdb evolution-exchange gwibber gwibber-service libgwibber0 tomboy

понедельник, 25 апреля 2011 г.

Java: how to test, run or not some process in your system?

public static boolean isRunning(String procName) {
    boolean found=false;
    String command="";
    if (System.getProperty("os.name").contains("Windows")) {
        command="tasklist";
    } else {
        command="ps ax";
    }
    try {
        Runtime r = Runtime.getRuntime();
        Process p = r.exec(command);
        p.waitFor();
        BufferedReader br = new BufferedReader (new InputStreamReader (p.getInputStream()));
        while (br.ready()) {
            if (br.readLine().contains(procName)) 
                 found=true;
        }
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        return found;
    }
}

понедельник, 18 апреля 2011 г.

How I get eth0 ip address

hostname -I|sed -e 's/\s.*//g'

If you have any better idea - write it in comments please. Also, if anybody knew how to get external ip address, write it too.

Updated:
ifconfig eth0|grep 'inet '|sed -e 's/[A-Z,a-z,:]//g;s/^\s*//g;s/\s.*//g'

if you're get fear from regexp:

ifconfig eth0|grep 'inet addr'|sed -e 's/[A-Z,a-z,:]//g'|awk '{print $1}'

пятница, 8 апреля 2011 г.

How to get domain administrator privilegies in Windows Server 2003 / 2008

That we need:
  1. Physical access to the server
  2. ERD Commander CD (or other with Locksmith utility)
  3. Head + Hands
Your actions:
  1. Insert CD and boot from ERD Commander
  2. Use locksmith to get privilegies of local administrator
  3. Reboot
  4. Boot windows server in directory restore mode
  5. Login with your local admin username and password
  6. Put cmd.exe, srvany.exe and instsrv.exe in C:\tools (or some other directory)
  7. Run cmd.exe
  8. cd C:\tools
  9. instsrv PassRecovery C:\tools\srvany.exe
  10. Set autorun to this service (in Settings panel or write services.msc) (PassRecovery)
  11. Run regedit
  12. Create subfolder Parameters in HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\PassRecovery
  13. Add keys (String): Application (C:\tools\cmd.exe) and AppParameters (/k net user administrator (name of domain administrator) Pa$$w0rd (new password, must be match to security policy) /domain)
  14. example: /k net user admin Pa$$w0rd /domain
  15. In service settings in tab log on enable checkbox Allow Service to interract with desktop, apply.
  16. Reboot
  17. Run
  18. Enjoy.

четверг, 10 февраля 2011 г.

Convert ogv to avi in linux

You need in:
  • mencoder
  • linux
Open terminal emulator, write:

mencoder -idx input.ogv -ovc lavc -oac mp3lame -o out.avi

where:
  • input.ogv - your ogv video file
  • output.avi - avi file, that you want to get.

воскресенье, 23 января 2011 г.

GTK, Windows or other LookAndFeel

public static void setLookAndFeel() {
try {
  UIManager.setLookAndFeel(new GTKLookAndFeel());
} catch (UnsupportedLookAndFeelException ex) {
  try {
    UIManager.setLookAndFeel(new WindowsLookAndFeel());
  } catch (UnsupportedLookAndFeelException e) {
     try {
       UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
     } catch (Exception exc) {
       throw new RuntimeException(exc);
     }
   }
 }
}

среда, 5 января 2011 г.

Модификация Ubuntu LiveCD

Потребуются:
  • 3-5гб свободного места
  • 512мб оперативной памяти
  • squashfs-tools
  • genisoimage, mkisofs
  • Ядро с поддержкой squashfs
  • Виртуальная машина для тестов
  • Образ Ubuntu Desktop
Итак, приступаем:
sudo apt-get install squashfs-tools genisoimage
mkdir ~/livecdtmp
mv $ubuntu_iso_image ~/livecdtmp
cd ~/livecdtmp
mkdir mnt
sudo mount -o loop $ubuntu_iso_image mnt
mkdir extract-cd
rsync --exclude=mnt/casper/filesystem.squashfs -a mnt/ extract-cd
sudo unsquashfs mnt/casper/filesystem.squashfs
sudo mv squashfs-root edit
sudo cp /etc/resolv.conf edit/etc/
sudo cp /etc/hosts edit/etc/
sudo mount --bind /dev/ edit/dev
sudo chroot edit
mount -t proc none /proc
mount -t sysfs none /sys
mount -t devpts none /dev/pts
export HOME=/root
export LC_ALL=C

Сейчас можно издеваться над дистрибутивом как вам угодно, вырезать у него пакеты, обновлять их, в общем время кастомизации настало. Для удобства вот пара команд:

dpkg-query -W --showformat='${Installed-Size}\t${Package}\n'|sort -nr|less
Выводит все установленные пакеты упорядочив их по уменьшению занимаемого размера

apt-get purge package-name
Удаление пакета

man gconf
Информация по настройке Gnome

После завершения издевательств над системой рекомендуется всё за собой подчистить:
aptitude clean
rm -rf /tmp/* ~/.bash_history /etc/resolv.conf /var/lib/dbus-machine-id

Теперь отцепляем все маунты и делаем ISO-образ
umount /proc
umount /sys
umount /dev/pts
exit
sudo umount edit/dev
chmod +w extract-cd/casper/filesystem.manifest
sudo chroot edit dpkg-query -W --showformat='${Package} ${Version}\n' > extract-cd/casper/filesystem.manifest
sudo cp extract-cd/casper/filesystem.manifest extract-cd/casper/filesystem.manifest-desktop
sudo sed -i '/ubiquity/d' extract-cd/casper/filesystem.manifest-desktop
sudo sed -i 'casper/d' extract-cd/casper/filesystem.manifest-desktop
sudo rm extract-cd/casper/filesystem.squashfs
sudo mksquashfs edit extract-cd/casper/filesystem.squashfs -b 1048576
sudo vim extract-cd/README.diskdefines
cd extract-cd
sudo rm md5sum.txt
find -type f -print0|sudo xargs -0 md5sum|grep -v isolinux/boot.cat|sudo tee md5sum.txt
sudo mkisofs -D -r -V "$IMAGE_NAME" -cache-inodes -J -l -b isolinux/isolinux.bin -c isolinux/boot.cat -no-emul-boot -boot-load-size 4 -boot-info-table -o ../имя_нового_образа.iso

Собственно образ готов. Можно его протестировать в виртуальной машине, можно нарезать:

cdrecord dev=/dev/cdrom имя_нового_образа.iso

Источник: https://help.ubuntu.com/community/LiveCDCustomization