Tuesday, 26 June 2018

python - Split the file name from git diff


Program:

import sys   # For command line argument
import os.path # To check file existing

def generate_writefile(file_name):
    count = 1
    while True:                      # in True T must be capital
        file_name_new = file_name
        file_name_new += "_" + str(count)
        count += 1
        if not os.path.isfile(file_name_new):
            return file_name_new
        if count >=10 :
            print "Error while creating file"
            return None


def main():
    cmd_len = len(sys.argv)
    if(cmd_len <2):
        print "\t\tVel Error, provide the git file name\n\n"
        return

    name =  sys.argv[1]
    file_name = generate_writefile(sys.argv[1])
    if file_name == None:
        return
    file_write = open(file_name, 'w')
    if  not os.path.isfile(sys.argv[1]):
        print "Vel Error, provided file is not existing\n\n"
        return

    count_file = 0
    with open(sys.argv[1]) as openfileobject:
        for line in openfileobject:
            spl_for_com = line.split()      # convert the list of array into an separated string
            length = len(spl_for_com)
            if((length >=4) and (spl_for_com[0] == "diff") and (spl_for_com[1] == "--git")):
#        print "Got the match velraj ", spl_for_com[2][1:], spl_for_com[3]
                file_write.write(spl_for_com[2][1:])
                file_write.write("\n")
                count_file += 1
    print "Number of file = ", str(count_file), "Output file name is = ", file_name

    if count_file == 0:
        os.remove(file_name)

main()


# API to read from file.
    #    message = file_read.read()   # It read a whole file in  1 time
    #    message = file_read.readline()  # Its read only single line

Thursday, 14 June 2018

python - Execute the system Linux command on remote Linux machine

python - Execute the system Linux command on remote Linux machine


Python Program:


mport pexpect
import getpass
import sys

PASSWORD = "admin123"

def child_kill(child_pro):
    if child_pro.isalive():
        print "Still child is live 1 \n"
        child_pro.close()       # Kill the child, give argument as force=true then also same behaviour
    if child_pro.isalive():
        print "Still child is live 2\n\n"
    else:
        print "Child is dead"

def child_read_command(child_pro, command, expect_str):
    child_pro.sendline (command)
    child_pro.expect (expect_str)

# use list format, string format is not working
    output = []
    done = False
    while True:
        try:
            if not child_pro.isalive():
                line = child_pro.readline()
                done = True
            else:
# Wait on multiple expect eg: i = child.expect(['first', 'second'])
# i retrun 0 for first, and 1 for second
                i = child_pro.expect(['\n', expect_str])
                if i == 0:
                    line = child_pro.before
                    print(line)
                else:
                    line = child_pro.before
                    print(line)
                    break
            output.append(line)
            if done:
                raise pexpect.EOF(0)
                print "Rasie the pexect EOF"
        except pexpect.EOF:
            print "Break of EOF"
            break

    print "\n\nOutput value = ", output
    child_kill(child_pro)

def ssh_login(host_address):
    child = pexpect.spawn ('ssh '+host_address)
    child.logfile = open("/home/labuser/mylog", "w")   # This will store the output logs into the file
#    child.logfile = sys.stdout
    child.expect ('password: ')
    child.sendline (PASSWORD)
    child.expect ('machine:')
    return child


def main():
    child = ssh_login("192.168.1.50")
    child_read_command(child,'ls','machine:')


main()



python - pexpect - multiple expect, spawn, kill child

python - pexpect - multiple expect, spawn, kill child


pexpect - multiple expect:


i = child.expect(['first', 'second'])
The expect() method returns the index of the pattern that was matched. So in your example:
if i == 0:
    # do something with 'first' match
else: # i == 1
    # do something with 'second' match

Spawn:

  • The more powerful interface is the spawn class. 
  • You can use this to spawn an external child command and then interact with the child by sending lines and expecting responses.
child = pexpect.spawn('scp foo myname@host.example.com:.')
child.expect ('Password:')
child.sendline (mypassword)

