Fun with mencoder and mkv 
January 20th, 2008Category: My Life, ArticlesNo Comments
About a week ago I had to save two DVD disks on my hdd and instead of wasting 9GB of disk space I started playing with mencoder. I looked a lot on the internet, lots of options, lots of ways to do it… it not very easy. In the end I decided on the following:
- x264 video codec
- mp3 audio codec( in my case, the audio wasn’t important, otherwise I would’ve decided on AAC)
- mkv container
- mencoder, mkvtools and ogmtools for the procedure
Here are the commands.
Info about the chapters and ripping the title on the HDD:
dvdxchap -t 1 /dev/dvd > 1.chapters
mplayer dvd://1 -dumpstream -dumpfile 1.vob
First pass only analyzes the video and writes a log file for the second pass:
rm *.log #remove old logs
mencoder -v 1.vob \
-alang en \#language english
-vf yadif \#yadif deinterlacer
-ovc x264 \ #codec x264
-x264encopts subq=4:bframes=4:b_pyramid:weight_b:pass=1:psnr:bitrate=1800:turbo=1 \ #1800 bitrate gives a good size to qualit ratio
-oac copy \ #for now only copy the audio
-ofps 24000/1001 \#approx 23.9 fps
-slang en \
-o /dev/null
Second pass:
mencoder -v 1.vob \
-alang en \
-vf yadif \
-ovc x264 \
-x264encopts subq=5:partitions=4x4:8x8dct:frameref=3:me=hex:bframes=4:b_pyramid:pass=2:psnr:bitrate=1800 \
-oac mp3lame \ #mp3lame audio codec
-lameopts abr:br=256:vol=7 \ #256kbits bitrate
-ofps 24000/1001 \
-o 1.avi #write everything as avi for now
At this stage we have a perfectly working AVI at around 1800MB per 4.3GB DVD. I, however, want the chapter information from the DVD. The next step for me is to open the DVD and start going trough the chapters and editing the titles in the 1.chapters file from Chapter 01 Chapter 02… to something that makes more sense.
Then I merge the audio and video from the .avi and the chapter information in one .mkv file:
mkvmerge --title "Title of the DVD" -o 1.mkv --chapters 1.chapters 1.avi
After I make sure that 1.mkv works, I cleanup:
rm -rf 1.vob 1.avi 1.chapters *.log
That’s it. The .mkv file supports multiple tracks of audio, subtitles and many more.
There could be a better way to do all this, but this worked for me.
Hacks and tips on the LG VX8550 (Chocolate v2) from Verizon 
July 31st, 2007Category: My Life, Articles28 Comments
The following information is provided for educational purposes and does not represent the views of my employer. If you intend to use it in any illegal way, please leave this website!!!
Tools:
LG VX8550 from here
BitPim from here
0xED from here
MacBook from here
*nix server with Squid (optional)
Unlocking WAP
To unlock the WAP functions you need to edit one file and a proxy server. The server could be yours or a public proxy. It doesn’t matter much.
Here are the steps:
Configuring your phone and laptop to talk via Bluetooth:
- Open Bluetooth Setup Assistant ( From the Bluetooth, choose Set up Bluetooth Device)
- Click Continue, choose Mobile Phone without clicking Continue
- Go to Menu-> Settings & Tools -> Bluetooth Menu on you phone and choose Options with the right button. Select Discovery Mode and say Yes to the question Turn Bluetooth power on, if it asks, and change the mode to On.
- Now click Continue on your Bluetooth Setup Assistant. Wait a few seconds for the phone to show up.
- When the phone is found it will show up as LG VX8550. Select it and click Continue
- Look at your phone again. It will ask you “Pairing request from
Compter. Accept?” Select Yes.>the_name_of_your_computer> - Now click Continue in Bluetooth Setup Assistant and you will see an authorization number.
- At the same time, your phone will ask you for the same number. Enter it and click ОК. If everything went well, the phone will say “Paired successfully”. Hold a few seconds and select “Always Connect” when asked “Before connecting”.
- Look again at Bluetooth Setup Assistant. Select “Use with Address Book”, “Access the Internet with your phone’s data connection” and “Dial a specific number for your Internet Service Provider”. Continue.
- Fill in the fields as follows:
- Username: your phone number + @vzw3g.com. If your number is 212-221-1221, then the Username will be 2122211221@vzw3g.com.
- Password: vzw
- Phone Number: #777
- Modem Script: Verizon Support (PC 5220)
- Select only Show Bluetooth status in the menu bar and Show Modem status in the menu bar
- Click Continue and then Quit
Unlocking with BitPim:
- Run the latest version of BitPim.
- Go to BitPim->Preferences.
- For Phone Type select LG VX8550
- For Com port enter /dev/cu.LGVX8550-BTDIAG-1 and click OK
- From the View menu click on View Filesystem
- Now click on File System in the left panel and go to directory OWS
- With the right button click on the file paramtable1.fil and choose Save. Save the file somewhere. Save it one more time somewhere else for backup
- Start 0xED and open one of the two paramtable1.fil
- At the start of the file you should see: 30 1E 00 01 . Change the third pair to 20, to end up with 30 1E 20 01.
- Save and close the file.
- In BitPim again right click on the file paramtable1.fil and select “Overwrite”
- Navigate to the file you just edited, select it and click on Open
- When the light on the bottom left corner is green, right click below the files and select Reboot Phone.
- When the phone is on again dial:##77647268550 which comes from ##program8550 and press Send. The password is 000000.
- From the menu go to Wap Settings->Proxy Address Setting
- Now you must enter your proxy.
- Change the port of the proxy from Wap Settings->Proxy Port Setting
- You can change the Username and Password if your proxy requires it.
- I advise you to change your Home Page to http://www.humpa.com/homepage
At this stage you should be able to setup a shortcut News & Info and to use it to go to http://www.humpa.com/homepage
Setting up the phone as a modem
If you have not done so, please go through the steps in “Configuring your phone and laptop to talk via Bluetooth”. After that all you need to do is:
Disable unsupported authorizations:
- Open Termina.app
- type: sudo pico /etc/ppp/options hit Enter and enter your password
- type in the following three lines :
refuse-chap
refuse-mschap
refuse-mschap-v2 - Press ctrl+o and hit Enter, then ctrl+x and close Terminal.app
Now go to the program menu by dialing :##77647268550 which is ##program8550 and click Send.The password is 000000. From the menu Network Select->Mode Preference select 1X Only. Press ОК and you are ready to use your phone as a modem anywhere you have signal at the price of a phone call. To connect, go the the phone icon on your menu and select Connect. If everything went well, you should be online in a few seconds.
Unlocking EVDO
Without EVDO both your WAP and your phone will be limited to about 17KB/s. To unlock the power of the 3G network follow the steps in “Configuring your phone and laptop to talk via Bluetooth” and do the folowing:
- Run the latest version of BitPim.
- Go to BitPim->Preferences.
- For Phone Type select LG VX8550
- For Com port enter /dev/cu.LGVX8550-BTDIAG-1 and click OK
- From the View menu click on View Filesystem
- Now click on File System in the left panel and go to directory /nvm/nvm
- With the right button click on the file nvm_data and choose Save. Save the file somewhere. Save it one more time somewhere else for backup
- Start 0xED and open one of the two nvm_data
- At the bottom of the file you will see XXXXXXXXXX@dun.vzw3g.com on two places, with XXXXXXXXXX being your phone number. Now you have to change the dun.vzw3g.com part to vzw3g.com. It is very important not to delete anything, but just overwrite and add 00. If you select dun.vzw3g.com you will see on the left that you’ve selected: 64756E2E767A7733672E636F6D. In order to not change the size of the file change these with:767A7733672E636F6D00000000. On the right you should see how one of the dun.vzw3g.com is now vzw3g.com. Repeat with the second dun.vzw3g.com
- Save and close the file.
- In BitPim again right click on the file nvm_data ( in /nvm/nvm ) and select “Overwrite”
- Navigate to the file you just edited, select it and click on Open
- When the light on the bottom left corner is green, right click below the files and select Reboot Phone.
- When the phone is on again dial:##77647268550 which comes from ##program8550 and press Send. The password is 000000.
- From the menu go to Network Select->Mode Preference
- Then select Digital Only Hybrid and click OK
If you see ЕV and 1x in the signal strength field of your phone, than you have EVDO in your area. Now when you connect to the internet, through the modem or through WAP, you will use speed of up to 70KB/s
Please be careful what traffic you generate.Both volume and type.
More soon…
Reading for you: http://howardforums.com/forumdisplay.php?f=295
Храна
June 29th, 2006Category: My Life, Recipies, Articles13 CommentsОт около 1 седмица съм се зачел по разни страници за храни и диети. За тези, които не знаят, диета не значи да не ядеш, а да ядеш определени неща, в определено време с точна цел. Целта може да е напълняване (мускулна маса в повечето варианти), отслабване (намаляване на мазнини в повечето варианти) или просто поемане на нужното количество хранителни вещества за запазване на формата на тялото и за здраве.
Енергия/Калории
Докато човек е жив, той гори енергия. Независимо какво прави. И да лежи, и да спи, и да тича, енергия е нужна на тялото.
Има много формули за изчисляване на количеството енергия (калории) нужди на тялото.
За изчисляване на нужната енергия в покой се ползват следните формули:
Метод 1: Уравнение на Харис-Бенедикт
BW = Тегло в килограми, HT = Височина в сантиметри, Възраст в години, RMR = нужни калории в покой на ден (колко калории ще изгори тялото за 1 ден ако само почива)
Мъже: RMR = 66.473 + (13.751*BW) + (5.0033*HT) - (6.755*Възраст)
Жени: RMR = 655.0955 + (9.463*BW) + (1.8496*HT) - (4.6756*Възраст)
Метод 2: (Като горното но в американски мерни единици)
Мъже: 66+ (6.22 x тегло (паундове)) + (12.7 x височина (инчове)) - (6.8 x възраст)
Жени: 655 + (4.36 x тегло (паундове)) + (4.32 x височина (инчове)) - (4.7 x възраст)
Метод 3: Бърза формула за изчисляване
Мъже: BW * 24.2
Жени: BW * 22.0
Метод 4: Метод с маса без мазнини
RMR = 1.3 * Чиста маса (без мазнините) в килограми * 24
От тук можете да си изчислите колко калории ви трябват за да може тялото ви да … спи
От тази цифра, в зависимост от това колко сте подвижни през деня, можете да определите колко ще са нужните калории за да прекарате деня. Ето как:
| Ежедневие | фактор |
| заседнало, предимно в леглото | 1.2 - 1.3 |
| без планирани занимания, предимно работа в офиса | 1.5 - 1.6 |
| малко ходене и качване на няколко стълби на ден | 1.6 - 1.7 |
| тежък физически труд | 1.9 - 2.1 |
И така. След като имате калориите нужни за задържане на текущото тегло, можете да изчислите какво ви липсва или ви е в излишък. Примерно ако сте 100кг а искате да сте 90, заместваме теглото по-горе от 100 на 90 и ще видим колко калории трябва да ядем за да стигнем това тегло. Същото важи и в обратната посока.
Има един тънък момент. Ако в момента ядете по 4000калории на ден а трябва да свалите на 2500, много е важно това да се прави постепенно. Същото е вярно и в двете посоки. Ако искате от 1500 калории да качите на 3500, не започвайте от следващия ден да ядете с 2000 калории повече. Целта е на седмица да се регулират калориите с не повече от 500. Така тялото няма да се изпада в паника и да започне да запазва мазнини.
След като си имате цел (било тя да си задържите теглото) трябва да се определят колко от тези калории да са от протеини, мазнини и въглехидрати.
Протеини
1г протеин = 4 калории
Протеините са суровият материал на мускулната маса. Важно: Жените да не се шашкат като четат за мускули, на тях също им трябват протеини и за предпочитане мускули пред мазнини. Дори е добре да вдигат тежести за да развиват мускули и да топят мазнини. Не се притеснявайте, няма да станете с изпъкнали мускули като жените бодибилдърки. Нормалното женско тяло не произвежда достатъчно тестостерон за да направи такива мускули. На темата… протеините са много важни за мускулната маса. Има няколко вида протеини. Такива които се усвояват бързо и такива които се усвояват бавно. Първите са предимно протеин от суроватка (това дето изтича като се прави сирене), а вторите са казеинови протеини (разни млека и сирена). Казеиновият протеин е добре да се поема вечер, за да даде достатъчно материал на тялото докато спи(моментът, когато хормонът на растежа се отделя и тялото расте). Суроватковия протеин е много добър след някакво физическо натоварване, защото между 20 и 40 минути той е усвоен от тялото.
Но колко протеин? Пак зависи от целта.
Грам протеин на килограм тегло на ден:
Възрастен със заседял живот 0.88
Възрастен спортуващ за здраве 1.66
Възрастен състезател атлет или бодибилдър 2
Атлет на правилна диета 2.2
Растящ атлет тинейджър 2.2
Мазнини
1г мазнини = 9 калории
Мазнините трябва да са около 30% за здраве или 15-20 процента от калориите за оптимално тяло. Колкото и да е странно мазнините са нужни на тялото. Но не и в излишък. По-късно ще поговорим какви мазнини да се вземат. За сега ако имаме диета от 2500 калории, 750 от тях трябва да са мазнини ако не се стремим към нещо специално или 400-500 ако искаме хубаво тяло. Разделяме на 9 и получаваме колко грама мазнини са ни нужни на ден.
Въглехидрати
1г въглехидрати = 4 калории
Въглехидратите са веществата, които дават енергия на тялото.
След като вече имаме протеините и мазнините останалото е за въглехидратите.
150г протеин х4 е 600 калории. + 600 от мазнини са 1200. Останалите калории са за въглехидратите.
Като цяло можете да си разпределите калориите в някакво съотношение протеини/въглехидрати/мазнини. Доста хора препоръчват 30/50/20 или 25/60/15. Всички номера са доста лични и могат леко да варират от човек до човек, но с времето, следейки диетата си и номерата си (тегло, размери т.н.) можете да прецените какво ви трябва повече и какво по-малко.
Едно нещо е важно: Не трябва да има излишък или недостатък на нито едно от веществата.
Но не всички мазнини имат една и съща хранителна стойност и не всички въглехидрати. Нито протеини. Трябва внимателно да се подбират продуктите за дадено ядене. Има много различни теории и методи за здравословно хранене, но всички те си приличат по едно. Добри и лоши източници на хранителни вещества. Ето ги и тях.
Здравословно хранене
И така, определили сме си колко протеини, въглехидрати и мазнини да ядем. Но от къде да ги вземем? За съжаление не можем да отидем в магазина и да кажем: “Може ли 100г млечен протеин, 20грама мазнини от фъстъци и 200 грама овесени въглехидрати”, а би било яко…
До тогава, трябва сами да си издокарваме диетите.
Вода
Едва ли ще успея достатъчно да наблегна на водата. Това е най-важното вещество, което ни е нужно. Вода трябва да се пие в изобилие. До такава степен, че като ходите да ви се люшка в корема. Много е важно водата да се пие постоянно. И по много, разбира се. На ден трябва да се изпиват по 3-4 литра вода, ако искате да имате хубаво тяло. Важното е да не спирате потока от вода към тялото. Винаги имайте до себе си бутилка с чиста вода и си пийвайте. На всяко ядене изпивайте по 2-3 чаши вода. Без да се притеснявате. Така няма да се тъпчете с храна и ще помагате на организма. За тези, които пият алкохол, това е още по-важно. Алкохола е голям противник на водата. Ако пиете алкохол, пийте и много вода, не за да не ви влияе алкохола, а за да предоставите на тялото колкото му е нужно.
Честота на хранене
Много хора са свикнали с традиционните 3 ястия на ден, като много дори и до там не го докарват. Всички проучвания показват, че яденето 5-6 пъти на ден е много по-здравословно и храната се усвоява от организма много по-добре. Затова, яжте всеки 3-4 часа, без да се притеснявате. Разбира се, яденето трябва да е в рамките на по-горните числа за вас. Не да се тъпчете по 6 пъти на ден с по 2-3 банички. Така няма да я докарате далеч.
Протеини
Добри източници на протеини са:
Риба тон, Сьомга, Пилешки гърди, Телешко, Свински пържоли, Пуешко и Яйца.
Доста книги препоръчват да се избягва телешкото и свинското и да се набляга на пернатите мръвки и рибата. Също така, някои казват, че в яйцата има много холестерол (в жълтъка), но според американската здравна асоциация, по 1 яйце на 2 дена е здравословно.
Соята и млечните продукти също са добри източници на протеин, за тези, които не ядат месо.
Мазнини
При мазнините е малко сложно. И то защото не знам как как да кажа на български съответните термини, но ще опитам.
Трябва да се избягват т.нар. trans и saturated мазнини. Нямам идея как се водят на .бг но ще знам в кои продукти ги няма.
Добри източници на хубави мазнини са:
Ядки, Риба, Натурално фъстъчено масло, семена, зехтин, девствен зехтин, канолиево олио, олио от ленено семе, рибено олио, соево олио, авокадо и сурова риба.
Избягвайте белите неща по месото (лоша мазнина). Агнешкото и патешкото са мазни меса и протеините на са толкова добри в тях.
Въглехидрати
При въглехидратите има 2 вида. Прости и и сложни. Простите въглехидрати са полезни само след някакво физическо натоварване за бърза енергия. През останалото време трябва да се избягват. Те са:
Декстроза, Плодове, Захар, Сироп от царевица с много фруктоза, Спортни напитки, Бонбони и т.н.
Едно изключение тук са плодовете. Яжте плодове без да се притеснявате.
Сложните въглехидрати бавно се разграждат в тялото и не предизвикват скок в нивото на инсулин (което предизвиква съхраняване на мазнини). Те са идеални за хубаво хранене.
Ето и храни със сложни въглехидрати:
Кафяв ориз, 100% пълнозърнен хляб, Овес, Макарони, Спагети, Бобове и Зеленчуци
Добри източници на въглехидрати са:
Плодове, овесена каша, пънозърнен хляб, картофи (не пържени), бобове, кафяв ориз, леща, 100% сокове и всички зеленчуци
Какво да избягваме
Избягвайте бонбони, сладолед, картофен чипс, пица, храни с много захар като понички, бял хляб, мазно сирене, червено месо и т.н.
Като цяло, когато се планира една диета, гледайте да ядете повечко въглехидрати в началото на деня и по-малко накрая. Последното голямо ядене да е поне 2 часа преди лягане и последният 1 -1.5 часа преди лягане не пийте много течности, защото е много важно да се наспивате всяка вечер. Поне 8 часа СЪН!
Пожелавам ви успех и постоянство.
Самба и КЪПС
March 12th, 2006Category: My Life, ArticlesNo CommentsДнеска пристигна новичкият ни Samsung ML-2010 черно-бял лазерен принтер и исках да го превърна в мрежов принтер за да може всеки да го ползва. Така и така линукската машина стои постоянно включена вързах принтера към нея. Едно от хубавите неща на принтера е, че дойде с драйвери за Уиндоус, Мак и Линукс. Стартирах инсталационния скрипт и инсталирах драйверите. Конфигурационното инструментче, което дойде със СДто ми помогна да инсталирам принтера в КЪПС и да го конфигурирам. Нямаше никакви проблеми.
Аз използвам slackware linux и за да стартирам автоматично къпс-а трябваше да напиша като руут chmod +x /etc/rc.d/rc.cups. И така печата под линукс бе настроен. Но освен линукска машина, имаме и един iBook. Също така съквартиранта ми има Уиндоус. Поради тази причина, трябваше да инсталирам и конфигурирам SAMBA. Ето и конфигурационния сайт:
[global]
netbios name = Geodar
security = SHARE
passdb backend = guest
ldap ssl = no
hosts allow = 192.168.0.[share]
path = /mnt/D
read only = No
guest ok = Yes[ml-2010]
path = /var/spool/samba
guest ok = Yes
printable = Yes
use client driver = Yes
Това е.
Моят printers.conf за CUPS садържа :
<DefaultPrinter ML-2010>
Info Samsung ML-2010 Series (SPL II)
Location
DeviceURI usb:/dev/usb/lp0
State Idle
Accepting Yes
JobSheets none none
QuotaPeriod 0
PageLimit 0
KLimit 0
</Printer>
cupsd.conf е малко по-голям и няма да го публикувам целия, но за да мога да го администрирам от другите машини само добавих Allow From 192.168.0.* под всяко Allow From 127.0.0.1
рестаритрах cups
стартирах smbd
До тук добре. Следващата стъпка беше да инсталирам драйверите на лаптопа и на уиндоуса.
След като това мина без проблем трябваше да добавя самият принтер на машините. Под Уиндоус не е кой-знае каква философия. Просто отваряте линукската машина с Network Neighbourhoot и трябва да видите принтера. Натискате десния бутон в/у него и избирате Connect. След това има някви стандартни въпроси и сте готови.
Под Мак беше малко по-забавно. За да може да се инсталира самба принтер под мак, се стартира Printer Setup Utility (в System preferences, Print & Fax кликате на +).
В мего се натиска Option бутона и се клика на More Printers. Продължава се да се държи Option бутона докато не се избере Advanced от първия списък. На втория, тогава, се избира Windows Share. В обновилото се диалогче си въвеждаме името “Samsung ML-2010″ и адреса на принтера в следната форма “smb://192.168.0.109/ml-2010″ като адреса е този на линукса а името след него е името на споделения принтер в конфигурационния файл на самба. За драйвер се избира новоинсталирания Samsung Драйвер и готово.
Не ми отне много време, но пак имаше играчка тук и там. Сега всички могат да си разпечатват от техните компютри през 50 доларов принтер, който печата доста добре.
CUPS+SAMBA
March 12th, 2006Category: Work, Articles2 CommentsI just purchased a Samsung ML-2010 Mono Laser Printer and wanted to turn it into a network printer. Since my linux box is online 24/7 I connected the printer to it. Something good about it is that it came with drivers for linux. So I ran the installer in the CD and installed the drivers. Than I used the configuration tool provided with the CD to install and configure the printer. CUPS was happy with it. I use slackware linux so i just had to chmod +x /etc/rc.d/rc.cups and now my printing daemon starts on boot. So the linux printing was done. But I also have an iBook and my roomate has windows box. So I had to configure SAMBA. Here is my config file:
[global]
netbios name = Geodar
security = SHARE
passdb backend = guest
ldap ssl = no
hosts allow = 192.168.0.[share]
path = /mnt/D
read only = No
guest ok = Yes[ml-2010]
path = /var/spool/samba
guest ok = Yes
printable = Yes
use client driver = Yes
that’s it.
My printers.conf for CUPS is :
<DefaultPrinter ML-2010>
Info Samsung ML-2010 Series (SPL II)
Location
DeviceURI usb:/dev/usb/lp0
State Idle
Accepting Yes
JobSheets none none
QuotaPeriod 0
PageLimit 0
KLimit 0
</Printer>
cupsd.conf is a little bigger but all I did was to add Allow From 192.168.0.* below every Allow From 127.0.0.1
restarted cupsd
started smbd
and the next step was to install the driver on the windows and mac machines.
Installing the printer under windows is easy. Just browse the server IP(where the printer is connected) and you should see the shared printer. Right click on it and select connect. After it finishes updating/installing you should be good to go.
Under Mac OS X, however, was a little tricky.
After installing the driver I ran the Printer Setup Utility (in System preferences, Print & Fax and you click on the +).
Pressing and holding the Option key, click on More Printers. keep holding the Option key and on the first drop down menu select Advanced. On the second select Windows Share. Now you can releise the option key. In the dialog just enter the name for your printer “Samsung ML-2010″ in my case. Than in the address enter “smb://192.168.0.109/ml-2010″ < - the ip is the IP of the server and the ml-2010 is the name of the printer share in your samba configuration.
Than from the drivers select the allready installed Samsung Driver and you are all set.
Now everyone in our house can print from our small Samsung ml-2010.
Automatic Daily Backup with cpanel
November 11th, 2005Category: Articles1 CommentThis script is an updated version of the one posted by max.hedroom in cpanel.net forums. It supports scp/ftp uploads and remote directories. You can execute this script from you scp host,home computer or your host server. I’d suggest using it from your own machine since it contains plan text passwords!
All You have to do is save the following code to a .php file and add a cron job to execute the php file every tome you would like to have a full backup of your entire web page(emails, DBs, web files) on your own machine.
Enjoy
< ?php
// PHP script to allow periodic cPanel backups automatically.
// Based on script posted by max.hedroom in cpanel.net forums
// This script contains passwords. KEEP ACCESS TO THIS FILE SECURE!
// It is updated to support secure ftp connections and remote directories
// ********* THE FOLLOWING ITEMS NEED TO BE CONFIGURED *********
// Info required for cPanel access
$cpuser = "username"; // Username used to login to CPanel
$cppass = "password"; // Password used to login to CPanel
$domain = "www.host.com"; // Domain name where CPanel is run
$skin = "x"; // Set to cPanel skin you use (script won't work if it doesn't match)
// Info required for FTP/SFTP host
$ftpuser = "sshusername"; // Username for FTP(SCP) account
$ftppass = "sshpassword"; // Password for FTP(SCP) account
$ftphost = "sshhost"; // Full hostname or IP address for FTP(SCP) host
$ftpmode = "scp"; // FTP mode ("ftp" for active, "passiveftp" for passive, "scp" for secure ftp)
$ftpport = "22"; // PORT for FTP(SCP) host
$ftprdir = "/path/to/directory"; //Remote Directory on SCP host
// Notification information
$notifyemail = "mailto@somehost.com"; // Email address to send results
// Secure or non-secure mode
$secure = 1; // Set to 1 for SSL (requires SSL support), otherwise will use standard HTTP
// Set to 1 to have web page result appear in your cron log
$debug = 0;
// *********** NO CONFIGURATION ITEMS BELOW THIS LINE *********
if ($secure) {
$url = "ssl://".$domain;
$port = 2083;
} else {
$url = $domain;
$port = 2082;
}
$socket = fsockopen($url,$port);
if (!$socket) { echo "Failed to open socket connection!\n"; exit; }
// Encode authentication string
$authstr = $cpuser.":".$cppass;
$pass = base64_encode($authstr);
$params = "dest=$ftpmode&email=$notifyemail&server=$ftphost&user=$ftpuser
&pass=$ftppass&port=$ftpport&rdir=$ftprdir&submit=Generate Backup";
// Make POST to cPanel
fputs($socket,"POST /frontend/".$skin."/backup/dofullbackup.html?".$params." HTTP/1.0\r\n");
fputs($socket,"Host: $domain\r\n");
fputs($socket,"Authorization: Basic $pass\r\n");
fputs($socket,"Connection: Close\r\n");
fputs($socket,"\r\n");
// Grab response even if we don't do anything with it.
while (!feof($socket)) {
$response = fgets($socket,4096);
if ($debug) echo $response;
}
fclose($socket);
?>
Нови снимки
November 9th, 2005Category: My Life, Recipies, ArticlesNo CommentsСложих малко от новите снимки на галерията. Добавих снимки на Плеадите, на наводненията от дъжда и на един тиквички, които си правихме наскоро. За по-голямо удобство преместих албумите с новите снимки в началото на първата страница.
Rsync + ssh
June 27th, 2004Category: ArticlesNo CommentsI reserve the right to change the howto and I’ll not be held responsible if ANY
damage is caused by this how-to. If you don’t agree please do not use it! Thanks
The idea of this how-to is to help you deal with this situation:
Imagine you have server with let’s say 10 users. Your server is getting too old
and you want to upgrade it. A good system administrator will not just shut down
the old server work on the new one for few days and then bring it up. A better
solution would be to leave the old server runnin, build the new one, configure
the new one, copy user files from old one to new one and for few seconds just
switch the IPs of both servers.
Now the problem comes when users change their files after you have transfered
them to the new server but before you have switched the IPs.
In this howto I’ll give you set of commands to run and set a cron job that will
update your /home for example every hour without causing high trafic on the
network. Only the first time!
What you need is:
ssh(d) on both servers
rsync on both servers
OpenSSL on both servers
Let’s give some names to our servers:
New server = thunder(192.168.0.101)
Old server = light(102.168.0.100)
we have a bunch of directories in /home/ on “light” that we want to transfer to
/home/ on “thunder”
here is what we do:
SSH no password part:
login to thunder as root
execute:
thunder#mkdir -p /root/.ssh
thunder#chmod 0700 /root/.ssh
thunder#ssh-keygen -t dsa -f /root/.ssh/id_dsa -P ” (two single quotes)
now you will have two new files:
/root/.ssh/id_dsa(your private key)
/root/.ssh/id_dsa.pub(your public key)
login to light as root
execute:
light#scp 192.168.0.101:.ssh/id_dsa.pub .
light#cat id_dsa.pub >> /root/.ssh/authorized_keys2
light#chmod 0600 /root/.ssh/authorized_keys2
NOTE: you might have to do the same for /root/.ssh/authorized_keys
now try to login from thunder to light with the key:
from thunder execute:
thunder#ssh -i /root/.ssh/id_dsa 192.168.0.100
you should login to light without entering password
!WARNING!WARNING!WARNING!WARNING!WARNING!WARNING!WARNING!
if someone gains root access on thunder he will be able to ssh to light without
entering any password if he figures out that you have a key!
!WARNING!WARNING!WARNING!WARNING!WARNING!WARNING!WARNING!
if everything is OK let’s test it trough rsync:
create a directory on light and touch some files:
light#mkdir /home/testdir
light#cd /home/testdir
light#touch a
light#touch b
from thunder execute:
thunder#rsync -azx –delete –numeric-ids -e “ssh -i /root/.ssh/id_dsa” \
192.168.0.100:/home/testdir/ /home/testdir/
you should now see /home/testdir on thunder with a and b in it
now move a to c on light:
light#mv /home/testdir/a /home/testdir/c
execute the same rsync command on thunder:
thunder#rsync -azx –delete –numeric-ids -e “ssh -i /root/.ssh/id_dsa” \
192.168.0.100:/home/testdir/ /home/testdir/
now on thunder you should have /home/testdir/b and /home/testdir/c
the ownership will be preserved while the uid and gid on both thunder and light
match(and they should, but that other how-to
now go to /etc/cron.hourly on thunder and add the rsync line:
thunder# cd /etc/cron.hourly
thunder# echo “rsync -azx –delete –numeric-ids -e “ssh -i /root/.ssh/id_dsa” \
192.168.0.100:/home/ /home/” > rsync_home_update
And that’s it! Every hour thunder will sync its /home/ with /home/ on light
remember that both directories will be identical, that means if you have new
users on thunder that are not on light, their home directoreis will be deleted!
to avoid that, create /home/oldusers/ and sync /home/ on light to /home/oldusers/
on thunder. Don’t forget to move it later when you switch the servers or change
/etc/passwd on thunder to point to the correct home directories!
Good Luck
Software RAID + LILO
June 27th, 2004Category: ArticlesNo CommentsThis how-to is made to help you configure your software raid and boot your root from it.
I’m doing this on slackware 10 with updated udev and mdadm, kernel 2.6.11-rc4
first you need to make sure that your raid support is IN your kernel, not as modules.
here is my config:
/usr/src/linux# grep -i raid .config
# CONFIG_BLK_DEV_3W_XXXX_RAID is not set
# CONFIG_SCSI_AACRAID is not set
# CONFIG_MEGARAID_NEWGEN is not set
# CONFIG_MEGARAID_LEGACY is not set
# Multi-device support (RAID and LVM)
CONFIG_MD_RAID0=y
CONFIG_MD_RAID1=y
# CONFIG_MD_RAID10 is not set
# CONFIG_MD_RAID5 is not set
# CONFIG_MD_RAID6 is not set
I have a small /dev/hda1 partition that I used to install the system and configure the latest kernel.
here is how my two drives are partitioned:
~# fdisk -l /dev/hda
Disk /dev/hda: 160.0 GB, 160041885696 bytes
255 heads, 63 sectors/track, 19457 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Device Boot Start End Blocks Id System
/dev/hda1 * 1 255 2048256 83 Linux
/dev/hda2 256 498 1951897+ 82 Linux swap
/dev/hda3 499 3537 24410767+ fd Linux raid autodetect
/dev/hda4 3538 19457 127877400 fd Linux raid autodetect
/dev/hdc is the same.
so, I have /dev/hda1 as a boot partition
/dev/hdc1 as a temp root partition
/dev/hd[ac]2 for swap
/dev/hd[ac]3 for /
/dev/hd[ac]4 for /home
when you create your partitions use FD not 83 for partition type if you want your raid to be detected at boot later…
now just execute the following:
mdadm –create /dev/md0 –chunk=32 –level=1 –raid-devices 2 /dev/hd[ac]3
this will create a raid1 device for / on /dev/md0
mdadm –create /dev/md1 –chunk=32 –level=1 –raid-devices 2 /dev/hd[ac]4
and finally a /dev/md1 for the /home partition under raid1 again
Now you can observe /proc/mdstat. You’ll have something like:
~# cat /proc/mdstat
md1 : active raid1 hdc4[1] hda4[0]
127877312 blocks [2/2] [UU]
resync=DELAYED
md0 : active raid1 hdc3[1] hda3[0]
24410688 blocks [2/2] [UU]
[================>....] resync = 82.5% (20147072/24410688) finish=1.5min speed=46944K/sec
…
if you have problems with /dev/md* just use –auto after the –create instead of /dev/mdX
and mdadm will create md1 and md2 for your two raids (it will number them by the order of
execution of the mdadm –create command)
next:
mkreiserfs (or whatever fs you prefer) /dev/md0 (or md1 if you have used –auto)
our next task is to move the current installation on the RAID:
mkdir /mnt/newroot
mount /dev/md0(1) /mnt/newroot
cd /
now I use tar to move all my files, that way I’m sure it will preserve my links and perms.
in bash:
(cd /;tar cpf - ./bin ./dev ./proc ./sbin ./tmp ./var ./etc ./lib ./opt ./root ./usr ./sys)|(cd /mnt/newroot;tar xvpf -)
and watch
you might see some errors in /sys/ but that’s OK
now create home and boot:
mkdir /mnt/newroot/home
mkdir /mnt/newroot/boot
if you have more directories just put them in the list above. I had to use a list because I don’t want to move /boot
(separate partition) and /mnt
create /mnt/newroot/mnt/oldroot ![]()
now edit your /mnt/newroot/etc/fstab. Here is mine:
/dev/hda2 swap swap defaults 0 0
/dev/hdc2 swap swap defaults 0 0
/dev/md0 / reiserfs defaults 1 1
/dev/md1 /home reiserfs defaults 1 2
/dev/hda1 /boot ext2 defaults 1 2
/dev/hdc1 /mnt/oldroot reiserfs defaults 1 2
/dev/cdrom /mnt/cdrom iso9660 noauto,owner,ro 0 0
/dev/fd0 /mnt/floppy auto noauto,owner 0 0
devpts /dev/pts devpts gid=5,mode=620 0 0
proc /proc proc defaults 0 0
this should do the work.
and the last one:
vim /etc/lilo.conf
if you have something like:
image = /boot/bzImage-2.6.11
root = /dev/hdc1
label = Linux2.6
read-only
add another block:
image = /boot/bzImage-2.6.11
root = /dev/md0
label = Linux2.6RAID
read-only
run “lilo”
in this case your kernel will be the same. I assume you are doing the above work under your new kernel.
That means you have raid support
now reboot and choose Linux2.6RAID
Good Luck!
RTFM for Slackware (BG)
June 27th, 2004Category: ArticlesNo Comments< <<<< Tezi komandi sa za Slackware moje da ima razminavane v drugite OS>>>>>
apropos xxx - pokazva spisuk ot komandite v koito ima xxx
w - koi e lognat v momenta v sistemata
last - slisuk na poslednite logvali se v sistemata useri
lastb - slisuk na poslednite neuspeshno logvali se v sistemata useri
uptime - kolko vreme e rabotila sistemata sled posledniq reboot i oshte
nqkolko polezni informaciiki
ps - spisuk sus raboteshtite procesi
ps -aux - po-razbiraem spisuk s procesite
killall xxx - ubivane na procesite imashti vruzka s xxx
kill -9 xxx - ubivane na edin proces kudeto xxx e negoviq pid nomer
cat /etc/issue - pokazva distribuciqta
cat /etc/version - pokazva versiqta
cat file - pokazva sudurjanieto na “file”
lsmod - pokazva spisuk sus zaredenite moduli
ls - spisuk s direktoriite i failovete v tekushtata direktoriq
ls -all - podroben spisuk ——————- || —————
cp source destination - kopira “source” v “destination”
mv ———- || ——– - premestva ————- || ———-
ln -s ———— || —— - pravi simvolichna vruzka
mkdir xxx - pravi papka na ime xxx
rmdir xxx - iztriva papka na ime xxx
rm xxx - trie file na ime xxx
rm -rf xxx - trie file na ime xxx s razlika ot gore che tuk ne te pita i
go trie vednaga… ako e direktoriq trie vsichko v neq primer rm -fr / -
tova bi iztrilo celiq hard disk…
addusr - dobavq potrebitel (script s vuprosi)
tar - xzvf filename.tar.gz - razarhivirane na filename.tar.gz
tar - xvf filename.tar- razarhivirane na filename.tar
bunzip filename.bz2 - razarhivirane na filename.bz2
gunzip filename.gz - razarhivirane na filename gz
unzip filename.zip - razarhivirane na filename.zip
jobs - spisuk sus sprqnite i “background” procesite
fg xxx - produljavane na proces kudeto xxx e “job number”
lsof - pokazva otvorenite failove
lspci - pokazva informaciq za PCI kartite na mashinata
watch -n xx - povtarq komanda na vseki xx sekundi
modprove -l |more - pokazva modulite koito sa dostupni
modprobe modulename - zarejda avtomatichno modul s ime modulname
lsdev - informaciq za DMA, IRQ I\O
insmod module - zarejda modul s ime module
rmmod module - premahva modul s ime module
cd - change dir (sushtoto kato pod DOS)
passwd - smqna na parolata na tekushtiq user
ifconfig - nastroika i informaciq za mrejovite karti
ifconfig eth0 192.168.0.1 bcast 192.168.0.255 netmask 255.255.255.0 -
nastroiva interface eth0 sus ip 192.168.0.1, maska 255.255.255.0 i
broadcast adres 192.168.0.255
prekompilirane na qdro - komandi:
1. cd /usr/src/linux
2. make config
2. make menuconfig
2. make xconfig (pod X)
#izbira se edno ot gornite 3 za nastroika
3. make clean; make dep; make bzImage; make modules; make modules_install
4. cp arch/i386/boot/bzImage /boot/[ime na image-a]
5. mcedit /etc/lilo.cof - nastroika na bootmanager-a
6. lilo
7. reboot
chmod - smenq pravata
chown - smenq sobstvenik
chgrp - smenq grupata
chmod -u +w /temp/example - dava w (write) prava na sobstvennika na
/temp/example
chmod -u -w /temp/example - premahva w (write) prava na sobstvennika na
/temp/example
za gornite komandi:
-u - sobstvennik
-g - grupa
-o - ostanalite
-a - na vsichki
——————-
w - write prava
r - read prava
x - execute prava
gornite 3 opcii se slagat s + ili - v zavisimost ot todva dali sa davat ili otnemat suotvetnite prava za file (direktoriq)
Georgi’s Blog is proudly powered by
WordPress
Постове (RSS)
and Коментари (RSS).

22 queries. 0.732 seconds.

