Archive for the ‘ Scripting ’ Category

C programming Language – Code snippets

C Programming Language, 2nd Edition

Compiling and running the sample codes using gcc :

gcc sample.c -o sample
./sample

Chapter 1 – Introductory tutorial : Input/output, characters, strings

0. Hello World!

#include<stdio.h>

int main()

{

  printf("Hello World\n");
  return 0;
}

1. Word counter


/* word counter */
#include<stdio.h>

#define  IN 1  //inside a word
#define  OUT   0  //outside a word

int main()

{
  int c,nl,nw,nc,state;
  state=OUT;
  nl=nw=nc=0;

  while((c=getchar())!=EOF)
   {
      ++nc;
      if(c=='\n') ++nl;
      if (c==' ' || c == '\n' || c=='\t') state=OUT;
      else if (state==OUT)
         {
           state=IN;
           ++nw;
          }
        }
      printf("lines=%d words=%d characters=%d\n",nl,nw,nc);
 return 0;
}

2. Convert Fahrenheit to Celsius


#include<stdio.h>

#define  LOWER 0
#define  UPPER 300
#define  STEP  20

int main()

  {
     int fahr;
     for (fahr = LOWER; fahr <= UPPER; fahr=fahr + STEP)
         printf("%3d %6.1f\n", fahr, (5.0/9.0)*(fahr-32));
     return 0;
 }


3. Count characters


/* character counter */
#include<stdio.h>

int main()

{
   short int nc;
   for(nc=0; getchar()!=EOF ; ++nc);
   printf("%d\n",nc);
   return 0;
}

4. Count characters by type – digits, white spaces etc.


/* count digits, white space, others */
#include<stdio.h>

int main()
 {
   int c,i,nwhite,nother;
   int ndigit[10];

   nwhite=nother=0;
   for(i=0; i < 10; ++i)  ndigit[i]=0;

   while((c=getchar())!=EOF)
     if(c>='0' && c<='9') ++ndigit[c-'0'];
     else if (c==' ' || c=='\n' || c=='\t') ++nwhite;
     else  ++nother;

   printf("digits=");
   for(i=0;i<10;++i) printf(" %d",ndigit[i]);
   printf(",white space=%d, other=%d\n",nwhite,nother);

return 0;
}

5. Copy input to output terminal


/* copy input to output 1 */
#include<stdio.h>

int main()

{
   int c;
   c = getchar();
   while ( c!=EOF)
     {
       putchar(c);
       c = getchar();
     }
 return 0;
}

6. Copy input to output terminal (shorter version)

/* copy input to output */
#include<stdio.h>

int main()
{
   int c;
   while((c=getchar())!=EOF)
     putchar(c);
   return 0;
}

7. Print longest line


#include<stdio.h>

#define  MAXLINE  1000  /* maximum input line length */

int getline(char line[], int maxline);
void copy(char to[], char from[]);

/* print the longest input line */

int main()

{
  int len;  /* current line length */
  int max;  /* maximum length seen so far */
  char line[MAXLINE];   /* current input line */
  char longest[MAXLINE];   /*longest line saved here */

  max=0;
  while((len=getline(line,MAXLINE))>0)
    if(len>max)
       { max=len;
         copy(longest,line);
       }
 if(max>0)  /*there was a line*/
  printf("Longest Line from input is:\n%s\n",longest);
  printf("Line length is: %d characters\n",max);

return 0;
}


/*getline: read a line into s, return length */

