Why doesn't pyngrok detect my config file? - python

I am trying to use my own configuration file with pyngrok but I don't understand why it does not detect it, my project needs to be run forcefully with sudo, therefore ngrok does not detect the configuration file in the root home directory for some users, it is that's why I want to mount my own configuration file in my project directory, here is my code:
from pyngrok import ngrok, conf
import os
from pathlib import Path
import re
def ngrok_start ():
file = Path (".config/ngrok.yml")
if file.exists():
os.system("kill -9 $(pgrep ngrok)")
ngrok.DEFAULT_CONFIG_PATH = ".config/ngrok.yml"
ngrok.connect(443, "tcp")
while True:
ngrok_tunnels = ngrok.get_tunnels()
url = ngrok_tunnels[0].public_url
if re.match ("tcp://[0-9]*.tcp.ngrok.io:[0-9]*", url) is not None:
print ("Ngrok TCP:" + url)
break
With my code I get the following error:
Traceback (most recent call last):
File "ngrok.py", line 27, in <module>
ngrok_start ()
File "ngrok.py", line 20, in ngrok_start
ngrok.connect (443, "tcp")
File "/usr/local/lib/python2.7/dist-packages/pyngrok/ngrok.py", line 181, in connect
timeout = pyngrok_config.request_timeout))
File "/usr/local/lib/python2.7/dist-packages/pyngrok/ngrok.py", line 321, in api_request
status_code, e.msg, e.hdrs, response_data)
pyngrok.exception.PyngrokNgrokHTTPError: ngrok client exception, API returned 502: {"error_code": 103, "status_code": 502, "msg": "failed to start tunnel", "details": {"err": "TCP tunnels are only available after you sign up. \ nSign up at: https://ngrok.com/signup\n\nIf you have already signed up, make sure your authtoken is installed. \ nYour authtoken is available on your dashboard: https: //dashboard.ngrok.com/auth/your-authtoken\r\n\r\nERR_NGROK_302\r\n "}}
No handlers could be found for logger "pyngrok.process"
My script is in the lib folder and my configuration file in .config/ngrok.yml, in which I have my token but I can't detect it, I hope you can support me, thanks.
imagen

Per the docs, the DEFAULT_CONFIG_PATH variable is in the conf module, not the ngrok module. So change ngrok.DEFAULT_CONFIG_PATH = to conf.get_default().config_path = .

Related

Error while fetching GCP monitoring via GCP Python API

I'm trying to fetch last 5 mins CPU utilization of a GCP SQL instance but getting following error. Please help me resolve it. The service account I'm using has full read permission over monitoring.
My script:
from google.cloud import monitoring_v3
from google.cloud.monitoring_v3 import query
credential_file = "/home/user/my-first-project.json"
GCP_SCOPES = [
'https://www.googleapis.com/auth/sqlservice.admin',
"https://www.googleapis.com/auth/logging.read",
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/monitoring",
"https://www.googleapis.com/auth/monitoring.read"
]
gcp_credential = service_account.Credentials.from_service_account_file(credential_file,scopes=GCP_SCOPES)
client = monitoring_v3.MetricServiceClient(credentials=gcp_credential)
project_name = f"projects/my-first-project"
cpu_query = query.Query(client,
project=project_name,
metric_type='cloudsql.googleapis.com/database/cpu/utilization',
minutes=5)
next(cpu_query.iter())
Error:
File "$PATH\grpc_helpers.py", line 75, in error_remapped_callable
six.raise_from(exceptions.from_grpc_error(exc), exc)
File "<string>", line 3, in raise_from
google.api_core.exceptions.PermissionDenied: 403 Permission monitoring.timeSeries.list denied (or the resource may not exist).
Removing the prefix "projects/" worked. So basically using project id instead of project_name worked.
cpu_query = query.Query(
client,
project="my-first-project",
metric_type='cloudsql.googleapis.com/database/cpu/utilization',
minutes=5
)

Receiving the error Code: SubscriptionNotFound Message: The subscription not found when trying to get data about Azure Virtual Machine?

