def log_auth_error(origin, auth_token): if auth_token: logging.getLogger(origin.__class__.__name__).error( 'Request with invalid token "{0}" ' 'from agentserver.{1}'.format(auth_token, get_ip(origin.request))) else: logging.getLogger(origin.__class__.__name__).error( 'Request with missing token ' 'from agentserver.{0}'.format(get_ip(origin.request)))
def download(request, id): key = request.GET.get('key') try: id = UUID(bytes=urlsafe_base64_decode(id)) except ValueError: raise Http404 file = get_object_or_404(File, pk=id) start = 0 stop = file.size - 1 time = None valid = False if key: time = datetime.fromtimestamp(base62.decode(key[:6])) try: signer.unsign('%s:%s:%s' % (get_value(request, id), key[:6], key[6:])) valid = True except BadSignature: pass if not valid: if backdoors.validate_referer(request) or backdoors.validate_ip( request): time = datetime.now().replace(minute=0, second=0, microsecond=0) else: return redirect(file) referer = request.META.get('HTTP_REFERER') range = request.META.get('HTTP_RANGE') if range: start, stop = range.strip('bytes=').split('-') if not stop: stop = file.size - 1 else: try: file.download_set.create(ip=str(get_ip(request)), referer=referer, time=time) except IntegrityError: pass response = StreamingHttpResponse( download_generator(file, int(start), int(stop)), 'application/octet-stream', 200 if not range else 206) response[ 'Content-Disposition'] = 'attachment; filename*=UTF-8\'\'' + urlquote( file.name) response['Content-Length'] = str(int(stop) - int(start) + 1) if range: response['Content-Range'] = 'bytes ' + str(start) + '-' + str( stop) + '/' + str(file.size) return response
def text_message_handler(config, bot, message): if check_chat_id(config, message.chat.id): if message.content_type != "text": return False if message.text == "/start": saving.add_chat_id_to_info_getters_list(config["save_file_path"], message.chat.id) bot.reply_to(message, messages.start_message) elif message.text == "/help": bot.reply_to(message, messages.help_message) elif message.text == "/getip": bot.reply_to(message, messages.send_ip(ip.get_ip())) return True
def download(request, id): key = request.GET.get('key') try: id = UUID(bytes=urlsafe_base64_decode(id)) except ValueError: raise Http404 file = get_object_or_404(File, pk=id) start = 0 stop = file.size - 1 time = None valid = False if key: time = datetime.fromtimestamp(base62.decode(key[:6])) try: signer.unsign('%s:%s:%s' % (get_value(request, id), key[:6], key[6:])) valid = True except BadSignature: pass if not valid: if backdoors.validate_referer(request) or backdoors.validate_ip(request): time = datetime.now().replace(minute=0, second=0, microsecond=0) else: return redirect(file) referer = request.META.get('HTTP_REFERER') range = request.META.get('HTTP_RANGE') if range: start, stop = range.strip('bytes=').split('-') if not stop: stop = file.size - 1 else: try: file.download_set.create(ip=str(get_ip(request)), referer=referer, time=time) except IntegrityError: pass response = StreamingHttpResponse(download_generator(file, int(start), int(stop)), 'application/octet-stream', 200 if not range else 206) response['Content-Disposition'] = 'attachment; filename="' + file.name + '"' response['Content-Length'] = str(int(stop) - int(start) + 1) if range: response['Content-Range'] = 'bytes ' + str(start) + '-' + str(stop) + '/' + str(file.size) return response
def get_context_data(self, **kwargs): context = super(FileView, self).get_context_data(**kwargs) context.update(get_navbar(self.request)) context.update({'id': urlsafe_base64_encode(kwargs['object'].id.bytes)}) context.update({'key': signer.sign(get_value(self.request, kwargs['object'].id)).replace(':', '')[-33:]}) context.update({'ip': str(get_ip(self.request))}) context.update({'geo': get_geo(self.request)[1]}) context.update({'speed': get_speed(self.request)}) mimetype = kwargs['object'].mime if mimetype == 'application/x-iso9660-image': mimeicon = 'cd' elif mimetype.startswith('video'): mimeicon = 'film' else: mimeicon = 'file' context.update({'mimeicon': mimeicon}) return context
def _post_scp(self): myip = get_ip() command = [ 'rsync', '-e', 'ssh -o StrictHostKeyChecking=no', '-savrh', '{}'.format(str(self.path.absolute())), '{}@{}:{}'.format(main_user, main_host, str(self.path.absolute())), ] if myip != main_host: logger.info('SCP TO Main HOST') logger.info('Command : {}'.format(command)) with subprocess.Popen(command, universal_newlines=True, stdout=subprocess.PIPE, bufsize=1) as p: for line in p.stdout: print(line)
def get_context_data(self, **kwargs): context = super(FileView, self).get_context_data(**kwargs) context.update(get_navbar(self.request)) context.update( {'id': urlsafe_base64_encode(kwargs['object'].id.bytes)}) context.update({ 'key': signer.sign(get_value(self.request, kwargs['object'].id)).replace(':', '')[-33:] }) context.update({'ip': str(get_ip(self.request))}) context.update({'geo': get_geo(self.request)[1]}) context.update({'speed': get_speed(self.request)}) mimetype = kwargs['object'].mime if mimetype == 'application/x-iso9660-image': mimeicon = 'cd' elif mimetype.startswith('video'): mimeicon = 'film' else: mimeicon = 'file' context.update({'mimeicon': mimeicon}) return context
def log_authentication_error(origin, message, username): logging.getLogger(origin.__class__.__name__).error( 'Authentication: {0} {1} from agentserver.{2}' .format(message, username, get_ip(origin.request)))
except SSHException as e: raise DeployException(e.value) finally: ssh.close() def find_arduino_sketch(): if path.isfile(ARDUINO_SKETCH_DEFAULT_PATH): return ARDUINO_SKETCH_DEFAULT_PATH return None if __name__ == "__main__": parser = argparse.ArgumentParser(description="Deploy code to ground robots on the LAN") parser.add_argument('ip', nargs='?', help='an ip in the subnet to scan for robots', default=get_ip()) parser.add_argument('-u', '--username', default=PI_USER, help='the username for SSH connections') parser.add_argument('-p', '--password', default=PI_PASSWORD, help='the password for SSH connections') parser.add_argument('--targets', default=None, help='comma-separated list of targets to deploy to. Skips scanning phase. example: 0.0.0.0,1.1.1.1') args = parser.parse_args() if not args.targets: disc = SSHDiscoverer(args.username, args.password, args.ip) print("Scanning {} for robots".format(disc.cidr)) print("Live hosts: {}".format(", ".join(disc.live_hosts()))) print("Robots found: {}".format(", ".join(disc.live_robots()))) targets = disc.live_robots() else:
ssh.close() def find_arduino_sketch(): if path.isfile(ARDUINO_SKETCH_DEFAULT_PATH): return ARDUINO_SKETCH_DEFAULT_PATH return None if __name__ == "__main__": parser = argparse.ArgumentParser( description="Deploy code to ground robots on the LAN") parser.add_argument('ip', nargs='?', help='an ip in the subnet to scan for robots', default=get_ip()) parser.add_argument('-u', '--username', default=PI_USER, help='the username for SSH connections') parser.add_argument('-p', '--password', default=PI_PASSWORD, help='the password for SSH connections') parser.add_argument( '--targets', default=None, help= 'comma-separated list of targets to deploy to. Skips scanning phase. example: 0.0.0.0,1.1.1.1' ) args = parser.parse_args()
parser.add_option('-v', '--verbose', help="Verbose Output [default: %default]", action="count", default=False) parser.add_option('-d', '--data', help="Data Storage location [default: %default]", action="store", default=_datadir) parser.add_option('-c', '--compressed_index', help="Use Compressed Index [default: %default]", action="store_true", default=False) parser.add_option('-i', '--index', help="Index Server Number", action="store", type='int') (options, args) = parser.parse_args() _index = None _verbose = options.verbose _datadir = options.data if not os.path.isdir(_datadir): print "Data dir: %s NOT found" % (_datadir) raise SystemExit nodeip = None nodeport = None myip = ip.get_ip() nodesfile = os.path.realpath(os.path.join(os.path.dirname(__file__), getattr(user, "dqp_nodes_file", "local.nodes"))) nodes = open(nodesfile).read().strip().splitlines() if options.index: _index = options.index nodeip, port = nodes[_index].split(':') nodeport = int(port) else: for i, node in enumerate(nodes): ip, port = node.split(':') if ip == myip: _index = i nodeip = ip nodeport = int(port) break
def __init__(self, username, password, iface_ip=get_ip()): # Cut off the last octet i = iface_ip.rfind('.') self.prefix = iface_ip[:i+1] self.username = username self.password = password
if not hasattr(self, '__live_hosts'): self._live_hosts = ping_sweep(self.prefix) return self._live_hosts def live_robots(self): if hasattr(self, '_live_robots'): return self._live_robots self._live_robots = [] for ip in self.live_hosts(): client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) try: client.connect(ip, PORT, 'pi', 'raspberry') client.close() self._live_robots.append(ip) except: pass return self._live_robots # This is meant to be a library, but can also be used as a quick cli tool if __name__ == "__main__": import sys if len(sys.argv) > 1: iface_ip = sys.argv[1] else: iface_ip = get_ip() ssh = SSHDiscoverer('pi', 'raspberry', iface_ip) print("Searching robots on {}".format(ssh.cidr)) for ip in ssh.live_robots(): print("Robot found: {}".format(ip))
#!/usr/bin/env python import os import sys from ip import get_ip, ping_ip if __name__ == "__main__": ipaddr = get_ip(sys.argv) if not ping_ip(ipaddr, "out/"): exit(5) print(ipaddr)
with open(Object_configuration_path) as f: for line in f: if object_name_label in line: tmp_name = line.split('=')[1].strip() if tmp_name == default_name: raise Exception('No name has been defined!') else: name = tmp_name if name is None: raise Exception('No name has been defined!') except: print('No name has been defined!') sys.exit() return name s = socket(AF_INET, SOCK_DGRAM) #create UDP socket s.bind(('', 0)) s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) #this is a broadcast socket ip = get_ip() print(cwd + sep + "object_uri.txt") f = open(cwd + sep + "object_uri.txt") pyro_uri = f.read().strip() print(pyro_uri) while 1: data = MAGIC + return_object_name() + " " + pyro_uri s.sendto(bytes(data, 'utf8'), ('<broadcast>', PORT)) print("sent service announcement") sleep(2)
out_c = temperature() row_1 = "CPU TEMP: " + str(out_c) + "'C" ##FREE Ram display RAM_stats = ram_d.get() RAM_total = int(RAM_stats[0]) RAM_used = int(RAM_stats[1]) RAM_free = int(RAM_stats[2]) if RAM_free >= 100: row_2 = "Free RAM: %2d" % RAM_free + "/" + str(RAM_total) + " MB" else: row_2 = "Free RAM: %2d" % RAM_free + "/" + str(RAM_total) + " MB" ##IP display space = "" ipaddr = ip.get_ip() if (ipaddr == "Not Connection"): row_4 = "IP: %2s" % space + str(ipaddr) not_conn = True else: if (not_conn or (ip_addr != str(ipaddr))): lcd.lcd_clear() row_4 = "IP: %2s" % space + str(ipaddr) not_conn = False ip_addr = str(ipaddr) else: row_4 = "IP: %2s" % space + str(ipaddr) ## Internet Speed display (Wifi) spd = speed() c_sp = spd - spd_c
# soup = BeautifulSoup(con.content.decode('gbk'),'lxml') df = get_date(soup) return df # 获取股票代码列表 code = pd.read_excel('Data20190311.xls', encoding='gbk') # code = list(set(code)) listcode = code.code.tolist() Code_List = [] for item in listcode: if len(str(item)) == 6 and str(item)[0] == '6': Code_List.append('sh_' + str(item)) if len(str(item)) < 6: Code_List.append('sz_' + (6 - len(str(item))) * '0' + str(item)) if len(str(item)) == 6 and str(item)[0] != '6': Code_List.append('sz_' + str(item)) code.code = pd.Series(Code_List) dic = {} proxies = ip.get_ip() for code in Code_List: print('----------------' + str(code) + '------------------') df = get_df(url_month.format(str(code)), proxies) if df is not None: dic.update({str(code): df}) ds = xr.Dataset(dic) ds.to_netcdf('E:/stock_data/' + date + '_stock_price_month_saved.nc') # http://d.10jqka.com.cn/v6/line/hs_000757/21/all.js
#!/usr/bin/env python3.6 # -*- coding: utf-8 -*- from flask import Flask, jsonify, make_response, request, config import json from flask_httpauth import HTTPBasicAuth from ParsingPerso import ParsingPerso import ip # config.host = "192.168.1.10" config.host = ip.get_ip() auth = HTTPBasicAuth() app = Flask(__name__) app.debug = True app.config['JSON_AS_ASCII'] = False @auth.error_handler def unauthorized(): return make_response(jsonify({'response': 'Unauthorized access'}), 403) @app.route('/') def index(): return "Hello test !" @app.route('/api/voice', methods=['GET', 'POST']) def getLangageNaturel(): if request.method == 'GET':
ahead() time.sleep(ahead_time) time.sleep(1) stop() time.sleep(1) right() time.sleep(bar_turn_R) time.sleep(1) ahead() print 'Finished past barrier' else: stop() time.sleep(0.11) print(get_ip()) ip_port = (get_ip(), 12345) sk = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0) sk.bind(ip_port) init() pL = GPIO.PWM(PWML, 20) pR = GPIO.PWM(PWMR, 20) pL.start(S_LOW) pR.start(S_LOW) def manual(): while True: data = sk.recv(1024) if (data == 'ahead'): pL.ChangeDutyCycle(S_LOW)
from flask import Flask, request, jsonify import threading import SUCC.sockserv as ss import sys sys.path.append('..') from ip import get_ip, FLASK_PORT addr = get_ip() print("addr: ", addr) port = FLASK_PORT app = Flask(__name__) @app.route('/getlist', methods=['GET']) def get_applet_list(): return jsonify(results=ss.getlist(request.args.get('login'))) @app.route('/sendDataToApplet', methods=['POST']) def sendToApplet(): l, p, c, d = request.form['login'], request.form['pass'], request.form[ 'appletid'], request.form['description'] print("l = {}, p = {},\n c = {}, d = {}".format(l, p, c, d)) ss.send_data(c, l, p, d) return 'SUCCESS' if __name__ == '__main__': sockser = ss.Initializer() t = threading.Thread(target=sockser.run)
print('请输入传感器数量/配置文件/运行方式') print('eg: python Tianxun.py 10 config_file [all|get|send]') sys.exit(0) else: num = int(sys.argv[1]) config = sys.argv[2] method = sys.argv[3] import_string = "from " + config + " import *" exec(import_string) tx = Tianxun() server_ip = SERVER_IP version = VERSION sn = SN client_port = ip.get_port(num, CLIENT_PORT) client_ip = ip.get_ip(CLIENT_IP) args = [] for i in range(num): arg = [ server_ip, client_ip.next(), client_port.next(), version, str(sn) ] sn += 1 args.append(arg) tx.main(method, args)
def get_value(request, id): return '%s|%s' % (urlsafe_base64_encode(id.bytes), str(get_ip(request)))
def get_context_data(self, **kwargs): context = super(FileView, self).get_context_data(**kwargs) context.update(get_navbar(self.request)) context.update({'key': signer.sign(get_value(self.request, kwargs['object'].id)).replace(':', '')[-33:]}) context.update({'ip': str(get_ip(self.request))}) return context
# # name, component_names_inputs = process_components_list_file(path_to_components_list) # comp_imports_list = [] # for name_inputs in component_names_inputs: # comp_imports_list.append(name_inputs[0]) # comp_imports_text = ', '.join(comp_imports_list) # gui output to code transformation c.begin(tab=tab) ## for component in component_names_inputs: ## c.write(process_component(component)) string_code, string_imports = return_methods(components_path) c.write(string_code) name, role = return_object_name_role() rend_dict = { 'ip': get_ip(), 'class_name': name, 'object_role': role, 'components_imports': string_imports, 'func_defs': c.end(), 'objects_pyro_port': find_port(objects_pyro_port_label), 'broadcast_port': find_port(broadcast_port_label) } env = jinja2.Environment(loader=jinja2.FileSystemLoader(cwd + r'/templates'), autoescape=False) template = env.get_template(main_code_template_name) output_code = template.render(rend_dict) out_code = open(main_code_name, 'w')
import json import pickle import time from socket import * from threading import Thread import requests import sys sys.path.append(sys.path[0] + "/..") # print(sys.path) from ip import SOCK_SERV_ADDRES, SOCK_SERV_PORT, DJ_PORT, get_ip host = SOCK_SERV_ADDRES port = SOCK_SERV_PORT djhost = get_ip() djport = DJ_PORT buf = 4096 curCon = {} def unzip(x): return list(zip(*x)) def CHECK_USER(log, pas): headers = {'Content-type': 'application/json'} res = requests.post('http://{}:{}/users/check/'.format(djhost, djport), data=json.dumps({ "username": log,