Wednesday, November 24, 2010

Ubuntu desktop as a nas server

I had a spare Desktop in my basement with Ubuntu installed on it. So had, in past added a spare hard drive to it.So I decided to use it as my own Nas server. Use it to back up pictures, mp3s etc.

Here's a list of steps that I had to follow in order to finally set it up:


Step 1: Upgraded ubuntu to 10.4.

Step 2: By default ubuntu will be configured with DHCP. That's no good. Got to fix he ip address so the network drive mounts do not break everytime the server starts up.
  • The easiest way to do this is to edit /etc/network/interfaces (don't mess with the gui it was kinda flaky).
    --------------------------------
    auto eth0
    iface eth0 inet static
            address 192.168.1.100
            netmask 255.255.255.0
            network 192.168.1.0
            broadcast 192.168.1.255
            gateway 192.168.1.1
    -----------------------------------
    • edit /etc/resolv.conf. Add your DNS name servers here. Or just add 8.8.8.8 ( gooogle's free dns service)
    • now just restart networking: /etc/init.d/networking restart ( or sudo service networking restart)
    • >ifconfig should now tell you that the ipaddress has changed. ping google.com to make sure you are up and running. 
    Step 3:  Install samba.
    • The best resource that I found was this : http://ubuntuforums.org/showthread.php?t=202605.
    • Note that in the link above the setting "guest = ok". This will allow any user to access your samba share. It should be set to no.
    • Make sure that you set "security = user"  and "users = winuser, otheruser" . This will restrict the access to users who have password.
    Step 4: Map network drive in a windows machine.
    • You might have to change the windows firewall setting for it to be able to connect to your shared network via smb.
    • Use map network drive option in Windows explorer to map your machine. Use the following for folder:
    //192.168.1.100/media/
    • Click on the "Connect using a different user name". link. Enter usename and password.

    Tuesday, November 23, 2010

    Date in java difference anyone ?

    Turns out it not simple function call to get the difference between two dates and display the result is a nicely formatted output. I ended up doing this (With liberal help from google )



    import java.util.*;
    import java.text.*;


    public class Test1 {

    private static String getDateDifference(String format, Date d1, Date d2 ){
    long dl1 = d1.getTime();
    long dl2 = d2.getTime();

    long sec2Millisec = 1000;
    long minute2Millisec = sec2Millisec*60;
    long hour2Millisec = minute2Millisec*60;
    long day2Millisec = hour2Millisec*24;

    long diff = (dl2-dl1);
    long days = (diff)/(day2Millisec);
    diff = diff%day2Millisec;
    long hours = (diff)/(hour2Millisec);
    diff = diff%hour2Millisec;
    long mins = (diff)/(minute2Millisec);
    diff = diff%minute2Millisec;
    long secs = diff/sec2Millisec ;
    return String.format( format, days, hours, mins, secs);
    }

    public static void main(String[] args){

    try {
    Date d1 = new Date();
    Date d2 = new Date(d1.getTime() + 1113660*1000);
    System.out.println (Test1.getDateDifference(" %d days, %d hours, %d mins, %d secs", d1, d2));

    }catch (Exception e){
    System.out.println("err = " + e);
    e.printStackTrace();
    }

    }
    }

    Monday, June 21, 2010

    Search And View

    Simple script for searching a file and viewing it in one go:



    #!/bin/bash

    usage="$0 "
    if [[ $# -ne 1 ]];then
    echo $usage
    exit 1
    fi
    files=`find . -name "$1";`
    if [[ -z $files ]];then
    echo "$1 not found"
    fi
    count=0
    for f in $files; do
    ((count += 1))
    done
    echo "Found $count files matching $1"

    for f in $files; do
    echo $f
    echo -n "Enter [Open : y , quit : q , skip : any other char] "
    read ans
    if [[ $ans == "q" ]];then
    break;
    fi
    if [[ $ans == "y" ]];then
    vim $f
    break;
    fi
    done


    Tuesday, January 19, 2010

    Making cygwin work

    You usually try to recreate the environment that you are most comforatable with. So when I got my work laptop, one of the first things I did was to install cygwin. Now cygwin works pretty well for the most part, however its a disaster when converting between windows style and unix style of file paths. Then of course you discover cygpath command which does exactly that.

    Classpath for JAVA:

    However this does not fix you java classpath issues. I struggled with this for a long time till I found this: just make sure that the path separator is ";" and put a double quote around the classpath :

    cygwin > java -cp ".;./classpathdir/;dir" Test

    Using Console for cygwin

    If you have cygwin on the windows cmd console, then its time to switch to console (Yes its console, though I wish they could have dreamt up a better term just to avoid any confusion.) Its available at http://sourceforge.net/projects/console/. It's pretty lets you do multiple tabs , unlimited resizing etc. Best of all you can set cygwin bash as your default shell !!




    Use SSH instead of Putty

    If you have made is so far, why not open ssh instead of putty. Don't get me wrong. I love putty myself, however it doesn't have tabs (well it does but you have to download putty manager for that). You get the advantage of multiple tabs, plus you can script your access now. (Note: cygwin will not download openssh by default, you need to download it). If you use password less access to your servers, you can use ssh-agent to cache your keys in memory. I have a function in my .bashrc that I just run to cache the keys:


    alias keyon='ssh-add /cygdrive/c/Documents\ and\ Settings/user/My\ Documents/PrivateKeys/id_rsa'
    alias keyoff='ssh-add -D'
    alias keylist='ssh-add -l'

    function ssh_agent_start
    {
    SSHAGENT=/bin/ssh-agent
    if [[ ! -a $SSHAGENT ]]; then
    echo "SSHAGENT not found $SSHAGENT"
    return
    fi
    echo Starting SSH-agent
    SSHAGENTARGS="-s"
    if [ -n "$SSH_AUTH_SOCK" ]; then
    echo "Killing existing agent"
    eval `$SSHAGENT -k`
    fi
    eval `$SSHAGENT $SSHAGENTARGS`
    trap "kill $SSH_AGENT_PID" 0
    keyon
    }

    Now you can easliy login to your favourite server without password:
    > ssh_agent_start
    > ssh user@myserver









    Monday, May 18, 2009

    Can you sudo ?

    One of the big improvements that ubuntu has over other distributions is that it disables root account by default. So every time you have to do something as root, you have to run it as sudo. This by no means is an replacement to the man page, but some things that I found useful.

    1. To change sudo prefs, try visudo. Don't edit sudoers manually, as visudo makes sure that the syntax checks out before you save.
    2. To change default timeout try:
    Defaults:your_user_name timstamp_timeout=7200
    3. Other than that the file is pretty well self documented.

    Monday, February 23, 2009

    I am an avid vim user.  I cannot compare it to emacs, as I have rarely used emacs because of its werird keyboard sequence.  Anyway its important to carry around your vimenv with you.  I am posting below my .vimrc file.  In addition, I have had to add the following extensions to make it do my bidding:

    1. vimshell : Vim  has had buffers for a few versions. But it does not support shell access in any of its buffers. Enter vimshell. Its extremely convenient when debugging your code. Thing is you have to patch the vim code and recompile it. But its totally worth it.
    2. matchit.vim plugin: google it. Its lets you to match on html/xml tags as well Super userful

    -------------------------vimrc----------------------------------------------
    "type :help option to get help on options below
    set tags=tags;/
    set nocompatible
    set backspace=2
    set confirm
    set dictionary=/usr/share/dict/words
    set formatoptions=tcq2
    set incsearch
    set listchars=tab:»·,trail:·
    set report=1
    set shortmess=fnrxotTI
    set smarttab
    set textwidth=78
    set title
    set whichwrap=
    set wildmenu
    set tabstop=2
    set shiftwidth=2
    set expandtab
    set paste
    set ruler
    set incsearch  " do incremental searching
    set history=50
    set hlsearch
    "set viminfo='20,\"50  " read/write a .viminfo file, don't store more
          " than 50 lines of registers
    set viminfo='10,\"100,:20,%,n~/.viminfo
    au BufReadPost * if line("'\"") > 0|if line("'\"") <= line("$")|exe("norm '\"")|else|exe "norm $"|endif|endif

    filetype plugin on

    syntax on

    function CodePrefs()
        set cindent
        set cinoptions=(0,u0
        set expandtab
        set makeprg=gmake
        set shiftwidth=4
        set textwidth=0
    endfun
    if has("autocmd")
        autocmd FileType c,cpp,html,make,perl,php,php3,php4,inc,sh,dc call CodePrefs()
        autocmd FileType make set noexpandtab nosmarttab
        autocmd FileType mail set textwidth=72 titleold=mutt
        autocmd FileType html set shiftwidth=2
    endif

    " Transparent editing of gpg encrypted files.
    " By Wouter Hanegraaff
    augroup encrypted
        au!

        " First make sure nothing is written to ~/.viminfo while editing
        " an encrypted file.
        autocmd BufReadPre,FileReadPre      *.gpg set viminfo=
        " We don't want a swap file, as it writes unencrypted data to disk
        autocmd BufReadPre,FileReadPre      *.gpg set noswapfile
        " Switch to binary mode to read the encrypted file
        autocmd BufReadPre,FileReadPre      *.gpg set bin
        autocmd BufReadPre,FileReadPre      *.gpg let ch_save = &ch|set ch=2
        autocmd BufReadPost,FileReadPost    *.gpg '[,']!gpg --decrypt -q -a 2>/dev/null
        " Switch to normal mode for editing
        autocmd BufReadPost,FileReadPost    *.gpg set nobin
        autocmd BufReadPost,FileReadPost    *.gpg let &ch = ch_save|unlet ch_save
        autocmd BufReadPost,FileReadPost    *.gpg execute ":doautocmd BufReadPost " . expand("%:r")

        " Convert all text to encrypted text before writing
        autocmd BufWritePre,FileWritePre    *.gpg   '[,']!gpg --encrypt --default-recipient "Punit Rathore " -q -a 2>/dev/null
        " Undo the encryption so we are back in the normal text, directly
        " after the file has been written.
        autocmd BufWritePost,FileWritePost    *.gpg   u
    augroup END


    Friday, February 6, 2009

    Automate tedious tasks using Autoit

    One of my collegues was looking for a script that would let him automate his daily ritual of opening up 4-5 putty sessions to his linux host. I had used autoit before and suggested it to him. I hadn't used it in a while and was curious as to how it worked. After downloading it took me all of 45 minutes to come up with the following script. It asks for your password, then uses it to log on to 5 different putty sessions!!
    ---------------------------------------------------
    ; this script logs you on to 5 different putty sessions

    $answer =  InputBox ("enter password", "please enter your password","","*",150,80)

    If $answer = "" Then
    MsgBox(0, "AutoIt Example", "Enter valid password")
    Exit
    EndIf

    Opt("WinTitleMatchMode", 2)

    For $count = 1 To 5
    Run("C:\Program Files\PuTTY\putty.exe -ssh username@hostname")
    WinWaitActive("PuTTY")
    Sleep(1500) 
    ;MsgBox(0,"Sending password" ,$answer)
    Send($answer)
    Send("{ENTER}")
    Next
    --------------------------------------------------------------