How to get operating sytem of an instance in Google Compute Engine? - python

Using python, I need to get the long name of the operating system for an instance. I'm trying to follow the example here Get Guest Attributes, but there is no python sample code.
params = {
"variableKey": "LongName"
}
instance_client = googleapiclient.discovery.build('compute', 'v1')
request = instance_client.instances().getGuestAttributes(project=self.project, zone=self.zone, instance=self.instance)
response = request.execute()
Without adding the params to my request, the request runs fine but I don't get the information I want about the operating system. When I try to include the params in the request after self.instance, I get a positional argument error.
How do I add the params to the request so that I can get the operating system info? Also, am I constructing the params incorrectly?
Thanks for any help.

Related

Thoughtspot: API calls to fetch metadata via Python

I'm trying to fetch metadata from thoughtspot. I am able to call the url using browser and fetch the data. But here I'm trying to achieve it via python program. According to thougthspot documentation. I have to enable trusted authentication and pass my secret key & username to obtain a token which I can use in my program.
https://developers.thoughtspot.com/docs/?pageid=api-auth-session
my username : username#username.com
secret key : secret-key
Below is my code:(generated by postman)
import requests
url = "https://<ThoughtSpot-host>/callosum/v1/tspublic/v1/session/auth/token?auth_token=secret-key&access_level=FULL&username=username#username.com"
payload={}
headers = {}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
I'm getting Bad request error. Anyone here using thoughtspot over this issue. Appreciate your support very much.
Error I'm getting:
{"type":"Bad Request","description":"The server could not understand the request due to invalid syntax."}
I can fetch data by calling the api using a web-browser. Below url returns list of all meta-data objects. I want to achieve this using a python program (I have to authenticate first & call the below URL - Authentication step is not working for me when I tried to follow the documentation)
https://<ThoughtSpot-host>/callosum/v1/tspublic/v1/metadata/list
Did you try changing the url so that it includes the domain name?
Also post the error you are getting. And a screenshot of a working request would be great!

How to send post to laravel api from python?

This is my python request code.
url = "https://test.com/"
r = requests.get(url, verify=False)
xsrf_token = r.cookies.get("XSRF-TOKEN")
headers = {
'X-XSRF-TOKEN':xsrf_token
}
data = {"account": "O_O#gmail.com", "password": "123123"}
r = requests.post(url+'/app/get/users', verify=False, data = data, headers=headers)
In laravel log, I got
[2019-12-27 16:09:14] local.ERROR: The payload is invalid. {"exception":"[object] (Illuminate\Contracts\Encryption\DecryptException(code: 0): The payload is invalid. at /var/www/html/test/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php:195)
[stacktrace]
Have any method to solve that? Thanks.
You can't solve the issue with a static xsrf alone since it's doing its job preventing Cross Site Request Forging wich is exactly what you're doing in that piece of code.
To use a route as an API, the laravel installation needs to be configured that way, so, if needed, a stateless way of authentification is used (jwt for example) instead of the session with xsrf token for post methods.
Basicly if it's not configured to be used as an API, you will not be able to use it as an API.

How to correctly use PowerBI's REST API?

I have been working on using the powerbi REST API and I haven't been able to properly make use of it. I made use of this and I was able to register an app and get as far as getting an access token, but still I get 401 statuses on my requests.
My major points of confusion are with regards to the app registration:
1) I am trying to read and write data from a python script. Is this a Native-App or a Web Side Server?
2) What is the meaning of the redirect and home urls on the app registration page? I am currently using my localhost:5000 with different /paths. Could this be the source of the issue?
3) My research indicates that there should be some sort of login interaction. I don't have one, is this an indication that something isn't being done properly?
My code is as follows:
import adal
import requests
AUTHORITY_URL = 'https://login.microsoftonline.com/{my_company}.onmicrosoft.com'
RESOURCE = 'https://analysis.windows.net/powerbi/api'
CLIENT_ID = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
CLIENT_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
def make_headers(access_token):
return {
'Authorization': "Bearer {}".format(access_token)
}
context = adal.AuthenticationContext(AUTHORITY_URL)
token = context.acquire_token_with_client_credentials(RESOURCE, CLIENT_ID, CLIENT_SECRET)
access_token = token['accessToken']
headers = make_headers(access_token)
url = "https://api.powerbi.com/v1.0/myorg/datasets"
resp = requests.get(url, headers=headers)
As I said above this works to give me an access token though a get a status 401 response on the request and there is no sign in prompt.
Any help/guidance would be tremendously appreciated.
1) In your case you should register a Native app.
2) Native apps has only Redirect URI. Redirect URI gives AAD more details about the specific application it authenticates. For Native apps you should set it to https://login.live.com/oauth20_desktop.srf.
3) It's hard to say why you are getting Unauthorized response. Check what rights you gave to your application - does it has rights to read or write all datasets? Try to decode the access token at https://jwt.io and look at scp - does it contain "Dataset.Read.All" or "Dataset.ReadWrite.All"?