close(force=True)
  • This closes the connection with the child application. 
  • Note that calling close() more than once is valid. 
  • This emulates standard Python behavior with files. 
  • Set force to True if you want to make sure that the child is terminated (SIGKILL is sent if the child ignores SIGHUP and SIGINT).
child.close() 
or child.close(force=true)

Program:

import pexpect
import getpass
import sys

PASSWORD = "admin123"

def child_kill(child_pro):
    if child_pro.isalive():
        print "Still child is live 1 \n"
        child_pro.close()       # Kill the child, give argument as force=true then also same behaviour
    if child_pro.isalive():
        print "Still child is live 2\n\n"
    else:
        print "Child is dead"

def child_read_command(child_pro, command, expect_str):
    child_pro.sendline (command)
    child_pro.expect (expect_str)

# use list format, string format is not working
    output = []
    done = False
    while True:
        try:
            if not child_pro.isalive():
                line = child_pro.readline()
                done = True
            else:
# Wait on multiple expect eg: i = child.expect(['first', 'second'])
# i retrun 0 for first, and 1 for second
                i = child_pro.expect(['\n', expect_str])
                if i == 0:
                    line = child_pro.before
                    print(line)
                else:
                    line = child_pro.before
                    print(line)
                    break
            output.append(line)
            if done:
                raise pexpect.EOF(0)
                print "Rasie the pexect EOF"
        except pexpect.EOF:
            print "Break of EOF"
            break

    print "\n\nOutput value = ", output
    child_kill(child_pro)



Reference: http://www.bx.psu.edu/~nate/pexpect/pexpect.html

Monday, 4 June 2018

typedef sample

  • typedef can use to give a type a new name. 
  • Following is an example to define a term Velraj for one-byte numbers −
    • typedef unsigned char Velraj;

Program:


/* typedef program by Velraj.K
   Check : http://velrajcoding.blogspot.in
 */

#include <stdio.h>

#define MAC_BUF_LEN  6

/* This also can bee used to access the single field.
   Here there is no magic, just use unsigned char mac[6] replace with MacAddress mac */
typedef unsigned char MacAddress[MAC_BUF_LEN];

// This typedef used to access the single char filed in mac
typedef unsigned char MacAddress_access;

int main()
{
    MacAddress mac_2 =  {0x00,0x0c,0x29,0x44,0x11,0x33};         // This is corrent this is equivalent to unigned char mac[6]
    MacAddress_access mac[6] = {0x00,0x0c,0xFF,0x44,0x00,0xEE};   // This is wrong because this is equivalent to unsigned char mac[6][6]
    MacAddress *pmac= NULL;  // This is equilaent to unsigned char *mac[6]
//    pmac = &mac_2;

    printf("Size of tMacAddr mac_2 = %lu mac = %02hhX:%02hhX:%02hhX:%02hhX:%02hhX:%02hhX  \n", sizeof(mac_2), mac_2[0], mac_2[1], mac_2[2], mac_2[3], mac_2[4], mac_2[5] );
    printf("Base address = %p address + 1 = %p addd +2 = %p \n", &mac_2, &mac_2[1], &mac_2[2]);
    printf("Pointer tMacAddr+1  = %p  pmac[1] Add = %p pmac[2] = %p \n", pmac+1, &pmac[1], &pmac[2]);

    printf("print the mac = %02hhX:%02hhX:%02hhX:%02hhX:%02hhX:%02hhX \n", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);

    return 0;
}

Output:

sample$ ./a.out
Size of tMacAddr mac_2 = 6 mac = 00:0C:29:44:11:33
Base address = 0x7ffc47bce8d0 address + 1 = 0x7ffc47bce8d1 addd +2 = 0x7ffc47bce8d2
Pointer tMacAddr+1  = 0x6  pmac[1] Add = 0x6 pmac[2] = 0xc
print the mac = 00:0C:FF:44:00:EE

 

 

Thursday, 24 May 2018

Signal handler using signal() commad

Signal handler using signal() commad


