def connect(self, params={}):
        client_id = params.get("client_id")
        client_secret = params.get("client_secret").get("secretKey")
        enterprise_id = params.get("enterprise_id")
        jwt_key_id = params.get("jwt_key_id")
        password = params.get("rsa_password").get("secretKey").encode()
        private_key = params.get("private_key").get("secretKey")

        self.logger.info("Connect: Connecting..")

        # Fix escaping issues in private_key
        if "\\n" in private_key:
            private_key = private_key.replace("\\n", "\n", -1)

        # Try to connect with the legacy code
        try:

            # store private key
            parsed_private_key = urllib.parse.unquote_plus(private_key)
            f = tempfile.NamedTemporaryFile("w")
            f.write(parsed_private_key)
            f.seek(0)

            auth = JWTAuth(
                client_id=client_id,
                client_secret=client_secret,
                enterprise_id=enterprise_id,
                jwt_key_id=jwt_key_id,
                rsa_private_key_file_sys_path=f.name,
                store_tokens=self.store_tokens,
                rsa_private_key_passphrase=password,
            )
            self.box_connection = Client(auth)
            access_token = auth.authenticate_instance()

            self.logger.info("Connect: Connection successful")
            f.close()

        # if legacy connection fails try to connect with new code
        except ValueError:

            # store private key
            f = tempfile.NamedTemporaryFile("w")
            f.write(private_key)
            f.seek(0)

            auth = JWTAuth(
                client_id=client_id,
                client_secret=client_secret,
                enterprise_id=enterprise_id,
                jwt_key_id=jwt_key_id,
                rsa_private_key_file_sys_path=f.name,
                rsa_private_key_passphrase=password,
            )
            self.box_connection = Client(auth)
            access_token = auth.authenticate_instance()

            self.logger.info("Connect: Connection successful")
            f.close()
Example #2
0
    def get_conn(self):
        """
        Returns an authentication with app in box.
        """

        try:
            client = CerberusClient('https://prod.cerberus.nikecloud.com')
            sdk = JWTAuth(
                client_id=client.get_secrets_data(
                    "shared/ngap-box/client_id")["client_id"],
                client_secret=client.get_secrets_data(
                    "shared/ngap-box/client_secret")["client_secret"],
                enterprise_id=client.get_secrets_data(
                    "shared/ngap-box/enterprise_id")["enterprise_id"],
                jwt_key_id=client.get_secrets_data(
                    "shared/ngap-box/jwt_key_id")["jwt_key_id"],
                rsa_private_key_data=((client.get_secrets_data(
                    "shared/ngap-box/boxpemkey")["pemkey"]).replace(
                        '\\n', '\n')),
                rsa_private_key_passphrase=bytes(
                    (client.get_secrets_data(
                        "shared/ngap-box/rsa_private_key_passphrase")
                     ["rsa_private_key_passphrase"]).encode('utf-8')))
            client = Client(sdk)
            return client
        except TypeError as e:
            print(e)
def get_box_client():
    """BoxSDKの初期化
    """
    secret = get_secret()
    client_id = secret["boxAppSettings"]["clientID"]
    client_secret = secret["boxAppSettings"]["clientSecret"]
    jwt_key_id = secret["boxAppSettings"]["appAuth"]["publicKeyID"]
    rsa_private_key_data = secret["boxAppSettings"]["appAuth"]["privateKey"]
    rsa_private_key_passphrase = secret["boxAppSettings"]["appAuth"]["passphrase"]
    enterprise_id = secret["enterpriseID"]

    webhook_signature_key = secret["webhookPrimaryKey"]

    auth = JWTAuth(
        client_id=client_id,
        client_secret=client_secret,
        jwt_key_id=jwt_key_id,
        rsa_private_key_data=rsa_private_key_data,
        rsa_private_key_passphrase=rsa_private_key_passphrase,
        enterprise_id=enterprise_id
    )
    auth.authenticate_instance()

    client = Client(auth)
    return client, webhook_signature_key
