Wednesday, 27 June 2018

Convert Error no(errno) into a string value

NAME

       strerror, strerror_r - return string describing error number

SYNOPSIS

 #include <string.h>
       char *strerror(int errnum);
       int strerror_r(int errnum, char *buf, size_t buflen);
                   /* XSI-compliant */
       char *strerror_r(int errnum, char *buf, size_t buflen);
                   /* GNU-specific */
   Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
       The XSI-compliant version of strerror_r() is provided if:
       (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! _GNU_SOURCE
       Otherwise, the GNU-specific version is provided.
     

DESCRIPTION


  • The strerror() function returns a pointer to a string that describes the error code passed in the argument errnum.
    • For example, if errnum is EINVAL, the returned description will "Invalid argument".
  • This string must not be modified by the application, but may be modified by a subsequent call to strerror()
  • The  strerror_r()  function  is  similar to strerror(), but is thread safe. 

RETURN VALUE

    Return the appropriate error description string, or an "Unknown error nnn" message if the error number is unknown.

Program:

/* error number into an String value program by Velraj.K
   Check : http://velrajcoding.blogspot.in
  */


#include <stdio.h>
#include <errno.h>
#include <string.h>

int main()
{
    FILE *fp;

    /* first rename if there is any file */
    rename("file.txt", "newfile.txt");

    /* now let's try to open same file */
    fp = fopen("file.txt", "r");
    if( fp == NULL ) {
        perror("Error: ");
        printf("velraj errno = %d value (%s)\n", errno, strerror(errno));
        return(-1);
    }
    fclose(fp);

    return(0);

}

Output:

sample$ ./a.out
Error: : No such file or directory
velraj errno = 2 value (No such file or directory)


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