Sunday 11 February 2018

Introduction to Python Argparse


What is Python Command line arguments?


While executing python script, we can provide additional arguments in command line. These arguments are passed into the program. We can access those arguments inside the program with help of python modules(sys, argparse, etc..).  python "sys" library module is one of the traditional and simple way of handling command line arguments.

my-script.py
import sys
print len(sys.argv)
print sys.argv
print sys.argv[0]
print sys.argv[1]
print sys.argv[2]


$ python my-script.py arg1 arg2
3
['my-script.py', 'arg1', 'arg2']
test.py
arg1
arg2


Python "argparse" module:


There are many python modules available for handling python command line arguments. One of the most popular module is argparse.  Argparse was added into python 2.7 as replacement of optparse.  It provided more features then traditional sys module.

Parsing command line arguments:


There is an function called "arg_parse" from ArgumentParser class which is used to parse the command line arguments. In default it will take arguments from sys.argv[1:], but we can also provide our own list. 

We can define arguments using add_argument function it will return the Namespace object which containing the arguments to the commands.

import sys
import argparse
parser = argparse.ArgumentParser(description='sample app')
parser.add_argument("name", help="Please enter your name")
args = parser.parse_args()
print args
print args.name
$ python my-script.py -h
usage: my-script.py [-h] name

sample app

positional arguments:
  name        Please enter your name

optional arguments:
  -h, --help  show this help message and exit
$ python my-script.py Jerry
Namespace(name='Jerry')
Jerry
-h or --help is an default feature added into your script when you import argparse module.  it will show the available positional arguments and optional arguments with help messages provided by us.


argument type:


We can externally specify the type of the argument to argparse can accept. "type" field is used for specifying cast. it will convert the argument value to specified type while parsing the arguments. if cannot convert to specified type it will throw error.

import sys
import argparse
parser = argparse.ArgumentParser(description='sample app')
parser.add_argument("square", type=int, help="Please enter your name")
args = parser.parse_args()
print args.square**2
$ python my-script.py 4
16

Optional arguments:


When you add positional argument to parser, we must provide value to positional arguments otherwise it will throw an error. But optional arguments are actually optional, there is no error when running the program without it.

import sys
import argparse
parser = argparse.ArgumentParser(description='sample app')
parser.add_argument("--square", dest="square", default=2, type=int, help="Please enter integer value")
args = parser.parse_args()
print args.square**2
$ python my-script.py --square 4
16
$ python my-script.py
4

If we are not providing any command line arguments, it will take value from default field. "None" is the default value for default field.

Short options:


We can define the short versions of the optional arguments. it is very useful for handy

import sys
import argparse
parser = argparse.ArgumentParser(description='sample app')
parser.add_argument("-s","--square", dest="square", default=2, type=int)
args = parser.parse_args()
print args.square**2

$ python my-script.py -s 4
16

Argument Actions:


action field of add_argument() function specifies what kind of action need to be perform to that argument. default value is "store", i.e store the given value to the destination variable. following are the six different kind of actions can be triggered when we add argument.

  • store - it is a default value of an action field. it will store specified value to destination variable
  • store_const - store the value defined as part of argument specification
  • store_true/store_false - save boolean values to the variables
  • append - save the value to the list
  • append_const - store the value defined in the argument to list
  • version - prints the version details about the program

examples:


import sys
import argparse
parser = argparse.ArgumentParser(description='sample app')
parser.add_argument("-v", "--verbose", action="store_true", default=False)
parser.add_argument("-s","--square", dest="square", default=2, type=int)
parser.add_argument("-a","--add", dest="my_list", default=[], action="append")
args = parser.parse_args()
if args.verbose:
    print "printing verbose output"
print "square value ", args.square**2
print "my list is ", args.my_list
$ python my-script.py -v --square 4 -a 2 -a 3
printing verbose output
square value  4
my list is  ['2', '3']


Thursday 8 February 2018

Generate SSH keys using cmd line - Mac OS/Linux

ssh-keygen:

    ssh-keygen is an command line tool which is used for generate, manage and convert ssh keys. ssh-keygen can create keys for use by ssh protocal version 1 and 2. it has many option 

The type of key to be generated is specified with the -t option.  If invoked without any arguments, ssh-keygen will generate an RSA key for use in SSH protocol 2 connections.

Normally each user wishing to use SSH with public key authentication runs this once to create the authentication key in 
  • ~/.ssh/identity
  • ~/.ssh/id_dsa,
  • ~/.ssh/id_ecdsa
  • ~/.ssh/id_ed25519
  • ~/.ssh/id_rsa.
Additionally, the system administrator may use this to generate host keys, as seen in /etc/rc.

Normally this program generates the key and asks for a file in which to  store the private key.  The public key is stored in a file with the same name but ``.pub'' appended.  The program also asks for a passphrase.  The passphrase may be empty to indicate no passphrase (host keys must have an empty passphrase), or it may be a string of arbitrary length. 

open your terminal and run following command:

ssh-keygen -t rsa -f ~/.ssh/[KEY_FILENAME] -C [USERNAME]

-f - is name that you want to use for your ssh key files.
-c - is user for whom you will apply this ssh file
-t  - Specifies the type of key to create. (dsa | ecdsa | ed25519 | rsa | rsa1)

ex: 

ssh-keygen -t rsa -f ~/.ssh/my-ssh-keys -C ubuntu
 Specifies Above command create following two files.

my-ssh-keys - private key
my-ssh-keys.pub - public key

This command generates a private SSH key file and a matching public SSH key with the following structure:
ssh-rsa [KEY_VALUE] [USERNAME]
And restrict access to your private key
chmod 400 ~/.ssh/[KEY_FILENAME]
And restrict access to your private key.. Once you created public key and private key, add your public key into server's authorized_keys file which you want to access via ssh.
Normally it will be located in ~/.ssh/authorized_keys

cat ~/.ssh/authorized_keys

connect the server using ssh command line tool. When you connect first time it will ask to add server IP address to your known host list. Give yes for that.

ssh -i [private_key_file] [username]@[server-name]
ssh -i my-private-key ubuntu@10.193.10.23