def get_box_client():
    secret = _get_secret()

    client_id = secret["box_client_id"]
    client_secret = secret["box_client_secret"]
    enterprise_id = secret["box_enterprise_id"]
    jwt_key_id = secret["box_jwt_key_id"]
    rsa_private_key_data = secret["box_rsa_private_key_data"]
    rsa_private_key_passphrase = secret["box_rsa_private_key_passphrase"]
    webhook_signature_key = secret["box_webhook_signature_key"]

    auth = JWTAuth(
        client_id=client_id,
        client_secret=client_secret,
        enterprise_id=enterprise_id,
        jwt_key_id=jwt_key_id,
        rsa_private_key_data=rsa_private_key_data,
        rsa_private_key_passphrase=rsa_private_key_passphrase,
    )
    auth.authenticate_instance()

    client = Client(auth)

    users = client.users()
    try:
        app_user = users.next()
    except StopIteration:
        LOGGER.warning(
            "no app user exists, so the service account will be used as the box api client"
        )
        return client, webhook_key

    app_client = client.as_user(app_user)

    return app_client, webhook_signature_key
Example #5
0
def upload():
    auth = JWTAuth(client_id='t7o9oknjyfmavpz2vq8qyeh2tq3bgwkc',
                   client_secret='tYjGJzz1iMiPA2JBW6csMyAFEXPrUj2c',
                   enterprise_id='511092066',
                   jwt_key_id='u4zebqgi',
                   rsa_private_key_file_sys_path='private.pem')

    access_token = auth.authenticate_instance()

    client = Client(auth)

    user_to_impersonate = client.user(user_id='13315944066')
    client = client.as_user(user_to_impersonate)

    user = client.user().get()
    print('The current user ID is {0}'.format(user.id))

    subfolder = client.folder('0').create_subfolder(str(Supportid))
    print('Created subfolder with ID {0}'.format(subfolder.id))

    cmdfile = client.folder(subfolder.id).upload('specs-cmd.txt')
    print(
        'File "{0}" uploaded to Circuit Technical Spec Storage with file ID {1}'
        .format(cmdfile.name, cmdfile.id))

    psfile = client.folder(subfolder.id).upload('specs-ps.txt')
    print(
        'File "{0}" uploaded to Circuit Technical Spec Storage with file ID {1}'
        .format(psfile.name, psfile.id))
    pass
Example #6
0
def create_service_auth():
    service_account_auth = JWTAuth(
        client_id=settings.box_client_id,
        client_secret=settings.box_secret,
        enterprise_id=settings.box_enterprise_id,
        jwt_key_id=settings.box_jwt_key_id,
        rsa_private_key_file_sys_path=settings.rsa_private_key_file_sys_path,
        rsa_private_key_passphrase=settings.rsa_private_key_passphras)

    print(f"service account - {service_account_auth}")
    return service_account_auth
Example #7
0
def create_user_auth(app_user):
    app_user_auth = JWTAuth(
        client_id=settings.box_client_id,
        client_secret=settings.box_secret,
        user=app_user,
        enterprise_id=settings.box_enterprise_id,
        jwt_key_id=settings.box_jwt_key_id,
        rsa_private_key_file_sys_path=settings.rsa_private_key_file_sys_path,
        rsa_private_key_passphrase=settings.rsa_private_key_passphras)
    print(f"user account - {app_user_auth}")
    return app_user_auth
Example #8
0
    def authenticate_box_client(self):
        self.auth = JWTAuth(
            client_id=self.client_id,
            client_secret=self.client_secret,
            enterprise_id=self.enterprise_id,
            jwt_key_id=self.jwt_key_id,
            rsa_private_key_passphrase=self.rsa_private_key_pass,
            rsa_private_key_file_sys_path=self.rsa_private_key_path,
            store_tokens=self.store_tokens)

        self.auth.authenticate_instance()
        return Client(self.auth)