I am working on a script that accesses details about an Azure Virtual Machine currently. This is the code that I have so far:
"""
Instantiate the ComputeManagementClient with the appropriate credentials.
#return ComputeManagementClient object
"""
def get_access_to_virtual_machine():
subscription_id = key.SUBSCRIPTION_ID
credentials = DefaultAzureCredential(authority = AzureAuthorityHosts.AZURE_GOVERNMENT,
exclude_environment_credential = True,
exclude_managed_identity_credential = True,
exclude_shared_token_cache_credential = True)
client = KeyClient(vault_url = key.VAULT_URL, credential = credentials)
compute_client = ComputeManagementClient(credentials, subscription_id)
return compute_client
"""
Check to see if Azure Virtual Machine exists and the state of the virtual machine.
"""
def get_azure_vm(resource_group_name, virtual_machine_name):
compute_client = get_access_to_virtual_machine()
vm_data = compute_client.virtual_machines.get(resource_group_name,
virtual_machine_name,
expand = 'instanceView')
return vm_data
When trying to run get_azure_vm(key.RESOURCE_GROUP, key.VIRTUAL_MACHINE_NAME) which I am certain does have the correct credentials, I get the following error output (note that I replaced the actual subscription ID with 'xxxx' for now):
Traceback (most recent call last):
File "/Users/shilpakancharla/Documents/function_app/WeedsMediaUploadTrigger/event_process.py", line 62, in <module>
vm_data = get_azure_vm(key.RESOURCE_GROUP, key.VIRTUAL_MACHINE_NAME)
File "<decorator-gen-2>", line 2, in get_azure_vm
File "/usr/local/lib/python3.9/site-packages/retry/api.py", line 73, in retry_decorator
return __retry_internal(partial(f, *args, **kwargs), exceptions, tries, delay, max_delay, backoff, jitter,
File "/usr/local/lib/python3.9/site-packages/retry/api.py", line 33, in __retry_internal
return f()
File "/Users/shilpakancharla/Documents/function_app/WeedsMediaUploadTrigger/event_process.py", line 55, in get_azure_vm
vm_data = compute_client.virtual_machines.get(resource_group_name,
File "/usr/local/lib/python3.9/site-packages/azure/mgmt/compute/v2019_12_01/operations/_virtual_machines_operations.py", line 641, in get
map_error(status_code=response.status_code, response=response, error_map=error_map)
File "/usr/local/lib/python3.9/site-packages/azure/core/exceptions.py", line 102, in map_error
raise error
azure.core.exceptions.ResourceNotFoundError: (SubscriptionNotFound) The subscription 'xxxx' could not be found.
Code: SubscriptionNotFound
Message: The subscription 'xxxx' could not be found.
I am using the beta preview version of azure.mgmt.compute which was installed with pip install azure-mgmt-compute=17.0.0b1. Note that I am also using an Azure Government account. Is there a way to solve this error? I have also tried using ServicePrincipalCredentials and get_azure_credentials() but ran into different errors - I was recommended to use DefaultAzureCredentials and the key vault by a coworker.
There is no problem with the code and it works fine on my side. And the error message shows the reason:
azure.core.exceptions.ResourceNotFoundError: (SubscriptionNotFound)
The subscription 'xxxx' could not be found. Code: SubscriptionNotFound
Message: The subscription 'xxxx' could not be found.
It seems you run the python code in your local machine. I recommend you log in with the Azure CLI first and then check if the subscription id that you used in your python code is right.

Pythonanywhere: Twitter API authenticates from bash, but fails on scheduled task

I'm using the python-twitter (not tweepy) module in my application.
I have a script set up (maketweet.py) that, when I run it from bash / console, works successfully (i.e. it makes a tweet).
The problem I'm having is that when I run the same script as a scheduled task, I get an error:
Traceback (most recent call last):
File "/home/dir1/dir2/proj/maketweet.py", line 21, in <module>
api = create_api()
File "/home/dir1/dir2/proj/config.py", line 31, in create_api
if api.VerifyCredentials():
File "/home/dir1/.local/lib/python3.8/site-packages/twitter/api.py", line 4699, in VerifyCredentials
resp = self._RequestUrl(url, 'GET', data)
File "/home/dir1/.local/lib/python3.8/site-packages/twitter/api.py", line 4959, in _RequestUrl
raise TwitterError("The twitter.Api instance must be authenticated.")
twitter.error.TwitterError: The twitter.Api instance must be authenticated.
The other problem I'm having is that I can't conceive why it would make a difference that I'm using a scheduled task, rather than running the file directly from bash. Here are the contents of config.py:
#!/usr/bin/python3.8
import twitter
import os
import logging
from dotenv import load_dotenv
logger = logging.getLogger()
# project folder is one level up from file location
project_folder = pathlib.Path(__file__).parent.absolute()
load_dotenv(os.path.join(project_folder, '.env'))
# Authenticate to Twitter and create API object
TWITTER_CONSUMER_API_KEY = os.getenv("TWITTER_CONSUMER_API_KEY")
TWITTER_CONSUMER_API_SECRET = os.getenv("TWITTER_CONSUMER_API_SECRET")
TWITTER_ACCESS_TOKEN = os.getenv("TWITTER_ACCESS_TOKEN")
TWITTER_ACCESS_SECRET = os.getenv("TWITTER_ACCESS_SECRET")
def create_api():
# Create API object
api = twitter.Api(
access_token_key = TWITTER_ACCESS_TOKEN,
access_token_secret = TWITTER_ACCESS_SECRET,
consumer_key = TWITTER_CONSUMER_API_KEY,
consumer_secret = TWITTER_CONSUMER_API_SECRET,
sleep_on_rate_limit=True)
# test API object
if api.VerifyCredentials():
pass
else:
logger.error("Error creating API", exc_info=True)
raise Exception("Twitter user authentication error")
logger.info("API created")
return api
Obviously there's an error in creating the API. I imagine this has something to do with the environment variables and how they are accessed through scheduled tasks vs. bash. Just really not sure how to figure this one out...

openstack: novaclient Python API not working

Trying to follow a simple tutorial for the openstack python API I found at http://docs.openstack.org/developer/python-novaclient/api.html but doesn't seem to be working. When I try to run
nova.servers.list()
or
nova.flavors.list()
from the tutorial on the python interpreter, I get following error:
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/novaclient/v2/servers.py", line 617, in list
return self._list("/servers%s%s" % (detail, query_string), "servers")
File "/usr/lib/python2.7/dist-packages/novaclient/base.py", line 64, in _list
_resp, body = self.api.client.get(url)
File "/usr/lib/python2.7/dist-packages/novaclient/client.py", line 440, in get
return self._cs_request(url, 'GET', **kwargs)
File "/usr/lib/python2.7/dist-packages/novaclient/client.py", line 399, in _cs_request
self.authenticate()
File "/usr/lib/python2.7/dist-packages/novaclient/client.py", line 569, in authenticate
self._v2_auth(auth_url)
File "/usr/lib/python2.7/dist-packages/novaclient/client.py", line 634, in _v2_auth
return self._authenticate(url, body)
File "/usr/lib/python2.7/dist-packages/novaclient/client.py", line 647, in _authenticate
**kwargs)
File "/usr/lib/python2.7/dist-packages/novaclient/client.py", line 392, in _time_request
resp, body = self.request(url, method, **kwargs)
File "/usr/lib/python2.7/dist-packages/novaclient/client.py", line 386, in request
raise exceptions.from_response(resp, body, url, method)
novaclient.exceptions.NotFound: The resource could not be found. (HTTP 404)
I'm using the same credentials as admin_openrc.sh, which works. Can't figure out what might be the problem.
You're using the python-novaclient as a library and it was never designed to be used that way. It's a CLI that people unfortunately use as a library.
Give the official Python OpenStack SDK a try.
pip install openstacksdk
The code for listing servers or flavors.
import sys
from openstack import connection
from openstack import profile
from openstack import utils
utils.enable_logging(True, stream=sys.stdout)
prof = profile.Profile()
prof.set_region(prof.ALL, 'RegionOne')
conn = connection.Connection(
auth_url='http://my.openstack.com:5000/v2.0',
profile=prof,
username='demo',
project_name='demo',
password='demo')
for server in conn.compute.servers():
print(server)
for flavor in conn.compute.flavors():
print(flavor)
More info that might be helpful too:
http://python-openstacksdk.readthedocs.org/en/latest/users/guides/compute.html
https://pypi.python.org/pypi/openstacksdk
From your description, CLI works fine but script/interpreter fail, so it definitely because you initialize the novaclient.client.Client in a wrong way.
The usage of novaclient.client.Client depends on what version you are using, but your question doesn't provide such information, so currently I cannot provide an example for you, you can check it by run command 'nova --version'.
you can get help from developer documents for python-novaclient http://docs.openstack.org/developer/python-novaclient/api.html
Remember that, it is a good practice to use keyword argument instead of normal argument, which means
nc = client.Client(version=2, user='admin', password='password',
project_id='12345678', auth_url='http://127.0.0.1:5000')
is encouraged, it will expose problem when you try to do something in a wrong way.
Solved the issue: not sure why, openstack complained of missing user domain in auth (don't remember the exactly message error). Couldn't find how to inform user domain in nova, but I do found it on keystone!
from keystoneclient.auth.identity import v3
from keystoneclient import session
from keystoneclient.v3 import client
auth_url = 'http://10.37.135.89:5000/v3/'
username = 'admin'
user_domain_name = 'Default'
project_name = 'admin'
project_domain_name = 'Default'
password = '123456'
auth = v3.Password(auth_url=auth_url,
username=username,
password=password,
project_id='d5eef1aae54742e787d0653eea57254b',
user_domain_name=user_domain_name)
sess = session.Session(auth=auth)
keystone = client.Client(session=sess)
keystone.projects.list()
and after that I used keystone for authenticating in nova:
from novaclient import client
nova = client.Client(2, session=keystone.session)
nova.flavors.list()
Some usefull links that I used for this answer:
http://docs.openstack.org/developer/python-keystoneclient/authentication-plugins.html
http://docs.openstack.org/developer/python-keystoneclient/using-api-v3.html
http://docs.openstack.org/developer/python-novaclient/api.html

Google Adwords API authentication issue

Just getting started on the Adwords API, for some reason I can't seem to connect at all.
The code below, straight from the tutorial throws the error:
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
client = AdWordsClient(path=os.path.join('Users', 'ravinthambapillai', 'Google Drive', 'client_secrets.json'))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/adspygoogle/adwords/AdWordsClient.py", line 151, in __init__
self._headers = self.__LoadAuthCredentials()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/adspygoogle/adwords/AdWordsClient.py", line 223, in __LoadAuthCredentials
return super(AdWordsClient, self)._LoadAuthCredentials()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/adspygoogle/common/Client.py", line 94, in _LoadAuthCredentials
raise ValidationError(msg)
**ValidationError: Authentication data is missing.**
from adspygoogle.adwords.AdWordsClient import AdWordsClient
from adspygoogle.common import Utils
client = AdWordsClient(path=os.path.join('Users', 'this-user', 'this-folder', 'client_secrets.json'))
It looks like there's two issues. First, try removing the last path element, as far as I recall, the path parameter expects a directory that contains the authentication pickle, logs etc. This approach requires that you already have a valid auth_token.pkl.
Second, it appears that you're using OAuth2 for authentication (I'm guessing by the client_secrets.json file). For this to work, you'll need to use the oauth2client library and provide an oauth2credentials instance in the headers parameter to AdWordsClient.
The following is straight from the file examples/adspygoogle/adwords/v201302/misc/use_oauth2.py in the client distribution and should give you an idea how it works:
# We're using the oauth2client library:
# http://code.google.com/p/google-api-python-client/downloads/list
flow = OAuth2WebServerFlow(
client_id=oauth2_client_id,
client_secret=oauth2_client_secret,
# Scope is the server address with '/api/adwords' appended.
scope='https://adwords.google.com/api/adwords',
user_agent='oauth2 code example')
# Get the authorization URL to direct the user to.
authorize_url = flow.step1_get_authorize_url()
print ('Log in to your AdWords account and open the following URL: \n%s\n' %
authorize_url)
print 'After approving the token enter the verification code (if specified).'
code = raw_input('Code: ').strip()
credential = None
try:
credential = flow.step2_exchange(code)
except FlowExchangeError, e:
sys.exit('Authentication has failed: %s' % e)
# Create the AdWordsUser and set the OAuth2 credentials.
client = AdWordsClient(headers={
'developerToken': '%s++USD' % email,
'clientCustomerId': client_customer_id,
'userAgent': 'OAuth2 Example',
'oauth2credentials': credential
})
I am not familiar with the AdWordsClient api but are you sure your path is correct?
your current join produces a relative path, do you need an absolute one?
>>> import os
>>> os.path.join('Users', 'this-user')
'Users/this-user'
For testing you could hardcode the absoulte path in to make sure it is not a path issue
I would also make sure that 'client_secrets.json exists, and that it is readable by the user executing python

Categories

Resources