Saturday, November 2, 2013

How to login as root in your shell using bash script ?

Whenever I need to login as root in bash I use su command.
What if I need to login as root using a bash script?? After the command bash prompts for password.
I tried to write a bash script for the same but could not. I did some googling again got no solution. Then I remembered about a shell utility Expect. I installed it and wrote some simple scripts.
spawn su
expect "Password: "
send "rootpassword\r"
expect "#"
interact
With this script we are left logged into the root and we can run any bash commands there after.
I wrote the next one by mixing bash and expect.
#!/bin/bash
/usr/bin/expect << EOD
set timeout 120
spawn su
expect "Password: "
send "rootpassword\r"
expect "#"
EOD
echo "\r"
ls
But with this we are logged out (we can't interact in the shell as root) after completion of the script.

Friday, November 1, 2013

How to get top n and bottom n lines from a text file in a single pass ?

Some days ago, I came across a problem. The problem was to get the row-count , top n and bottom n number of lines from a text file in a single pass.
I thought for a while and remembered about a data-structure Queue that I had learned about in Data Structures and Algorithm course. I then wrote a simple Java code to get implementing Queue.
Below is the code I wrote, please read and give me feedbacks.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;

public class Test {
 private static Queue top=new LinkedList();
 private static Queue bottom=new LinkedList();
 private static int count=0;
 
 public static void main(String[] args) throws IOException{
  func(3);
  }
 
 //function to get count, top n, bottom n lines
 private static void func(int n) throws IOException{
  FileInputStream fstream = new FileInputStream("abc.txt");
  BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

  String strLine;

  //Read File Line By Line
  while ((strLine = br.readLine()) != null){
    count++;
    if(count<=n){
     top.add(strLine);    //initialize both top and bottom as top n 
     bottom.add(strLine);
    }else{
     bottom.remove();
     bottom.add(strLine);
        }
  }
  System.out.println(count);
  System.out.println(top.toString());
  System.out.println(bottom.toString());
  br.close();    
 }
}