Example #9
0
def box_auth(user_id):
    auth = JWTAuth(client_id='YOUR_CLIENT_ID',
                   client_secret='YOUR_CLIENT_SECRET',
                   enterprise_id='YOUR_ENTERPRISE_ID',
                   jwt_key_id='YOUR_JWT_KEY_ID',
                   rsa_private_key_passphrase='RSA_PRIVATE_KEY_PASSPHRASE',
                   rsa_private_key_file_sys_path='PATH_TO_KEY_FILE')

    access_token = auth.authenticate_instance()

    client = Client(auth)
    user = client.user(user_id)

    return (client, user)
Example #10
0
def check_box_auth(secret):
    try:
        JWTAuth(
            client_id=secret["box_client_id"],
            client_secret=secret["box_client_secret"],
            enterprise_id=secret["box_enterprise_id"],
            jwt_key_id=secret["box_jwt_key_id"],
            rsa_private_key_data=secret["box_rsa_private_key_data"],
            rsa_private_key_passphrase=secret[
                "box_rsa_private_key_passphrase"],
        ).authenticate_instance()
    except Exception as e:
        raise RuntimeError(
            "Box failed to authenticate, check credentials and try again"
        ) from e
Example #11
0
def get_auth():

    auth = JWTAuth(
        client_id='37vdfnknzax5htrkiler5xkphbxs6f4s',
        client_secret='pMUwYf2g1iAsvFDnCA08ASa1oHwYj3Ut',
        enterprise_id="849101",
        jwt_key_id='h4qpyf9b',
        rsa_private_key_file_sys_path='private_key.pem',
        rsa_private_key_passphrase=b'datos1234',
    )

    access_token = auth.authenticate_instance()
    client = Client(auth)

    print("Upload authenticated successfully")

    return client
Example #12
0
def box_auth():

    path_name = key_path()

    auth = JWTAuth(
        client_id=config('CLIENT_ID'),
        client_secret=config('CLIENT_SECRET'),
        enterprise_id=config('ENTERPRISE_ID'),
        jwt_key_id=config('JWT_KEY_ID'),
        rsa_private_key_file_sys_path=path_name,
        rsa_private_key_passphrase=config('RSA_PRIVATE').encode('utf-8'),
    )
    client = Client(auth)
    user = client.user(user_id=config('BOX_USER_ID'))

    delete_temp_key()

    return client, user