Declaration:

  • Following is the declaration for signal() function.
    • #include <signal.h>
    • typedef void (*sighandler_t)(int);
    • sighandler_t signal(int signum, sighandler_t handler)
    • other declare
      • void (*signal(int sig, void (*func)(int)))(int)


DESCRIPTION:

  •  signal() sets the disposition of the signal signum to handler, which is either SIG_IGN, SIG_DFL, or the address of a programmer-defined function (a "signal handler").
  • sig − This is the signal number to which a handling function is set. The following are few important standard signal numbers.

Return Value

  • This function returns the previous value of the signal handler, or SIG_ERR on error.

Program:

* Singal program by Velraj.K
   Check : http://velrajcoding.blogspot.in
*/

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <stdbool.h>

void sighandler(int);

int main()
{
    signal(SIGINT, sighandler);

    signal(SIGHUP, sighandler);
    while(1)
    {
        printf("Going to sleep for a second...\n");
        sleep(1);
    }
    return(0);
}
void sighandler(int signum)
{
    static int sighup = 0;

    printf("Caught signal %d, coming out...\n", signum);
    switch(signum)
    {
        case SIGHUP:
            printf("Vel instid eSIGUP.\n");
            if(sighup++ %2)
            {
                printf("Ignore the sigint \n");
                signal(SIGINT, SIG_IGN);
            }
            else
            {
                printf("set defalt to  int \n");
                signal(SIGINT, SIG_DFL);
            }
            break;
    }

//    exit(1);
}


Output:


   $./a.out
   Going to sleep for a second...
   Going to sleep for a second...
   Going to sleep for a second...
   Going to sleep for a second...
   ^CCaught signal 2, coming out...
  

Send the signal from Command prompt:
1. Need to know the signal number:
  • The signal number will be different for OS, as check in net they commonly mentioned SIGUSR1 value as 10 but in mips64 archetecture, we are getting SIGUSR1 value as 16.
  • To know the signal number, give "kill -l" command to get signal number:

EG: $ kill -l
 1) SIGHUP       2) SIGINT       3) SIGQUIT      4) SIGILL       5) SIGTRAP
 6) SIGABRT      7) SIGEMT       8) SIGFPE       9) SIGKILL     10) SIGBUS
11) SIGSEGV     12) SIGSYS      13) SIGPIPE     14) SIGALRM     15) SIGTERM
16) SIGUSR1     17) SIGUSR2  

  • To send signal use below:
  • kill -s 16 14517
     


Monday, 21 May 2018

Break statement on nested loop

Break statement on nested loop

  • When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop.
  • If you are using nested loops, the break statement will stop the execution of the innermost loop and start executing the next line of code after the block.

Program:

/* Break statement on nested loop */
#include <stdio.h>


int main()
{
    int count_1 = 0, count_2 = 0;

    while(1) {

        printf("Vel 1st while count = %d \n", count_1++);
        while(1) {
            printf("Vel Inside 2nd while count %d, 1st while = %d \n",count_2++, count_1);
            sleep(1);
            if(!(count_2 % 5)) {
                /* This break will be apply to this while loop only,
                   1st while loop still be live. */
                break;
            }
        }
        sleep(1);
    }

    return 0;
}

