From e4338e18da24066a6bd9469ff9d73b5861d7c9b0 Mon Sep 17 00:00:00 2001 From: nitanka Date: Tue, 19 Sep 2017 13:20:41 +0530 Subject: [PATCH 1/4] Initial script for string replacement --- stringReplace.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 stringReplace.py 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): + From e1584bd94b9d570a2382da56608cb4e5d2c3856c Mon Sep 17 00:00:00 2001 From: nitanka Date: Tue, 19 Sep 2017 13:22:44 +0530 Subject: [PATCH 2/4] Added initial package to work with AWS ec2 --- AWS/addInstanceTag.py | 4 +- AWS/getInstanceByTag.py | 10 +++++ AWS/tabluateawsdata/.fetchdate.py.swp | Bin 0 -> 12288 bytes AWS/tabluateawsdata/__init__.py | 0 .../__pycache__/fetchdate.cpython-33.pyc | Bin 0 -> 937 bytes .../__pycache__/fibo.cpython-33.pyc | Bin 0 -> 631 bytes .../__pycache__/getinstance.cpython-33.pyc | Bin 0 -> 1582 bytes AWS/tabluateawsdata/fetchdate.py | 37 ++++++++++++++++++ AWS/tabluateawsdata/fetchdate.pyc | Bin 0 -> 810 bytes AWS/tabluateawsdata/fibo.py | 17 ++++++++ AWS/tabluateawsdata/getinstance.py | 35 +++++++++++++++++ AWS/test.py | 1 + README | 2 +- 13 files changed, 103 insertions(+), 3 deletions(-) create mode 100644 AWS/tabluateawsdata/.fetchdate.py.swp create mode 100644 AWS/tabluateawsdata/__init__.py create mode 100644 AWS/tabluateawsdata/__pycache__/fetchdate.cpython-33.pyc create mode 100644 AWS/tabluateawsdata/__pycache__/fibo.cpython-33.pyc create mode 100644 AWS/tabluateawsdata/__pycache__/getinstance.cpython-33.pyc create mode 100644 AWS/tabluateawsdata/fetchdate.py create mode 100644 AWS/tabluateawsdata/fetchdate.pyc create mode 100644 AWS/tabluateawsdata/fibo.py create mode 100644 AWS/tabluateawsdata/getinstance.py create mode 100644 AWS/test.py 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 0000000000000000000000000000000000000000..719e493eb123419e7db1db12411ca3098e2c224d GIT binary patch literal 12288 zcmeI2&1(}u7>B1GyworBB6x5#huzeC)K;tnb0`u^Kx0YLXemXen@PHDvb*d~YD0(~ z3xasigI)wb4qo&i-lck0kKVj_(Lcbezx_zkswws&6yAY{N%oz2=bdL}520NeujH@t zsnj`!c7(CJw_nd!PoCd@Z;dg_RKi*nb-Qkxet1|bgyV*V`_I$1qtZ@WE!$SqB~?q= zt|=Pn>FcGm5=)JiP*U9TszQl$O)6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ff --git a/AWS/tabluateawsdata/__pycache__/getinstance.cpython-33.pyc b/AWS/tabluateawsdata/__pycache__/getinstance.cpython-33.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0556f403733a6f58509763e383700b2128c74c1c GIT binary patch literal 1582 zcmZ`&TW{1x6h32b_F^_+6VgCini|>^lj6|k5mi+q6lh;iL?Wavsx0F(**L5(^~?Y( z)TjL)eXV%r7xB>l(KBb($+n{FUGKSk^PTJbIb03izx(Ugw<`b{EPXae{)v9-ZvlV+ zV*n`t1-$g2`5@2(^kM2j;ltPm);p|sVBB%~3QSj^=)$;5dKa(<(;gIk826ptXMF(U z0SM^>4gdqdD}Y15RlqfvgFg;H25?TstAHcGb-)e&UW2*kiG^nRL^Fh3xWQNuBNk?gB=O)40t7m4AbU4VVjG z$bmaWm46H8TMO)5kdwH`dat#Ptf{ret<|!yl>$;W$I*Qnx7npv5Yp$d)H*LGp+1vg z+DuF#OC6pzRlydcWD^E~=@UFjiZm~iBqtdnS{E>D^g37^I!YS?JNqWtpQf)*%J z;mkJaM;2lWIefSu{%&M53-e1VV`J7$HQ`ERw$BJdw*ibwC(_sib|QKBKmtZFu*JWb8irAmd@nG5xb6Mc5{@ZV`!e?a6$#jmNFc>e{rm(1aV@a-S$ z<7Av_mxwB1EOxA<87~w{zP3yCku@{_w_%*9nkg>JE*a18RO;*u zZRb9^XdK`_J7%ZM(HpKgMNHc3;bQ29>tl>{DUQ@))J4ba9Nds>tE^wzJLUlG?4MMn zbaZx&6W#!Okdxw#bGITQ8(hB3h}6CNbaV2O8eL{`uby!ue<&(6Q~9GUL*1iSR}8(8 eSUmnvbj3j26p?r&B5&y35`hT(9k1tY(en=$XI`HG literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..795220d457b54942a87a4a21f4080fce38a2048e GIT binary patch literal 810 zcmb_aO;6iE5S_K-1SqKlsVeox(U;azj}@vKg(yXpQshJ+5It<;CFIKv-U%PVzBIk{ zxA5!u1ARLQLfo-EZ^zHi&oevrAM0Cx{D;#4tq+Cu8^XQ^Bt(CS&X6cc6eS+@LLZL? zPPl=nAbue1KR`iLdUQLcLeZFLNp$e*oX$NeeJU%?W~`|2si@G>qt17vaGZFQw;fjo zl)?n0FXWk!)hDtdWJAarT{YZwk_6%zP*J6#MoS;IsJj4#$10WUP?8 Date: Tue, 19 Sep 2017 13:25:21 +0530 Subject: [PATCH 3/4] initial commit for network modules --- misc/test.py | 7 +++ misc/testsomething.py | 115 ++++++++++++++++++++++++++++++++++++++++++ network/banner.py | 42 +++++++++++++++ network/connection.py | 75 +++++++++++++++++++++++++++ 4 files changed, 239 insertions(+) create mode 100644 misc/test.py create mode 100644 misc/testsomething.py create mode 100644 network/banner.py create mode 100644 network/connection.py 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..fd82a64 --- /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 connection 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/connection.py b/network/connection.py new file mode 100644 index 0000000..5274680 --- /dev/null +++ b/network/connection.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 + From 470f6d72613703217cc0695eb71004eef4901e45 Mon Sep 17 00:00:00 2001 From: nitanka Date: Tue, 19 Sep 2017 13:27:59 +0530 Subject: [PATCH 4/4] Restructuring the naming convention --- network/banner.py | 2 +- network/{connection.py => util.py} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename network/{connection.py => util.py} (100%) diff --git a/network/banner.py b/network/banner.py index fd82a64..56e9608 100644 --- a/network/banner.py +++ b/network/banner.py @@ -3,7 +3,7 @@ from socket import socket from socket import gethostbyname from sys import exit -from connection import * +from util import * def grab(host,port): diff --git a/network/connection.py b/network/util.py similarity index 100% rename from network/connection.py rename to network/util.py