Example #13
0
 def connect_box(self):
     auth = JWTAuth(
         client_id='fj5klf35gaydgnx2hewpfdg4uqz85ri7',
         client_secret='mM2d0ZScYgg6dE22jShBgK6y5xL6xFID',
         enterprise_id='635964596',
         jwt_key_id='061jkz4x',
         rsa_private_key_file_sys_path=None,
         rsa_private_key_data=
         '-----BEGIN ENCRYPTED PRIVATE KEY-----\nMIIFDjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQICUFlpOqJ2DkCAggA\nMBQGCCqGSIb3DQMHBAhk2ZclZTqcNASCBMhSLnADIn+MhR1PtS0YWLej0bUrIxjE\n7uzrtYwXN9b8G7Y7PUhroEetlRIS5Uf4qEDsYFJeZwlW/wd9Xzzjdhg+bUMmVLC5\n57tcPnS9Sv0Q3gDcGiJrhjm9k7u17/GgHhCOeUeakZX8U/RJfasijw5X8ue8+esY\ng+99BB83H+9anSjTYqic2dU7PtwDdx9AYeru6g1psBjZurzT0eE1SWdTOw5QGhG4\n78+gBsuzuU4D2SefS1wMFiuY45JvxUq6+zAGtzRi8MYXYruRsi3vQRkctTqcJZil\n6g7yxs/oY0xaSNocMY7y8kuHVirdYzj3KZX/+p8EvVB+1pzVJ50dFtJntzdpcu03\nfCfLYz2Vod6TXnGs2Dr6Zzq9NSb5otumvn6FrD5QeAoVKkEcakPbGOLACBKCJe7B\nfoDB2FJXC2LqZwDsf0X7kLcJh7xaf6l2HOOp73wsZUfpifGmmswmL3dfEbZ3uLeR\nIBIdSlNyWuwrOuNc+5fl0V1zBdys3RGo4pavwq7QDFVSg3FgwtAqfOFICUlO48EL\nuF9Z3xp8pz+rlfYiF4iMpbIqt1/OD6GOFH2PiVIUaf4xB7Arbbbv93JKnTzwj8j1\nbKowjITWVc4RmPI0XbCVvukAYm4hY1ohlTaFVs5+3Dg6BQTqEtkfxknCphtPUoGD\nKV+c0YxI4jz9bYLPAWsMvwlvfYg10kUleyzKZAGt+NvBeplbi73Je7as1ZcvNcJX\nJ1jBLatH24RB7XU0N2r0KjIKMaE7pMDghTjtoJ1DczIi2t+J5dymwqAyoba0FktF\nA+T/AsAfjs95ashgekL0g0odKeCQL6YOnb41AKFZ9m6aOOONF0q8S4oLKYdqoL5U\nWq/2DnMyiKNH7eZfbAKMAJzYDjjkVKXj2MBDg/tF4ibwoVoa6jJZT6eKi82moCr5\n3LPQpJsIlfQ5nZg6faito35KlKEUCLQkSPP9p+sAZ3qyqirvkzps1c2FRyuUnVWH\nCMPUKGHcOhdq/2ziSLS8a1X95PxpWHCOS4BRnHEiGX0m2WleqkiQsJRnXrAw8Ft8\neu6knlL1o51EE4EaQeipfHaBxRDhdLMxEJGmj4mOTOP9Q8It9Sk4FNu8Sf3bXV85\nBpK30tBHFgSo04DQdxFrcHykEuFR0CjEf26us6Thp8YkAov/ogQb6EdjaYUQpm2P\nGdWxle14L/QAhkzXGA3cVng5bbeqU3gdagCe+UN1gCWGXer6OFmA3jjy5jZCrlDM\nd1O2HonoFdlh0V+RhJtvJWi2P/KcIOu/LroBnR0wcOles/TqnSHZ3LvPp2f+SfP+\nL2KL+jgZR24vofh+owEELYSD2luoi1H7X79cCWP6qxfYBj7jKzUBUkVjKOZ5QwIo\nlpCspT9mHzDB+K83p9nwwrnYy+J55InT0tiLtWvpN3og6kPy+vdX9SN1rp0VImxO\n6n1pfzYwfbhGLgc953/avlU9vSSHjAA9wFsONB344H+QMT1pgMh6D4O42XfZzriY\ne/rgz/EH7v39RQL4Y4VJbmdv9WW3NqBfLGwGgVuGFhh0wSc3ct/PYImeiijYviiD\nOvzIFZexsc5jgms0qr7Iby2fqYAwWYhxGN/uqpfDq0p9TYti7XUNHsDa0jAQrEb/\no1A=\n-----END ENCRYPTED PRIVATE KEY-----\n',
         rsa_private_key_passphrase='b8560c4b0187d6d5a068a637cfd034a9')
     try:
         return Client(auth)
     except BoxAPIException as error:
         error_obj = {
             "isSuccess": False,
             "message": str(error),
             "traceback": traceback.format_exc()
         }
         return json.dumps(error_obj)
Example #14
0
def main(json_file):
    '''
    Authorize the application and print the user name and email
    '''
    settings = read_settings(json_file)
    auth = JWTAuth(
        client_id=settings['boxAppSettings']['clientID'],
        client_secret=settings['boxAppSettings']['clientSecret'],
        enterprise_id=settings['enterpriseID'],
        jwt_key_id=settings['boxAppSettings']['appAuth']['publicKeyID'],
        rsa_private_key_data=settings['boxAppSettings']['appAuth']
        ['privateKey'],
        rsa_private_key_passphrase=settings['boxAppSettings']['appAuth']
        ['passphrase'],
        store_tokens=store_token,
        access_token=get_token(os.path.join(SETTINGS_PATH, TOKEN_FILE)))
    client = Client(auth)
    current_user = client.user(user_id='me').get()
    print('Successfully authenticated user: {} with email: {}'.format(
        current_user.name, current_user.login))