Output:

   sample$ ./a.out
   Vel 1st while count = 0
   Vel Inside 2nd while count 0, 1st while = 1
   Vel Inside 2nd while count 1, 1st while = 1
   Vel Inside 2nd while count 2, 1st while = 1
   Vel Inside 2nd while count 3, 1st while = 1
   Vel Inside 2nd while count 4, 1st while = 1
   Vel 1st while count = 1
   Vel Inside 2nd while count 5, 1st while = 2
   Vel Inside 2nd while count 6, 1st while = 2
   Vel Inside 2nd while count 7, 1st while = 2
   Vel Inside 2nd while count 8, 1st while = 2
   Vel Inside 2nd while count 9, 1st while = 2
   Vel 1st while count = 2
   Vel Inside 2nd while count 10, 1st while = 3
   Vel Inside 2nd while count 11, 1st while = 3
   Vel Inside 2nd while count 12, 1st while = 3
   Vel Inside 2nd while count 13, 1st while = 3
   Vel Inside 2nd while count 14, 1st while = 3
   Vel 1st while count = 3
   Vel Inside 2nd while count 15, 1st while = 4
   Vel Inside 2nd while count 16, 1st while = 4
   Vel Inside 2nd while count 17, 1st while = 4
   Vel Inside 2nd while count 18, 1st while = 4
   Vel Inside 2nd while count 19, 1st while = 4
   Vel 1st while count = 4
   Vel Inside 2nd while count 20, 1st while = 5
   Vel Inside 2nd while count 21, 1st while = 5
   Vel Inside 2nd while count 22, 1st while = 5

Friday, 18 May 2018

Checks if specified IP is multicast IP

Checks if specified IP is multicast IP


  • IPv4 multicast addresses are defined by the leading address bits of 1110, originating from the classful network design of the early Internet when this group of addresses was designated as Class D.
  • The Classless Inter-Domain Routing (CIDR) prefix of this group is 224.0.0.0/4. The group includes the addresses from 224.0.0.0 to 239.255.255.255.
  • The macro IN_MULTICAST is used to check the IP as multicast, this macro is impleted as part of Linux kernal.
  • The below file contain this macro.
    • https://github.com/torvalds/linux/blob/master/include/uapi/linux/in.h#L268
  • The userlevel application header file netinet/in.h & arpa/inet.h contain this macro definition.

Program:



#include <stdio.h>
#include <stdbool.h>   // For bool

// For inet_addr
#include <sys/socket.h>
#include <netinet/in.h>    // This contain the in_addr_t, & IN_MULTICAST macro
#include <arpa/inet.h>  // This also including  <netinet/in.h>

/*
  IN_MULTICAST macro is defined in Linux in.h file,
  Below is the definition
  */

//#define IN_CLASSD(a)            ((((long int) (a)) & 0xf0000000) == 0xe0000000)
//#define IN_MULTICAST(a)         IN_CLASSD(a)


bool isMulticastAddress(in_addr_t s_addr)
{
    //in_addr_t stored in network order
    uint32_t address = ntohl(s_addr);
    char *char_saddr = (char*) &s_addr;
    char *char_address = (char *) &address;

    printf("S-add value = %x %x %x %x address = %x %x %x %x \n", char_saddr[0], char_saddr[1], char_saddr[2], char_saddr[3],
                    char_address[0], char_address[1], char_address[2], char_address[3]);

    return (address & 0xF0000000) == 0xE0000000;
}

int main()
{
    int ret = 0;

    if (IN_MULTICAST(ntohl(inet_addr("239.4.4.4")))) {
        printf("239.4.4.4 is an multicast using IN_MULTICAST macro. \n");
    }
    else {
        printf("Not an multicast IP check using IN_MULTICAST macro. \n");
    }


    ret = isMulticastAddress(inet_addr("239.4.4.4"));
    if(ret) {
        printf("239.4.4.4 is an multicast using isMulticastAddress function. \n");
    }
    else {
        printf("Not an multicast IP check using isMulticastAddress function. \n");
    }

    ret = isMulticastAddress(inet_addr("224.4.4.4"));
    if(ret) {
        printf("224.4.4.4 is an multicast using isMulticastAddress function. \n");
    }
    else {
        printf("Not an multicast IP check using isMulticastAddress function. \n");
    }


}

Output:

sample$ ./a.out
239.4.4.4 is an multicast using IN_MULTICAST macro.
S-add value = ffffffef 4 4 4 address = 4 4 4 ffffffef
239.4.4.4 is an multicast using isMulticastAddress function.
S-add value = ffffffe0 4 4 4 address = 4 4 4 ffffffe0
224.4.4.4 is an multicast using isMulticastAddress function.


Refer: http://www.tcpipguide.com/free/t_IPMulticastAddressing.htm