#!/usr/bin/env python import ssl import jsonrpclib from pprint import pprint from getpass import getpass ssl._create_default_https_context = ssl._create_unverified_context ip = '184.105.247.72' port = '443' username = '******' password = getpass() url = 'https://{}:{}@{}:{}/command-api'.format(username, password, ip, port) print url eapi_connect = jsonrpclib.Server(url) response = eapi_connect.runCmds(1, ['show version']) pprint(response)
the interfaces on the switch. Accomplish this directly using jsonrpclib. ''' import jsonrpclib from pprint import pprint arista_dict = dict( ip='10.10.10.10', port=8543, username='******', password='******', ) eapi_url = 'https://{username}:{password}@{ip}:{port}/command-api'.format( **arista_dict) eapi_conn = jsonrpclib.Server(eapi_url) interfaces = eapi_conn.runCmds(1, ["show interfaces"]) # Strip off unneeded data structures interfaces = interfaces[0]['interfaces'] # inOctets/outOctets are fields inside 'interfaceCounters' dict data_stats = {} for interface, int_values in interfaces.items(): int_counters = int_values.get('interfaceCounters', {}) data_stats[interface] = (int_counters.get('inOctets'), int_counters.get('outOctets')) # Print output data print "\n{:20} {:<20} {:<20}".format("Interface:", "inOctets", "outOctets")
def __init__(self, host='localhost', port=6464): address = 'http://%s:%d/cloudi/api/json_rpc/' % (host, port) self.__server = jsonrpclib.Server(address)
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore') value = unicode(re.sub('[^\w\s-]', '', value).strip().lower()) value = unicode(re.sub('[-\s]+', '-', value)) return value def we_to_filename(we): return '%s - ' % we['_id'] + slugify(we['name']) # SCRIPT # Hyphe connect try: hyphe_api = jsonrpclib.Server( 'http://%s:%s' % (settings['hyphe_host'], settings['hyphe_port']), version=1) except Exception as e: sys.stderr.write("%s: %s\n" % (type(e), e)) sys.stderr.write('ERROR: Could not initiate connection to hyphe core\n') sys.exit(1) res = hyphe_api.ping(settings['corpus_id'], 10) if "message" in res: sys.stderr.write( "ERROR: please start or create corpus %s before indexing it: %s\n" % (settings['corpus_id'], res['message'])) sys.exit(1) # MongoDB connect from pymongo import MongoClient client = MongoClient('localhost', settings['mongodb_port'])
import numpy as np import gp_conf as neat_gp from deap import creator from speciation import calc_intracluster from conf_primitives import conf_sets import evoworker_gp as evoworker import jsonrpclib import yaml import os config = yaml.load(open("conf/conf.yaml")) num_var = config["num_var"] pset = conf_sets(num_var) toolbox = evoworker.getToolBox(config, pset) server = jsonrpclib.Server(config["server"]) def counter(): r = server.get_CounterSpecie() rs_species = [] for i in range(1, int(r) + 1): rs_species.append(int(server.getSpecieInfo(i)['specie'])) pop = [] for sp in rs_species: evospace_sample = server.getSample_specie(sp) for cs in evospace_sample['sample']: i = creator.Individual( neat_gp.PrimitiveTree.from_string(cs['chromosome'], pset)) if isinstance(cs['params'], list): i.params_set(np.asarray(cs['params'])) elif isinstance(cs['params'], unicode):
def get_client(self): client = jsonrpclib.Server('http://localhost:%d' % self.port) return client
def create_bitcoin_address(address=None): if not address: address = get_rpc_address() server = jsonrpclib.Server(address) new_addr = server.getnewaddress() return new_addr
class TestRegApp(unittest.TestCase): server_ip, server_port = get_server_conf('registration_app_config.json') server = jsonrpclib.Server('http://%s:%s' % (server_ip, server_port)) def test_register_with_non_unique_username(self): ''' Registration with non-unique user names should not be allowed :return: ''' first_name = ['TestFirstName_100', 'TestFirstName_101'] last_name = ['TestLastName_100' , 'TestLastName_101'] email = ['*****@*****.**', '*****@*****.**'] user_name = 'test_username_100' for index in range(0, 2): public_key_value, private_key_value = get_ssh_keys(first_name[index], last_name[index]) #create unique public private key pair ret_values = self.server.register_user(first_name[index], last_name[index], user_name, email[index], public_key_value) if len(ret_values) == 2: member, key = ret_values[:2] else: member = None # First registration has unique parameters so it should succeed if index == 0: self.assertIsNotNone(member) # First registration has non-unique user_name so it should fail if index == 1: self.assertIsNone(member) def test_register_with_non_unique_email(self): ''' User registration is allowed for non-unique email address as long as user name and public key is unique :return: ''' first_name = ['TestFirstName_200', 'TestFirstName_201'] last_name = ['TestLastName_200' , 'TestLastName_201'] user_name = ['test_username_200', 'test_username_201'] email = '*****@*****.**' for index in range(2): public_key_value, private_key_value = get_ssh_keys(first_name[index], last_name[index]) #create unique public private key pair ret_values = self.server.register_user(first_name[index], last_name[index], user_name[index], email, public_key_value) if len(ret_values) == 2: member, key = ret_values[:2] else: member = None #Registration should succeed for all combinations self.assertIsNotNone(member) def test_register_with_non_unique_public_key(self): ''' User registration should fail if non-unique public is provided ''' first_name = ['TestFirstName_300', 'TestFirstName_301'] last_name = ['TestLastName_300', 'TestLastName_301'] user_name = ['test_username_300', 'test_username_301'] email = ['*****@*****.**', '*****@*****.**'] public_key_value = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDLpbEIycnsX7/pm1cC3TonZLU/AIlFujPvPL+68d3VShw1QkBNBJgqIRo9wPqz6B31HzkBpwkmdFkZQqhWUbvbnllgEK8sIvZ4a9u2ZsRI5qvoc9qDTS/kpRLajivBGH5quNAFBE5LSmkV29/pOOzJTO4XLMp8xAfCwq8s4hNdbZWpmX9/1GrC9yUckmchpD2YKVDrVqneCH3PlbB2XLmE1UIP98ic/Y3FXAwX5bS/i+k27N8TWlPSWV4I9MZkN4sVAIt99yjxJZtimWBm0fYZAEfDS57G58fpPTamQV2RWq1iNl6X9DxufxRQqHVRlo9ixKp1TTfkvCvH//PSLi+r [email protected]' ret_values = self.server.register_user(first_name[0], last_name[0], user_name[0], email[0], public_key_value) if len(ret_values) == 2: member, key = ret_values[:2] else: member = None #Registration should succeed for unique public key self.assertIsNotNone(member) ret_values = None try: ret_values = self.server.register_user(first_name[1], last_name[1], user_name[1], email[1], public_key_value) except Exception: pass #Registration should fail for non-unique public key self.assertIsNone(ret_values) def test_register_with_first_and_last_name_combinations(self): """ User registration should be possible for any combination of First and Last names as long as user names and public keys are unique """ # define name combinations first_name = ['TestFirstName_A', 'TestFirstName_A', 'TestFirstName_B', 'TestFirstName_B'] last_name = ['TestLastName_A', 'TestLastName_B', 'TestLastName_A', 'TestLastName_B'] #define unique user names and email addresses user_name = ['test_username_A', 'test_username_B', 'test_username_C', 'test_username_D'] email = ['*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**'] #All registration attempts should succeed in the this loop because First and Last name combinations are unique for index in range(0, 4): public_key_value, private_key_value = get_ssh_keys(first_name[index], last_name[index]) ret_values = self.server.register_user(first_name[index], last_name[index], user_name[index], email[index], public_key_value) if len(ret_values) == 2: member, key = ret_values[:2] else: member = None #Registration should succeed for all combinations self.assertIsNotNone(member) #Redefine user names to make them unique user_name = ['test_username_E', 'test_username_F', 'test_username_G', 'test_username_H'] #All registration attempts should succeed in the this loop because user names are unique though First and Last name combinations are already registered for index in range(0, 4): public_key_value, private_key_value = get_ssh_keys(first_name[index], last_name[index]) ret_values = self.server.register_user(first_name[index], last_name[index], user_name[index], email[index], public_key_value) if len(ret_values) == 2: member, key = ret_values[:2] else: member = None #Registration should succeed for all combinations self.assertIsNotNone(member) def test_register_with_empty_argument(self): """ User registration should not be possible if any of the necessary arguments are missing, i.e., First and Last name, user name, email address. """ first_name = ['', 'TestFirstName_401', 'TestFirstName_402', 'TestFirstName_403'] last_name = ['TestLastName_400', '', 'TestLastName_402', 'TestLastName_403'] user_name = ['test_username_400', 'test_username_401', '', 'test_username_403'] email = ['*****@*****.**', '*****@*****.**', '*****@*****.**', ''] #All registration attempts should fail in the this loop because of missing details for index in range(0, 4): public_key_value, private_key_value = get_ssh_keys(first_name[index], last_name[index]) ret_values = self.server.register_user(first_name[index], last_name[index], user_name[index], email[index], public_key_value) if len(ret_values) == 2: member, key = ret_values[:2] else: member = None #Registration should fail for all combinations self.assertIsNone(member) def test_create_root_user(self): """ Creates a root user :return: """ privileges = ["GLOBAL_MEMBERS_VIEW", "GLOBAL_MEMBERS_WILDCARDS", "GLOBAL_PROJECTS_MONITOR", "GLOBAL_PROJECTS_VIEW", "GLOBAL_PROJECTS_WILDCARDS", "MEMBER_REGISTER"] public_key_value, private_key_value = get_ssh_keys("Expedient", "Expedient") ret_values = self.server.register_user("System", "expedient", "expedient", "*****@*****.**", public_key_value, privileges) if len(ret_values) == 2: member, key = ret_values[:2] credentials = member['MEMBER_CREDENTIALS'] certificate = member['MEMBER_CERTIFICATE'] private_key_cert = member['MEMBER_CERTIFICATE_KEY'] else: credentials = None self.assertIsNotNone(credentials) write_file("exp-cred.xml", credentials) write_file("exp-cert.pem", certificate) write_file("exp-key.pem", private_key_cert)
import jsonrpclib server = jsonrpclib.Server('http://localhost:5000/add') server.add(5, 6)
emulator_service_host = 'localhost' emulator_service_port = random.randint(20001, 59999) emulator_service_url = 'http://' + emulator_service_host + ':' + str( emulator_service_port) # # Check that we have the correct arguments # if len(sys.argv) != 2: usage() # Grab the URL to use [progname, rvi_url] = sys.argv # Setup an outbound JSON-RPC connection to the RVI Service Edge. rvi_server = jsonrpclib.Server(rvi_url) emulator_service = RVIJSONRPCServer(addr=((emulator_service_host, emulator_service_port)), logRequests=False) # # Regsiter callbacks for incoming JSON-RPC calls delivered to # the SOTA server from the vehicle RVI node's Service Edge. # emulator_service.register_function(report, "/logging/report") # Create a thread to handle incoming stuff so that we can do input # in order to get new values thr = threading.Thread(target=emulator_service.serve_forever) thr.start()
def get_client(ip, port): remote = jsonrpclib.Server('http://' + ip + ':' + str(port)) return remote
op = optparse.OptionParser(usage=usage) op.add_option('-n', '--host', dest='host', action='store', help='IP addresses of host to connect to', type='string') op.add_option('-i', '--ip', dest='address', action='store', help='IP addresses to set on Interface', type='string') op.add_option('-t', '--interface', dest='interface', action='store', help='interface to configure', type='string') opts, _ = op.parse_args() host = opts.host address = opts.address interface = opts.interface switch = jsonrpclib.Server('%s://%s:%s@%s/command-api' % (EAPI_METHOD, EAPI_USERNAME, EAPI_PASSWORD, host)) response = switch.runCmds( 1, ["enable", "configure", "interface " + interface, "ip address " + address])
import sys, getopt import json import pycurl import struct import cStringIO import pprint import jsonrpclib import subprocess import os from binascii import unhexlify, crc32 # Settings rpcserver = "http://*****:*****@localhost:8332" # Bitcoin RPC Client server = jsonrpclib.Server(rpcserver) def decode_transaction(transaction): "Decodes an individual transaction" try: rawTx = server.getrawtransaction(transaction) tx = server.decoderawtransaction(rawTx) data = b'' for txout in tx['vout']: if "OP_RETURN" in txout['scriptPubKey']['asm']: for op in txout['scriptPubKey']['asm'].split(' '): if not op.startswith('OP_'): print(transaction + ": contains OP_RETURN")
def xhr_controls(command): serversettings = server_settings() xbmc = jsonrpclib.Server(server_api_address()) return_response = 'failed' try: active_player = xbmc.Player.GetActivePlayers() if active_player[0]['type'] == 'video': playerid = 1 elif active_player[0]['type'] == 'audio': playerid = 0 except: active_player = None if command == 'play_pause': logger.log('CONTROLS :: Play/Pause', 'INFO') try: xbmc.Player.PlayPause(playerid=playerid) return_response = 'success' except: logger.log('CONTROLS :: %s' % xbmc_error, 'ERROR') return_response = 'failed' elif command == 'stop': logger.log('CONTROLS :: Stop', 'INFO') try: xbmc.Player.Stop(playerid=playerid) return_response = 'success' except: logger.log('CONTROLS :: %s' % xbmc_error, 'ERROR') return_response = 'failed' elif 'volume' in command: logger.log('CONTROLS :: Volume', 'INFO') try: volume = command.split('_') volume = int(volume[1]) xbmc.Application.SetVolume(volume=volume) return_response = 'success' except: logger.log('CONTROLS :: %s' % xbmc_error, 'ERROR') return_response = 'failed' elif command == 'next': logger.log('CONTROLS :: Next', 'INFO') try: version = xbmc.Application.GetProperties( properties=['version'])['version']['major'] if version < 12: xbmc.Player.GoNext(playerid=playerid) else: xbmc.Player.GoTo(playerid=playerid, to='next') return_response = 'success' except: logger.log('CONTROLS :: %s' % xbmc_error, 'ERROR') return_response = 'failed' elif command == 'previous': logger.log('CONTROLS :: Previous', 'INFO') try: version = xbmc.Application.GetProperties( properties=['version'])['version']['major'] if version < 12: xbmc.Player.GoPrevious(playerid=playerid) else: xbmc.Player.GoTo(playerid=playerid, to='previous') return_response = 'success' except: logger.log('CONTROLS :: %s' % xbmc_error, 'ERROR') return_response = 'failed' elif command == 'fast_forward': logger.log('CONTROLS :: Fast forward', 'INFO') try: xbmc.Player.SetSpeed(playerid=playerid, speed='increment') return_response = 'success' except: logger.log('CONTROLS :: %s' % xbmc_error, 'ERROR') return_response = 'failed' elif command == 'rewind': logger.log('CONTROLS :: Rewind', 'INFO') try: xbmc.Player.SetSpeed(playerid=playerid, speed='decrement') return_response = 'success' except: logger.log('CONTROLS :: %s' % xbmc_error, 'ERROR') return_response = 'failed' elif 'seek' in command: logger.log('CONTROLS :: Seek', 'INFO') try: percentage = command.split('_') percentage = int(percentage[1]) xbmc.Player.Seek(playerid=playerid, value=percentage) return_response = 'success' except: logger.log('CONTROLS :: %s' % xbmc_error, 'ERROR') return_response = 'failed' elif command == 'shuffle': logger.log('CONTROLS :: Shuffle', 'INFO') try: version = xbmc.Application.GetProperties( properties=['version'])['version']['major'] if version > 11: xbmc.Player.SetShuffle(playerid=playerid, shuffle='toggle') else: shuffled = xbmc.Player.GetProperties(playerid=playerid, properties=['shuffled' ])['shuffled'] if shuffled == True: xbmc.Player.UnShuffle(playerid=playerid) else: xbmc.Player.Shuffle(playerid=playerid) return_response = 'success' except: logger.log('CONTROLS :: %s' % xbmc_error, 'ERROR') return_response = 'failed' elif command == 'repeat': logger.log('CONTROLS :: Repeat', 'INFO') try: version = xbmc.Application.GetProperties( properties=['version'])['version']['major'] if version > 11: xbmc.Player.SetRepeat(playerid=playerid, repeat='cycle') else: states = ['off', 'one', 'all'] repeat = xbmc.Player.GetProperties(playerid=playerid, properties=['repeat' ])['repeat'] state = states.index(repeat) if state <= 1: state = state + 1 else: state = 0 state = states[state] xbmc.Player.Repeat(playerid=playerid, state=state) return_response = 'success' except: logger.log('CONTROLS :: %s' % xbmc_error, 'ERROR') return_response = 'failed' elif command == 'update_video': logger.log('CONTROLS :: Updating video library', 'INFO') try: xbmc.VideoLibrary.Scan() return_response = 'success' except: logger.log('CONTROLS :: %s' % xbmc_error, 'ERROR') return_response = 'failed' elif command == 'clean_video': logger.log('CONTROLS :: Cleaning video library', 'INFO') try: xbmc.VideoLibrary.Clean() return_response = 'success' except: logger.log('CONTROLS :: %s' % xbmc_error, 'ERROR') return_response = 'failed' elif command == 'update_audio': logger.log('CONTROLS :: Updating audio library', 'INFO') try: xbmc.AudioLibrary.Scan() return_response = 'success' except: logger.log('CONTROLS :: %s' % xbmc_error, 'ERROR') return_response = 'failed' elif command == 'clean_audio': logger.log('CONTROLS :: Cleaning audio library', 'INFO') try: xbmc.AudioLibrary.Clean() return_response = 'success' except: logger.log('CONTROLS :: %s' % xbmc_error, 'ERROR') return_response = 'failed' elif command == 'poweroff': logger.log('CONTROLS :: Shutting down XBMC machine', 'INFO') try: xbmc.System.Shutdown() return_response = 'success' except: logger.log('CONTROLS :: %s' % xbmc_error, 'ERROR') return_response = 'failed' elif command == 'suspend': logger.log('CONTROLS :: Suspending XBMC machine', 'INFO') try: xbmc.System.Suspend() return_response = 'success' except: logger.log('CONTROLS :: %s' % xbmc_error, 'ERROR') return_response = 'failed' elif command == 'reboot': logger.log('CONTROLS :: Rebooting XBMC machine', 'INFO') try: xbmc.System.Reboot() return_response = 'success' except: logger.log('CONTROLS :: %s' % xbmc_error, 'ERROR') return_response = 'failed' elif command == 'pvr-scan': logger.log('CONTROLS :: Scanning PVR EPG', 'INFO') try: xbmc.PVR.Scan() return_response = 'success' except: logger.log('CONTROLS :: %s' % xbmc_error, 'ERROR') return_response = 'failed' elif command == 'poweron': logger.log('CONTROLS :: Powering on XBMC machine', 'INFO') server_macaddress = serversettings['mac_address'] if not server_macaddress: logger.log('CONTROLS :: No XBMC machine MAC address defined', 'ERROR') return jsonify({'failed': True}) else: try: addr_byte = server_macaddress.split(':') hw_addr = struct.pack('BBBBBB', int(addr_byte[0], 16), int(addr_byte[1], 16), int(addr_byte[2], 16), int(addr_byte[3], 16), int(addr_byte[4], 16), int(addr_byte[5], 16)) msg = '\xff' * 6 + hw_addr * 16 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.sendto(msg, ("255.255.255.255", 9)) return_response = 'success' except: logger.log('CONTROLS :: Failed to send WOL packet', 'ERROR') return_response = 'failed' if return_response == 'success': return jsonify({'success': True}) else: return jsonify({'failed': True})
def xhr_play_media(file_type, media_type, media_id): logger.log('CONTROLS :: Playing %s' % media_type, 'INFO') xbmc = jsonrpclib.Server(server_api_address()) position = 0 if file_type == 'video': id = 1 else: id = 0 try: xhr_clear_playlist(id) except: logger.log('CONTROLS :: Failed to clear %s playlist' % file_type, 'DEBUG') return jsonify({'failed': True}) if file_type == 'video': if media_type == 'tvshow': try: tvshow_episodes = xbmc.VideoLibrary.GetEpisodes( tvshowid=media_id, sort={'method': 'episode'})['episodes'] for episode in tvshow_episodes: episodeid = episode['episodeid'] item = {'episodeid': episodeid} xbmc.Playlist.Add(playlistid=1, item=item) except: logger.log('CONTROLS :: Failed to retrieve episodes', 'DEBUG') return jsonify({'failed': True}) elif 'season' in media_type: media_type = media_type.split('_') season = int(media_type[1]) try: tvshow_episodes = xbmc.VideoLibrary.GetEpisodes( tvshowid=media_id, season=season, sort={'method': 'episode'})['episodes'] for episode in tvshow_episodes: episodeid = episode['episodeid'] item = {'episodeid': episodeid} xbmc.Playlist.Add(playlistid=1, item=item) except: logger.log('CONTROLS :: Failed to retrieve episodes', 'DEBUG') return jsonify({'failed': True}) else: try: item = {media_type + 'id': media_id} xbmc.Playlist.Add(playlistid=1, item=item) except: logger.log( 'CONTROLS :: Failed to add %s to playlist' % media_type, 'DEBUG') return jsonify({'failed': True}) else: try: if media_type == 'song' and get_setting_value( 'xbmc_songs_play_album') == '1': song = xbmc.AudioLibrary.GetSongDetails( songid=media_id, properties=['albumid', 'track'])['songdetails'] item = {'albumid': song['albumid']} position = song['track'] - 1 else: item = {media_type + 'id': media_id} xbmc.Playlist.Add(playlistid=0, item=item) except: logger.log('CONTROLS :: Failed to add %s to playlist' % media_type, 'DEBUG') return jsonify({'failed': True}) try: item = {'playlistid': id, 'position': position} xbmc.Player.Open(item) except: logger.log('CONTROLS :: Failed to open %s playlist' % file_type, 'DEBUG') return jsonify({'failed': True}) return jsonify({'success': True})
import jsonrpclib import ssl import pprint ssl._create_default_https_context = ssl._create_unverified_context ip = '172.31.33.249' port = '443' username = '******' password = '******' switch_url = 'https://{}:{}@{}:{}'.format(username, password, ip, port) switch_url = switch_url + '/command-api' print(switch_url) remote_connect = jsonrpclib.Server(switch_url) print(remote_connect) response = remote_connect.runCmds(1, ['show version']) response2 = remote_connect.runCmds(1, ['show arp', 'show ip route']) #pprint.pprint(response) #pprint.pprint(response2) ''' Response is a list with a single object. This object is a dictionary. We are pulling the dictionary out of the list ''' dictionary_repsonse = response[0] dictionary_repsonse2 = response2[0]