diff --git a/AWS/addInstanceTag.py b/AWS/addInstanceTag.py index fcebb86..5c2d3c1 100644 --- a/AWS/addInstanceTag.py +++ b/AWS/addInstanceTag.py @@ -10,11 +10,11 @@ addTag = list(ast.literal_eval(sys.argv[4])) ec2 = boto3.client('ec2',Region) -response = ec2.describe_instances(Filters=[{'Name':'tag:' + selectionTag, 'Values': selectionValue }]) +response = ec2.describe_instances(Filters=[{'Name':'tag:' + selectionTag, 'Values': selectionValue },{'Name':'instance-state-name', 'Value':['running']}]) for reservation in response['Reservations']: for instance in reservation['Instances']: - if instance['State']['Name'] == 'running': + #if instance['State']['Name'] == 'running': for tagDict in addTag: ec2.create_tags(Resources=[instance['InstanceId']], Tags=[{'Key': tagDict['Key'], 'Value': tagDict['Value']}]) diff --git a/AWS/getInstanceByTag.py b/AWS/getInstanceByTag.py index a0d08c2..edfa119 100644 --- a/AWS/getInstanceByTag.py +++ b/AWS/getInstanceByTag.py @@ -2,6 +2,16 @@ import boto3 import sys + +''' +Description : To list the running instances of an AWS region based on the Tag +Command Line Arguments : + * REGION_NAME: name of the region + * TAG_NAME: tag to use to filter + * TAG_VALUES: value to use for searching +''' + + Region = sys.argv[1] Tag = sys.argv[2] tagVALUE = sys.argv[3].split() diff --git a/AWS/tabluateawsdata/.fetchdate.py.swp b/AWS/tabluateawsdata/.fetchdate.py.swp new file mode 100644 index 0000000..719e493 Binary files /dev/null and b/AWS/tabluateawsdata/.fetchdate.py.swp differ diff --git a/AWS/tabluateawsdata/__init__.py b/AWS/tabluateawsdata/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/AWS/tabluateawsdata/__pycache__/fetchdate.cpython-33.pyc b/AWS/tabluateawsdata/__pycache__/fetchdate.cpython-33.pyc new file mode 100644 index 0000000..d7a1a13 Binary files /dev/null and b/AWS/tabluateawsdata/__pycache__/fetchdate.cpython-33.pyc differ diff --git a/AWS/tabluateawsdata/__pycache__/fibo.cpython-33.pyc b/AWS/tabluateawsdata/__pycache__/fibo.cpython-33.pyc new file mode 100644 index 0000000..e12fd22 Binary files /dev/null and b/AWS/tabluateawsdata/__pycache__/fibo.cpython-33.pyc differ diff --git a/AWS/tabluateawsdata/__pycache__/getinstance.cpython-33.pyc b/AWS/tabluateawsdata/__pycache__/getinstance.cpython-33.pyc new file mode 100644 index 0000000..0556f40 Binary files /dev/null and b/AWS/tabluateawsdata/__pycache__/getinstance.cpython-33.pyc differ diff --git a/AWS/tabluateawsdata/fetchdate.py b/AWS/tabluateawsdata/fetchdate.py new file mode 100644 index 0000000..5320a72 --- /dev/null +++ b/AWS/tabluateawsdata/fetchdate.py @@ -0,0 +1,37 @@ +#VPC = None +#STATE = None +#TAG = None + +def getEc2Information(region,**kargs): + + INPUTS = {} + INPUTS['REGION'] = region + + for key,value in kargs.items(): + if key == 'VPC': + #VPC = value + INPUTS['VPC'] = value + if key == 'STATE': + #STATE = value + INPUTS['STATE'] = value + if key == 'TAG': + #TAG = value + INPUTS['TAG'] = value + + return INPUTS + +def printParameter(INPUTS): + + for i,j in INPUTS.items(): + # print('Inside printParameter') + #print('{} : {}'.format(i,j)) + #print(VPC) + #print(STATE) + #print(TAG) + + if INPUTS[i]: + print('{} : {}'.format(i,j)) + + + +#def getinstance(region,) diff --git a/AWS/tabluateawsdata/fetchdate.pyc b/AWS/tabluateawsdata/fetchdate.pyc new file mode 100644 index 0000000..795220d Binary files /dev/null and b/AWS/tabluateawsdata/fetchdate.pyc differ diff --git a/AWS/tabluateawsdata/fibo.py b/AWS/tabluateawsdata/fibo.py new file mode 100644 index 0000000..1dc654c --- /dev/null +++ b/AWS/tabluateawsdata/fibo.py @@ -0,0 +1,17 @@ +# Fibonacci numbers module + +def fib(n): # write Fibonacci series up to n + a, b = 0, 1 + while b < n: + print(b, end=' ') + a, b = b, a+b + print() + +def fib2(n): # return Fibonacci series up to n + result = [] + a, b = 0, 1 + while b < n: + result.append(b) + a, b = b, a+b + return result + diff --git a/AWS/tabluateawsdata/getinstance.py b/AWS/tabluateawsdata/getinstance.py new file mode 100644 index 0000000..51475e8 --- /dev/null +++ b/AWS/tabluateawsdata/getinstance.py @@ -0,0 +1,35 @@ +#!/bin/env python3 + +''' + Getting the argument from the user + +''' +if __name__ == '__main__': + + from argparse import ArgumentParser + from argparse import RawTextHelpFormatter + from sys import exit + from fetchdate import getEc2Information + from fetchdate import printParameter + + parser = ArgumentParser(description='Printing EC2 query information', + prog='ec2query', + usage='%(prog)s [option]') + parser.add_argument('--version', '-V', action='version', version='%(prog)s 0.1') + parser.add_argument('--tag', '-t', action='store', dest='TAG', type=str, help='query by tag') + parser.add_argument('--state','-s', action='store', dest='STATE', type=str, help='query by state', nargs='*',choices=['running','stop'],default=['running','stop']) + parser.add_argument('--vpc', '-v', action='store', dest='VPC', type=str, help='query by vpc') + + arguments = parser.parse_args() + + if (arguments.VPC or arguments.STATE or arguements.TAG) is None: + parser.print_help() + exit() + + + INPUTS = getEc2Information('us-west-2b',VPC=arguments.VPC, STATE=arguments.STATE, TAG=arguments.TAG) + + printParameter(INPUTS) + + + diff --git a/AWS/test.py b/AWS/test.py new file mode 100644 index 0000000..9c37cf9 --- /dev/null +++ b/AWS/test.py @@ -0,0 +1 @@ +import diff --git a/README b/README index 985424d..0a3a155 100644 --- a/README +++ b/README @@ -1 +1 @@ -Python Scripts written while learning python programming language +This file contains python scripts which were written while learning Python Programming language diff --git a/misc/test.py b/misc/test.py new file mode 100644 index 0000000..db0489a --- /dev/null +++ b/misc/test.py @@ -0,0 +1,7 @@ +N = int(input().strip()) +B = [int(B_temp) for B_temp in input().strip().split(' ')] +idx = [i for i, x in enumerate(B) if x % 2 == 1 ] +if len(idx) % 2 == 1: + print("NO") +else: + print(sum([(idx[i+1]-idx[i])*2 for i in range(0,len(idx),2)])) diff --git a/misc/testsomething.py b/misc/testsomething.py new file mode 100644 index 0000000..c4bebc6 --- /dev/null +++ b/misc/testsomething.py @@ -0,0 +1,115 @@ +#!/bin/env python + + def atomic_move(self, src, dest, unsafe_writes=False): + '''atomically move src to dest, copying attributes from dest, returns true on success + it uses os.rename to ensure this as it is an atomic operation, rest of the function is + to work around limitations, corner cases and ensure selinux context is saved if possible''' + context = None + dest_stat = None + b_src = to_bytes(src, errors='surrogate_or_strict') + b_dest = to_bytes(dest, errors='surrogate_or_strict') + if os.path.exists(b_dest): + try: + dest_stat = os.stat(b_dest) + + # copy mode and ownership + os.chmod(b_src, dest_stat.st_mode & PERM_BITS) + os.chown(b_src, dest_stat.st_uid, dest_stat.st_gid) + + # try to copy flags if possible + if hasattr(os, 'chflags') and hasattr(dest_stat, 'st_flags'): + try: + os.chflags(b_src, dest_stat.st_flags) + except OSError as e: + for err in 'EOPNOTSUPP', 'ENOTSUP': + if hasattr(errno, err) and e.errno == getattr(errno, err): + break + else: + raise + except OSError as e: + if e.errno != errno.EPERM: + raise + if self.selinux_enabled(): + context = self.selinux_context(dest) + else: + if self.selinux_enabled(): + context = self.selinux_default_context(dest) + + creating = not os.path.exists(b_dest) + + try: + # Optimistically try a rename, solves some corner cases and can avoid useless work, throws exception if not atomic. + os.rename(b_src, b_dest) + except (IOError, OSError) as e: + if e.errno not in [errno.EPERM, errno.EXDEV, errno.EACCES, errno.ETXTBSY, errno.EBUSY]: + # only try workarounds for errno 18 (cross device), 1 (not permitted), 13 (permission denied) + # and 26 (text file busy) which happens on vagrant synced folders and other 'exotic' non posix file systems + self.fail_json(msg='Could not replace file: %s to %s: %s' % (src, dest, to_native(e)), + exception=traceback.format_exc()) + else: + b_dest_dir = os.path.dirname(b_dest) + # Use bytes here. In the shippable CI, this fails with + # a UnicodeError with surrogateescape'd strings for an unknown + # reason (doesn't happen in a local Ubuntu16.04 VM) + native_dest_dir = b_dest_dir + native_suffix = os.path.basename(b_dest) + native_prefix = b('.ansible_tmp') + error_msg = None + tmp_dest_name = None + try: + tmp_dest_fd, tmp_dest_name = tempfile.mkstemp(prefix=native_prefix, dir=native_dest_dir, suffix=native_suffix) + except (OSError, IOError) as e: + error_msg = 'The destination directory (%s) is not writable by the current user. Error was: %s' % (os.path.dirname(dest), to_native(e)) + except TypeError: + # We expect that this is happening because python3.4.x and + # below can't handle byte strings in mkstemp(). Traceback + # would end in something like: + # file = _os.path.join(dir, pre + name + suf) + # TypeError: can't concat bytes to str + error_msg = ('Failed creating temp file for atomic move. This usually happens when using Python3 less than Python3.5. ' + 'Please use Python2.x or Python3.5 or greater.') + finally: + if error_msg: + if unsafe_writes: + self._unsafe_writes(b_src, b_dest) + else: + self.fail_json(msg=error_msg, exception=traceback.format_exc()) + + if tmp_dest_name: + b_tmp_dest_name = to_bytes(tmp_dest_name, errors='surrogate_or_strict') + + try: + try: + # close tmp file handle before file operations to prevent text file busy errors on vboxfs synced folders (windows host) + os.close(tmp_dest_fd) + # leaves tmp file behind when sudo and not root + try: + shutil.move(b_src, b_tmp_dest_name) + except OSError: + # cleanup will happen by 'rm' of tempdir + # copy2 will preserve some metadata + shutil.copy2(b_src, b_tmp_dest_name) + + if self.selinux_enabled(): + self.set_context_if_different( + b_tmp_dest_name, context, False) + try: + tmp_stat = os.stat(b_tmp_dest_name) + if dest_stat and (tmp_stat.st_uid != dest_stat.st_uid or tmp_stat.st_gid != dest_stat.st_gid): + os.chown(b_tmp_dest_name, dest_stat.st_uid, dest_stat.st_gid) + except OSError as e: + if e.errno != errno.EPERM: + raise + try: + os.rename(b_tmp_dest_name, b_dest) + except (shutil.Error, OSError, IOError) as e: + if unsafe_writes and e.errno == errno.EBUSY: + self._unsafe_writes(b_tmp_dest_name, b_dest) + else: + self.fail_json(msg='Unable to rename file: %s to %s: %s' % (src, dest, to_native(e)), + exception=traceback.format_exc()) + except (shutil.Error, OSError, IOError) as e: + self.fail_json(msg='Failed to replace file: %s to %s: %s' % (src, dest, to_native(e)), + exception=traceback.format_exc()) + finally: + self.cleanup(b_tmp_dest_name) diff --git a/network/banner.py b/network/banner.py new file mode 100644 index 0000000..56e9608 --- /dev/null +++ b/network/banner.py @@ -0,0 +1,42 @@ +from socket import AF_INET +from socket import SOCK_STREAM +from socket import socket +from socket import gethostbyname +from sys import exit +from util import * + +def grab(host,port): + + ''' + Function to grab the banner of a port + + Arguments: + socketobject: A socket object which is already connected + port: The port to which we want to connect + ''' + + socketobject = createsocket() + + if not setupconnection(socketobject,host,port): + print('Connection Failure') + return + + try: + if port == 80: + socketobject.send(b"Get HTTP/1.1 \r\n") +# print('Packet sent') + else: + socketobject.send(b"\r\n") + + results = socketobject.recv(4096) +# print('Result received') + + print('Banner : ' + results.decode()) + + + except: + print("Banner not available") + + finally: +# print('Closing socket') + closesocket(socketobject) diff --git a/network/util.py b/network/util.py new file mode 100644 index 0000000..5274680 --- /dev/null +++ b/network/util.py @@ -0,0 +1,75 @@ +from socket import AF_INET +from socket import SOCK_STREAM +from socket import socket +from socket import gethostbyname +from sys import exit + + +def createsocket(): + ''' + Python function to create to socket object + + Argument : None + Return : socket object with of AF_INET family with stream as SOCK_STREAM + + ''' + try: + #print('Creating socket') + return socket(AF_INET, SOCK_STREAM) + except: + print("Socket cannot be created") + return Null + +def closesocket(name): + ''' + Python function to close socket connection + + Argument : + name: Name of socket object + Return : None + + ''' + try: + #print('Closing socket') + name.close() + except: + print("Socket cannot be close") + + +def setupconnection(name,host,port): + ''' + Python function to setup the connection to a port on a host + + Argument : + name: Name of socket object + host: Host where we need to connect + port: Port where we need to connect + + Return : None on failure, otherwise True. + ''' + + if not isinstance(name,socket): + print('socket object should be passed') + closesocket(name) + return None + + try: + gethostbyname(host) + except: + print('Host Name is not reachable') + closesocket(name) + return None + + if not isinstance(port,int): + print("Port number should be integer") + closesocket(name) + return None + + try: + name.connect((host,port)) + return True + except: + #print('Connection Refused') + closesocket(name) + return None + diff --git a/stringReplace.py b/stringReplace.py new file mode 100644 index 0000000..b837089 --- /dev/null +++ b/stringReplace.py @@ -0,0 +1,10 @@ +#!/bin/env python3 + +''' + Python script to perform substitution of a word in a fil + + +''' + +def substitue(word, replace): +