Example #15
0
def get_box_user(
    clientid,
    token,
    enterpriseid,
    publickeyid,
    passphrase,
    privatekey,
):
    auth = JWTAuth(
        client_id=clientid,
        client_secret=token,
        enterprise_id=enterpriseid,
        jwt_key_id=publickeyid,
        rsa_private_key_passphrase=passphrase.encode(),
        rsa_private_key_data=privatekey,
    )
    try:
        client = Client(auth)
        return client.user().get().name
    except Exception:
        return None
Example #16
0
def get_client():
    '''
    Returns the client object for running Box commands
    '''
    try:
        auth = JWTAuth(
            client_id = box_config.CLIENT_ID,
            client_secret = box_config.CLIENT_SECRET,
            enterprise_id = box_config.ENTERPRISE_ID,
            jwt_key_id = box_config.JWT_KEY_ID,
            rsa_private_key_file_sys_path = box_config.CERT,
            rsa_private_key_passphrase = box_config.PASSPHRASE
        )
        client= Client(auth)
        #should only be one porter user. only app user in my account
        porter_user = client.users()[0]
        porter_client = client.as_user(porter_user)
    except Exception as e:
        log.info('FAILURE: get_client ')
        log.info(e)
    else:
        log.info('SUCCESS: get_client ')
        return porter_client
Example #17
0
def run():
    boxClientId = ""
    boxClientSecret = ""
    boxEnterpriseId = ""
    boxJwtKeyId = ""
    boxPrivateKeyPath = os.getcwd() + "/" + "CERT.PEM"
    boxPrivateKeyPassphrase = b""

    auth = JWTAuth(client_id=boxClientId,
                   client_secret=boxClientSecret,
                   enterprise_id=boxEnterpriseId,
                   jwt_key_id=boxJwtKeyId,
                   rsa_private_key_file_sys_path=boxPrivateKeyPath,
                   rsa_private_key_passphrase=boxPrivateKeyPassphrase)

    access_token = auth.authenticate_instance()
    print(access_token)

    client = Client(auth)
    shared_link_url = "https://uc.box.com/v/estests-videos"
    local_path = "/Users/tylerestes/BoxSync/Media/TEST"

    download_files(client, shared_link_url, local_path)
Example #18
0
def authorize_jwt_client_json(config, private_key_file):
    """
    Function to obtain an authorised Box API Client using JWT
    """
    if os.path.exists(config):
        with open(config, 'r') as json_file:
            config = json.load(json_file)
    else:
        raise IOError('Config file not found')

    jwt_auth = JWTAuth(
        client_id=config['boxAppSettings']['clientID'],
        client_secret=config['boxAppSettings']['clientSecret'],
        enterprise_id=config['enterpriseID'],
        jwt_key_id=config['boxAppSettings']['appAuth']['publicKeyID'],
        access_token=None,
        rsa_private_key_file_sys_path=private_key_file,
        rsa_private_key_passphrase=str(
            config['boxAppSettings']['appAuth']['passphrase']).encode('utf_8'),
        store_tokens=lambda acc, _: store_token(acc, _))

    jwt_auth.authenticate_instance()

    return Client(jwt_auth)
config_file = open(config, "r")

resultString = config_file.read().replace('\n', '')
result = json.loads(resultString, strict=False)

app_auth = result['boxAppSettings']['appAuth']

box_settings = result['boxAppSettings']

print("\n\n\n" + json.dumps(result) + "\n\n\n")