using an http request to update google spreadsheet

Trying to set up a spreadsheet to take in data via an http post. To test it, I set up a simple python script to just send an http request. I dont want to use a specific google api on python or somewhere else, because I want some other people to be able to simply send a request how they would like. So, In my google script I just have:
function doPost(e){
sheet = SpreadsheetApp.getActiveSheet();
range = sheet.getRange(1, 1)
ange.setValue(e.text)
}
In python I simply have:
import requests
if __name__== "__main__":
params = {'Authorization': "Bearer [token]",
'contentType': 'application/json',
'text': "is working?"}
r = requests.post("https://script.google.com/macros/s/[uniquekey]/exec", params)
print(r.status_code, r.reason)
All I get is
"401 Unauthorized"
I've also tried sending this over python as well as running JS in a webserver and through chrome (which i guessed raised security issues). everything gave me the same response. I'm sure I'm just not authorizing properly, but I havent been able to find the correct way to do it. thanks in advance. I'm sure theres some other issues too, but I cant seem to even get access.
How about this modification?
Modified script:
In this modified script supposes as follows.
Web Apps is deployed as
Execute the app as is Me
Who has access to the app is Only myself or Anyone
Your access token can be used for accessing to your Web Apps.
If your access token cannot be used for it, please try to set the Web Apps as follows.
- Execute the app as is Me
- Who has access to the app is Anyone, even anonymous
- In this setting, you can access to Web Apps without the access token.
Python:
import requests
if __name__== "__main__":
params = {
'text': "is working?",
}
headers = {
'Authorization': "Bearer [token]",
}
r = requests.post("https://script.google.com/macros/s/[uniquekey]/exec", data=params, headers=headers)
print(r.status_code, r.reason)
Note:
Please put the access token to the header.
Google Apps Script:
When you modified your script, please redeploy as new version. By this, the latest script is reflected to the Web Apps.
function doPost(e) {
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange(1, 1);
range.setValue(e.parameter.text);
return ContentService.createTextOutput("Done.");
}
Note:
By returning ContentService.createTextOutput(), Web Apps returns the status code of 200.
You can retrieve the value of 'text': "is working?" as e.parameter.text.
When you use SpreadsheetApp.getActiveSheet(), the value of e.parameter.text is put to the 1st page of Spreadsheet.
References:
Web Apps
ContentService
In my environment, I could confirm that this modification worked. But if in your environment, this modified scripts didn't work, I'm sorry.

Getting Azure Event Hubs metrics using rest api?

I'm trying to pull the event hubs metrics using the rest API,
after reading https://msdn.microsoft.com/en-us/library/azure/dn163589.aspx and https://msdn.microsoft.com/en-us/library/azure/mt652158.aspx
I have got python code that can actually call the url and get a response
I currently try the following code
def get_metrics(subscription, eventhub, cert, specific_partition=None):
apiversion = '2014-01'
namespace = eventhub['namespace']
eventhubname = eventhub['name']
url = "https://management.core.windows.net/{}/services/ServiceBus/Namespaces/{}/eventhubs/{}/Metrics/requests.total/Rollups/P1D/Values/?$filter=timestamp%20gt%20datetime'2016-04-09T00:00:00.0000000Z'&api-version={}".format(
subscription, namespace, eventhubname, apiversion)
request = requests.Request('GET', url, headers=DEFAULT_HEADERS).prepare()
session = requests.Session()
if cert is None or not os.path.isfile(cert):
raise ValueError('You must give certificate file')
session.cert = cert
result = session.send(request)
return result
my problem is with the url, when using the url in the code above I get
<Error xmlns="http://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><Code>InternalError</Code><Message>The server encountered an internal error. Please retry the request.</Message></Error>
I can get the API to output all possible rollups and all possible metrics but when trying to get actual values it fails.
is there something wrong in the url or is it a bug in azure/azure documantation?
Usually, when we occur this issue, it means that there something wrong with the endpoint we combined for the Rest Apis, so that then service raise exception when parse the endpoint.
As compared with my successfully test, what the interesting I found is that the issue raised by the filter param timestamp whose first letter should be uppercased as Timestamp. The following endpoint works fine on my side. Hope it will be helpful to you.
url = "https://management.core.windows.net/{}/services/ServiceBus/Namespaces/{}/eventhubs/{}/Metrics/requests.total/Rollups/P1D/Values/?$filter=Timestamp%20gt%20datetime'2016-04-09T00:00:00.0000000Z'&api-version={}".format(
subscription, namespace, eventhubname, '2012-03-01')

Categories

Resources