int getline(char s[], int lim)
{
  int c,i;
  for(i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
   s[i]=c;
 if(c=='\n') {
  s[i]=c;
  ++i;
  }
 s[i]='\0';
 return i;
}

/*copy: copy 'from' into 'to'; assume 'to' is big enough */

void copy(char to[], char from[])
{
  int i;
  i=0;
  while((to[i]=from[i]) != '\0')
    ++i;
}

8. Print longest line – improved


#include<stdio.h>

#define  MAXLINE  1000  /* maximum input line length */

int max;
char line[MAXLINE];
char longest[MAXLINE];

int getline(char line[], int maxline);
void copy(char to[], char from[]);

/* print the longest input line */

int main()

{
  int len;  /* current line length */
  extern int max; /* maximum length seen so far */
  extern char longest[MAXLINE];  /*longest line saved here */

  max=0;
  while((len=getline(line,MAXLINE))>0)
    if(len>max)
       { max=len;
         copy(longest,line);
       }
 if(max>0)  /*there was a line*/
  printf("Longest Line from input is:\n%s\n",longest);
  printf("Line length is: %d characters\n",max);

return 0;
}


/*getline: read a line into s, return length */

int getline(char s[], int lim)
{
  int c,i;
  extern char line[];
  for(i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
   s[i]=c;
 if(c=='\n') {
  s[i]=c;
  ++i;
  }
 s[i]='\0';
 return i;
}

/*copy: copy 'from' into 'to'; assume 'to' is big enough */

void copy(char to[], char from[])
{
  int i;
  extern char line[], longest[];
  i=0;
  while((to[i]=from[i]) != '\0')
    ++i;
}

9. Power function


#include<stdio.h>

int power(int m, int n);

/* test power function */

int main()

{
  int i;
  for(i=0; i<10; ++i)
   printf("%d %d %d\n",i,power(2,i),power(-3,i));
 return 0;
}

int power(int base, int n)
 {
   int i,p=1;
   for(i=1;i<=n;++i)
     p*=base;
   return p;
 }

10. Reverse string


#include<stdio.h>

#define  MAXLINE  1000

int size=0;
void reverse(char line[], int lim);
int main()

{ extern int size;
  char line[MAXLINE];
  reverse(line,MAXLINE);
  while(size) putchar(line[--size]);
  printf("\n");
  return 0;
}

void reverse(char line[], int lim)

{
 extern int size;
 int c;
 while((c=getchar())!=EOF ) line[size++]=c;
 line[size]='\0';

}

11. Get digits only


#include<stdio.h>

int atoi(char s[]);

int main()

{
  char str[]="12a4c5 ";
  int i=0,n=0;

 while(str[i]!='\0')
   {
      if(str[i]>='0' && str[i]<='9') { n=10*n+(str[i]-'0'); i++; }
      else
       { i++; continue; }
   }
 printf("number=%d\n",n);
 return 0;

 }

12. Fahrenheit to Celsius table

/* print Fahrenheit-Celsius table for fahr =0,20,40,....,300 */

#include<stdio.h>

int main()

{
  int fahr, celsius;
  int lower, upper, step;
  lower = 0;
  upper = 300;
  step = 20;

  fahr = lower;
  while( fahr <= upper)
   {
      celsius = 5 * (fahr - 32) / 9;
      printf("%d\t%d\n", fahr, celsius);
      fahr = fahr + step;
   }

return 0;
}

Reference –

https://www.amazon.com/Programming-Language-2nd-Brian-Kernighan/dp/0131103628#reader_0131103628

Ansible : rolling upgrades or updates.

Making a change to live servers in production is something which has to be done with extreme care and planning. Several deployment types such as blue/green, canary, rolling update are in use today to minimize user impact. Ansible can be used to orchestrate a zero-downtime rolling change to a service.

A typical upgrade of an application, such as patching, might go like this –

  1. disable monitoring alerts for a node
  2. disable or pull out from load balancer
  3. make changes to server
  4. Reboot node
  5. wait for node to be UP and do sanity check
  6. put node back to load balancer
  7. turn on monitoring of node

Rinse and repeat.

Ansible would be a great choice in orchestrating above steps. Let us start with an inventory of web servers, a load balancer and a monitoring node with nagios –

[webservers]
web1.example.net
web2.example.net
web3.example.net
web4.example.net
web5.example.net

[balancer]
haproxy.example.net

[monitoring]
nagios.example.net

The web servers are running apache2, and we will patch apache and the kernel. For the patch to take effect, the servers need to be recycled. We will perform the patching one node at a time, wait for the node to be healthy and go to the next. The first portion of our playbook would be something like this –

---
- hosts: webservers
  serial: 1

  pre_tasks:
  - name: Stop apache service
    service: name=httpd state=stopped

  tasks:
  - name: update apache
    yum: name=httpd state=latest
  - name: Update Kernel
    yum: name=kernel state=latest
  - name: Reboot server
    shell: /sbin/reboot -r +1

  post_tasks:
  - name: Wait for webserver to come up
    wait_for: host={{ inventory_hostname }} port=80 state=started delay=65 timeout=300
    delegate_to: 127.0.0.1

I haven’t included the playbook tasks for disabling/enabling monitoring as well as removing/adding node to the load balancer. The procedures might differ depending on what type of monitoring system or load balancer technology you are using. In addition to this, the sanity check show is a simple port 80 probing, in reality a much more sophisticated validation can be done.

References –

http://docs.ansible.com/ansible/latest/playbooks_delegation.html

http://docs.ansible.com/ansible/latest/guide_rolling_upgrade.html

Ansible – How to run a portion of a playbook using tags.

If you have a large playbook it may become useful to be able to run a specific part of it or only a single task without running the whole playbook. Both plays and tasks support a “tags:” attribute for this reason.

In this specific scenario, I have a playbook which configures all productions servers from the moment the servers boot till they start taking traffic. While testing the plays in dev environment, I was debugging an issue on the parts which does dns configuration. This is where the “tags” attributes comes handy –

1. Tag the task –

...
- name: Configure resolv.conf
  template: src=resolv.conf.j2 dest=/etc/resolv.conf
  when: ansible_hostname != "ns1"
  tags:
    - dnsconfig
...

2. Run only the tasks tagged with a specific name –

root@linubuvma:/etc/ansible# ansible-playbook -i dc1/hosts dc1/site.yml --tags "dnsconfig" --check

PLAY [Setup data center 1 servers] *****************************************************

TASK: [common | Configure resolv.conf] ****************************************
skipping: [ns1]
changed: [docker]
ok: [ns2]
ok: [whitehat]
ok: [mail]
ok: [www]
ok: [ftp]

PLAY RECAP ********************************************************************
whitehat                   : ok=1    changed=0    unreachable=0    failed=0
docker                     : ok=1    changed=1    unreachable=0    failed=0
ns1                        : ok=0    changed=0    unreachable=0    failed=0
ns2                        : ok=1    changed=0    unreachable=0    failed=0
mail                        : ok=1    changed=0    unreachable=0    failed=0
www                   : ok=1    changed=0    unreachable=0    failed=0
ftp                   : ok=1    changed=0    unreachable=0    failed=0

Ansible playbook will run only the task with the specified tag, it will skip the rest of the tasks in the playbook. Use the ‘–list-tags’ flag to view all the tags.

References –

http://docs.ansible.com/playbooks_tags.html

https://www.percona.com/live/mysql-conference-2015/sites/default/files/slides/Ansible.pdf

Ansible – enable logging

Ansible – Enable logging

By default, Ansible logs the output of playbooks to the standard output only. In order to enable logging to a file for later review or auditing, it can be turned on by setting log_path to a path location where Ansible has a write access.

In my case, i have added the “log_path” setting in the ansible configuration file “/etc/ansible/ansible.cfg”

# grep log_path /etc/ansible/ansible.cfg
log_path = /var/log/ansible.log

Now I can view the log file to all the details on ansible runs –

root@linubuvma:/etc/ansible# ansible-playbook tasks/groupby.yml --check
PLAY [all:!swarm:!docker1] ****************************************************

TASK: [group_by key=os_{{ ansible_os_family }}] *******************************
changed: [ns2]
.....

root@linubuvma:/etc/ansible# ls -al /var/log/ansible.log
-rw-r--r-- 1 root root 4255 May 16 21:21 /var/log/ansible.log
root@linubuvma:/etc/ansible# head  /var/log/ansible.log
2015-05-16 21:21:43,732 p=22946 u=root |
2015-05-16 21:21:43,732 p=22946 u=root |  /usr/local/bin/ansible-playbook tasks/groupby.yml --check
2015-05-16 21:21:43,732 p=22946 u=root |
2015-05-16 21:21:43,734 p=22946 u=root |  ERROR: the playbook: tasks/groupby.yml could not be found
2015-05-16 21:21:48,575 p=22954 u=root |
2015-05-16 21:21:48,576 p=22954 u=root |  /usr/local/bin/ansible-playbook tasks/groupby.yml --check
2015-05-16 21:21:48,576 p=22954 u=root |
2015-05-16 21:21:48,594 p=22954 u=root |  PLAY [all:!swarm:!docker1] ****************************************************
2015-05-16 21:21:48,609 p=22954 u=root |  TASK: [group_by key=os_{{ ansible_os_family }}] *******************************
2015-05-16 21:21:48,641 p=22954 u=root |  changed: [ns2]

It logs dry-runs (–check) as well and it is smart enough not to log Password arguments.

References –

http://docs.ansible.com/ansible/latest/intro_configuration.html#log-path

ipython – quick introduction

ipython tutorial and how to delete sensitive data from history

ipython is program which allows you to run python code in an interactive shell. Although Python itself when run from CLI opens an interactive shell as well, ipython is much more powerful and greatly improves your productivity. Some of the things you can do with ipython but not the default python shell is command or code and file name completion, view history, copy/paste a single or multiline code, nicely colored help with in the shell, run Linux commands such as ls or cat, scroll up/down to previous commands, automatically adds spaces after you press enter, etc.

Installation

pip install ipython

Quick demo
Start ipython by typing the

ipython

command in your CLI –

daniel@lindell:/tmp$ ipython
Python 2.7.12 (default, Nov 19 2016, 06:48:10) 
Type "copyright", "credits" or "license" for more information.

IPython 5.4.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: print('ipython')
ipython

In [2]: 

With in the ipython interactive shell you can run any python code, let us walk through some examples –


  In [1]: x=2

In [2]: x
Out[2]: 2

In [3]: mylist=[1,2,3,4,5]

In [4]: [i**3 for i in mylist]
Out[4]: [1, 8, 27, 64, 125]

In [5]: with open('/etc/hosts') as fp:
   ...:     for line in fp:
   ...:         if 'localhost' in line:
   ...:             print line
   ...:             
127.0.0.1	localhost

::1     ip6-localhost ip6-loopback


In [6]: ls /opt/
ansible/  google/  vagrant/

In [7]: 

Go back to previously typed commands / History
With ipython, you can either press the UP arrow key or type

 history 

command to view history. ipython keeps session history as well as all input and output lines in a SQLite file which is located in

~/.ipython/profile_default/history.sqlite 

You can view and modify this file using

sqlite3

tool –

daniel@lindell:/tmp$ sqlite3 ~/.ipython/profile_default/history.sqlite
SQLite version 3.11.0 2016-02-15 17:29:24
Enter ".help" for usage hints.
sqlite> .schema
CREATE TABLE sessions (session integer
                        primary key autoincrement, start timestamp,
                        end timestamp, num_cmds integer, remark text);
CREATE TABLE history
                (session integer, line integer, source text, source_raw text,
                PRIMARY KEY (session, line));
CREATE TABLE output_history
                        (session integer, line integer, output text,
                        PRIMARY KEY (session, line));
sqlite> 

Deleting sensitive data from history
You can delete any line from history by using SQL. First use SELECT statement to find the line number and then use DELETE statement to delete it. In this example, we are deleting line number 10 from the history table –

sqlite> select * from history;
sqlite> .schema history
CREATE TABLE history
                (session integer, line integer, source text, source_raw text,
                PRIMARY KEY (session, line));
sqlite> delete from history where line=10;

References –
https://ipython.org/
http://www.sqlitetutorial.net/sqlite-delete/

How to copy to a clipboard in Linux


Problem – You have a file with hundreds or thousands of lines and you want to copy the contents of this file and paste it to an external application, for instance to a browser.

Solution – The first attempt is to try to cat the file and scroll down with your mouse to select each line. This is time consuming or in some cases might not work if there are too many lines as some of the lines will ‘scroll out of the terminal’. One way of getting around this is to use “xclip” – a command line interface to X selections (clipboard).

In my case I wanted to copy the contents of ‘/tmp/ipaddresses.txt’ file to a browser for blogging. The file had 10000 lines. I used the following commands, first to install xclip and then to copy the file contents to a clipboard –

apt-get -y install xclip
xclip -sel cli < /tmp/ipaddresses.txt

The xclip command basically does a selection (-sel) from the file into the clipboard(-cli), where you can copy paste to any other external application.

Once you have the contents of the file in your clipboard, simply paste it, usually with Ctrl+v or Ctrl+Shift+v, to the intended application or file.

References
https://linux.die.net/man/1/xclip

https://stackoverflow.com/questions/5130968/how-can-i-copy-the-output-of-a-command-directly-into-my-clipboard