sdk = JWTAuth(
    client_id = box_settings['clientID'],
    client_secret = box_settings['clientSecret'],
    enterprise_id = result['enterpriseID'],
	jwt_key_id = app_auth['publicKeyID'],
    rsa_private_key_data = app_auth['privateKey'],
    rsa_private_key_passphrase = app_auth['passphrase']
)

client = Client(sdk)

print("Client: " + str(client) + "\n")

current_user = client.user().get()


print ("Current user: "******"\n")

##############################################################
##############################################################
Example #20
0
# -*- coding: utf-8 -*-

from boxsdk import JWTAuth, Client
import os

auth = JWTAuth(
    client_id=os.environ["clientID"],
    client_secret=os.environ["clientSecret"],
    enterprise_id=os.environ["enterpriseID"],
    jwt_key_id=os.environ["publickeyID"],
    rsa_private_key_data=os.environ['privateKey'],
    rsa_private_key_passphrase='047dac7e6cd83f6b2a858014b50feb40'.encode(),
)

access_token = auth.authenticate_instance()
print(access_token)
"""
# 認証
auth = JWTAuth(
        client_id=os.environ["clientID"],
        client_secret=os.environ["clientSecret"],
        enterprise_id=os.environ["enterpriseID"],
        jwt_key_id="nno2ipwo",
        )
client = Client(auth)
user = client.user().get()
print('The current user ID is {0}'.format(user.id))

 
# ユーザ権限移譲
user_to_impersonate = client.user(user_id = "3056900391")
Example #21
0
oauth2 = OAuth2(jsonCred['boxAppSettings']['clientID'],
                jsonCred['boxAppSettings']['clientSecret'],
                access_token=strAccessToken)
#
#
#client = Client(oauth2)#, LoggingNetwork())
#
#
#print(client.folder('0').get())

auth = JWTAuth(
    client_id=jsonCred['boxAppSettings']['clientID'],
    client_secret=jsonCred['boxAppSettings']['clientSecret'],
    enterprise_id=jsonCred['enterpriseID'],
    jwt_key_id=jsonCred['boxAppSettings']['appAuth']['publicKeyID'],
    rsa_private_key_file_sys_path=jsonCred['boxAppSettings']['appAuth']
    ['privateKey'],
    rsa_private_key_passphrase=jsonCred['boxAppSettings']['appAuth']
    ['passphrase'],
    store_tokens=store_tokens,
)

# Configure JWT auth object
#sdk = JWTAuth(jsonCred)

#client = Client(sdk)

#userid="*********"
#user=client.user(user_id = userid)

#%%
Example #22
0
from boxsdk import JWTAuth

import json

with open('/home/josh/keys/box/58354353_r2sa3in3_config.json') as f:
    data = json.load(f)

auth = JWTAuth(
    client_id=data['boxAppSettings']['clientID'],
    client_secret=data['boxAppSettings']['clientSecret'],
    enterprise_id=data.get('enterpriseID', None),
    jwt_key_id=data['boxAppSettings']['appAuth'].get('publicKeyID', None),
    #rsa_private_key_data=str(data['boxAppSettings']['appAuth'].get('privateKey', None)),
    rsa_private_key_passphrase=str(data['boxAppSettings']['appAuth'].get(
        'passphrase', None)),
    rsa_private_key_file_sys_path='/home/josh/keys/box/private.pem',
)

#JWTAuth.from_settings_dictionary(data)
#auth = JWTAuth(data)

access_token = auth.authenticate_instance()

from boxsdk import Client

client = Client(auth)

#file = client.file(file_id=297752586807).get()
#print('user_login: '******'name'])

user = client.user(user_id=3718623393)
Example #23
0
client_id = ""
client_secret = ""
enterprise_id = ""
jwt_key_id = ""
rsakey_filename = ""
rsakey_passphrase = None

logger = LoggingNetwork()

start_time = time.time()

auth = JWTAuth(
    client_id=client_id,
    client_secret=client_secret,
    enterprise_id=enterprise_id,
    jwt_key_id=jwt_key_id,
    rsa_private_key_file_sys_path=rsakey_filename,
    rsa_private_key_passphrase=rsakey_passphrase,
    network_layer=logger,
)
print "App Admin Token: " + str(auth.access_token)
client = Client(auth)

print '-' * 80
me = client.user(user_id='me').get()
print 'Logged in as: '
print 'NAME: ' + me['name']
print 'EMAIL: ' + me['login']
print 'ID: ' + me.id
role = me.get(fields=['role']).role
print "User's Role is " + role
Example #24
0
from boxsdk import JWTAuth
from boxsdk import Client
import paramiko
import time

# Configure JWT auth object
sdk = JWTAuth(
    client_id="pi4s33hjb67dp1fiqeb8redy5j7ovosu",
    client_secret="GKtOuTOMuQCHY2SH0bx0sDs6l7VGC47u",
    enterprise_id="62450315",
    jwt_key_id="0jntyc9m",
    rsa_private_key_file_sys_path="C:\\cygwin64\\home\\Victor\\private.json",
    rsa_private_key_passphrase='password'.encode())
client = Client(sdk)

#file_path = 'C:\\Users\\Victor\\Documents\\transition.txt'
#file_name = 'transition.txt'
#folder_id = '0'

#box_file = client.folder(folder_id).upload(file_path, file_name)

#box_file = client.folder(folder_id).upload(file_path)

#box_file = client.folder('0').upload('C:\\Users\\Victor\\Documents\\language.txt')


def runner(ip, u_name, p_word, komand):
    ssh = paramiko.SSHClient()
    #print("hi")
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip, port=22, username=u_name, password=p_word, timeout=10)
Example #25
0
def get_box_client(plaintext: str) -> BoxClient:
    auth_args = json_config_to_jwtauth(plaintext)
    auth = JWTAuth(**auth_args)
    access_token = auth.authenticate_instance()
    return BoxClient(auth)
Example #26
0
from boxsdk import JWTAuth
from boxsdk import Client

auth = JWTAuth(
    client_id='2xld7m3w2j9hvjy60aq951lc68u2ocfv',
    client_secret='gFZg7dhe4Rr2eSIW1D7aZJs6WjXSGI2J',
    enterprise_id='15270599',
    jwt_key_id='qtm1mgfu',
    rsa_private_key_file_sys_path='loans/private_key.pem',
    rsa_private_key_passphrase='nb062795',
)

access_token = auth.authenticate_instance()

client = Client(auth)

ned_stark_user = client.create_user('Ned Stark')
Example #27
0
from boxsdk import JWTAuth
from boxsdk import Client
import netmiko
from netmiko import ConnectHandler
import datetime

import threading
from threading import Thread

# Configure JWT auth object
sdk = JWTAuth(client_id="Qn6p8cio5i1nr93kzlyac70aj6xjprbw",
              client_secret="TMrbjJLq8Ek3kht8hGH9FAgZbOJkKaJl",
              enterprise_id="62977688",
              jwt_key_id="qun049ut",
              rsa_private_key_file_sys_path=
              "C:\\cygwin64\\home\\User-12\\private_Jing.json",
              rsa_private_key_passphrase='#####Round'.encode())
client = Client(sdk)


def runner(ipp, u_name, p_word, s_word):
    ssh_connection = ConnectHandler(
        device_type='checkpoint_gaia',
        ip=ipp,
        username=u_name,
        password=p_word,
        #secret=s_word
    )
    result = ssh_connection.find_prompt() + "\n"
    result += ssh_connection.send_command('clish -c "show configuration"',
                                          delay_factor=4)
Example #28
0
from boxsdk import Client
from boxsdk import JWTAuth
from flask import Flask, render_template
import config

# Configure JWT auth and fetch access token
auth = JWTAuth(client_id=config.client_id,
               client_secret=config.client_secret,
               enterprise_id=config.enterprise_id,
               jwt_key_id=config.jwt_key_id,
               rsa_private_key_file_sys_path=config.private_key_path,
               rsa_private_key_passphrase=config.private_key_passphrase)

# Obtain client auth
access_token = auth.authenticate_instance()
client = Client(auth)

# Render HTML using Flask
app = Flask(__name__)


@app.route('/')
def hello():
    html = render_template('template.html', fid=config.fid, at=access_token)
    return html


if __name__ == '__main__':
    app.run()
Example #29
0
from django.template import loader
from django.core.files.storage import FileSystemStorage
from django.conf import settings
from django.views.decorators.csrf import ensure_csrf_cookie
from django.contrib.auth import authenticate, login
from boxsdk import JWTAuth
from boxsdk import Client
from StringIO import StringIO
from boxsdk.object.collaboration import CollaborationRole
from boxsdk.exception import BoxAPIException
import os

auth = JWTAuth(
    client_id='00000000',
    client_secret='00000000',
    enterprise_id='00000000',
    jwt_key_id='00000000',
    rsa_private_key_file_sys_path='loans/private_key.pem',
    rsa_private_key_passphrase='00000000',
)

access_token = auth.authenticate_instance()
client = Client(auth)

ned_stark_user = client.create_user('Phillip Fry')

ned_auth = JWTAuth(
    client_id='00000000',
    client_secret='00000000',
    enterprise_id='00000000',
    jwt_key_id='00000000',
    rsa_private_key_file_sys_path='loans/private_key.pem',
Example #30
0
def pull():
    # initialize paths for config file
    private_path = Path(__file__).resolve().parent
    config_path = private_path / "config.json"
    key_path = private_path / "private.pem"
    print('keypath = ' + str(key_path))
    print('config = ' + str(config_path))
    print('private = ' + str(private_path))

    with config_path.open() as f:
        config = json.load(f)

    # initialize client variables from config tokens
    client_id = config["clientID"]
    client_secret = config["clientSecret"]
    enterprise_id = config["enterpriseID"]

    # initialize a new client
    auth = JWTAuth(client_id=client_id,
                   client_secret=client_secret,
                   enterprise_id=enterprise_id,
                   jwt_key_id='0l74oi4p',
                   rsa_private_key_file_sys_path="private.pem")

    access_token = auth.authenticate_instance()
    client = Client(auth)

    me = client.user(user_id='me').get()

    folderId = config["folderId"]  # id of box folder to sync with

    # returns a list of all items inside box folder
    itemsToSync = client.folder(folder_id=folderId).get_items(limit=100,
                                                              offset=0)

    # create a list of file names to parse and id number to identify and pull data
    nameList = []
    idList = []

    # counter variables
    i = 0
    while i < len(itemsToSync):
        s = str(itemsToSync[i])
        name = str(re.search('\(([^)]+)', s).group(1))
        idNum = re.findall(r'\d{12}',
                           s)  # finds string of 12 digits as file id number

        # only searches for .png types
        # saves name and id number to separate lists
        if name.endswith('.png') or name.endswith('.jpg') or name.endswith(
                '.jpeg'):
            idList.append(idNum)
            nameList.append(name)
        else:
            pass
        i += 1

    j = 0
    destinationPath = config["destinationPath"]  # path files will be saved to
    timelogPath = config["timelogPath"]
    now = datetime.datetime.now()  # get current timestamp
    strNow = now.strftime("%Y-%m-%d %H:%M:%S")
    while j < len(nameList):
        print nameList[j]
        print idList[j]
        completeName = os.path.join(
            destinationPath,
            nameList[j])  # concatenates destination with name of file
        idNum = ''.join(
            idList[j])  # parses id number to be pulled from box folder
        filecontent = client.file(
            file_id=idNum).content()  # saves file content as variable
        newfile = open(completeName, 'w')
        newfile.write(filecontent)
        newfile.close()
        j += 1
    with open(timelogPath, "a") as f:  # logs sync date and time in timelog.txt
        f.write("Last box sync at " + strNow + "\n")