Softlayer Server_ID - python-2.7

I am trying to implement the following:
import SoftLayer.API
username = 'set me!'
apiKey = 'set me too!'
serverId = 1234
client = SoftLayer.API.Client('SoftLayer_Hardware_Server', serverId, username, apiKey)
Here, I don't really know how to retrieve the serverId. How could I know my server ID for a specific server. Please help.

The SoftLayer_Account::getHardware retrieves information about your hardware objects, in which you can find the serverIds from your servers.
Try this python script:
"""
This script retrieves an account's associated hardware objects
Important manual pages:
http://sldn.softlayer.com/reference/services/SoftLayer_Account/getHardware
License: http://sldn.softlayer.com/article/License
Author: SoftLayer Technologies, Inc. <sldn#softlayer.com>
"""
# So we can talk to the SoftLayer API:
import SoftLayer.API
# For nice debug output:
from pprint import pprint as pp
# Your SoftLayer username and api key
API_USERNAME = 'set me'
API_KEY = 'set me'
# Creates a new connection to the API service.
client = SoftLayer.API.Client(username=API_USERNAME,api_key=API_KEY)
try:
hardwareObjects = client['SoftLayer_Account'].getHardware()
pp(hardwareObjects)
except SoftLayer.SoftLayerAPIError as e:
pp('Unable to get hardware objects faultCode=%s, faultString=%s'
% (e.faultCode, e.faultString))
This script will return the information from your servers, in which the "id" property refers to serverId from the server that you need.
However, if you wish to retrieve the information for an specific server, it can be done using Object Filters, here an example:
"""
This script retrieves a hardware information for an specific hardware object.
It is only necessary to specify the hostname from the server.
Important manual pages:
http://sldn.softlayer.com/reference/services/SoftLayer_Account/getHardware
http://sldn.softlayer.com/article/object-filters
License: http://sldn.softlayer.com/article/License
Author: SoftLayer Technologies, Inc. <sldn#softlayer.com>
"""
# So we can talk to the SoftLayer API:
import SoftLayer.API
# For nice debug output:
from pprint import pprint as pp
# Your SoftLayer username and api key
API_USERNAME = 'set me'
API_KEY = 'set me'
# Define the hostname from the hardware object
hostname = 'hostnametest'
# Declare an object filter to get an specific hardware object
filterHardware = {
'hardware': {
'hostname': {
'operation': hostname
}
}
}
# Creates a new connection to the API service.
client = SoftLayer.API.Client(username=API_USERNAME,api_key=API_KEY)
try:
hardwareObjects = client['SoftLayer_Account'].getHardware(filter=filterHardware)
pp(hardwareObjects)
except SoftLayer.SoftLayerAPIError as e:
pp('Unable to get the hardware object faultCode=%s, faultString=%s'
% (e.faultCode, e.faultString))
You need to specify the "hostname" from your server. The "id" in the response refers to serverId.
Some references:
Using Initialization Parameters in the SoftLayer
API
SoftLayer Python
Going Further with the SoftLayer API Python Client - Part 1

Related

Launch GCP instance from my PC using python

Which python library should i use to control or launch or delete an instance on my Google cloud platform from my private PC ?
I think the simplest way is to use the Google Compute Engine Python API Client Library. You can see a sample with examples here.
You can see the complete list of functions regarding instances in REST Resource: instances
As you can see, you might do:
import googleapiclient.discovery
compute = googleapiclient.discovery.build('compute', 'v1')
listInstance = compute.instances().list(project=project, zone=zone).execute()
stopInstance = compute.instances().stop(project=project, zone=zone, instance=instance_id).execute()
startInstance = compute.instances().start(project=project, zone=zone, instance=instance_id).execute()
deleteInstance = compute.instances().delete(project=project, zone=zone, instance=instance_id).execute()
Don't confuse the param name "instance" with the chosen name for the path parameter "resourceId". You can see on the right side or at the bottom of the page examples with the real parameter's name.
You also could directly call the the REST API (see example) with in Python if you prefer to using POST/PUT methods.
You also might want to use OAuth. As you can see in the examples of the links provided, it would be something like:
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
credentials = GoogleCredentials.get_application_default()
service = discovery.build('compute', 'v1', credentials=credentials)
# Project ID for this request.
project = 'my-project' # TODO: Update placeholder value.
# The name of the zone for this request.
zone = 'my-zone' # TODO: Update placeholder value.
# Name of the instance resource to start.
instance = 'my-instance' # TODO: Update placeholder value.
request = service.instances().start(project=project, zone=zone, instance=instance)
response = request.execute()
You may also want to check out libcloud.

Error Pulling Facebook Ad Campaign

I am trying to automate a task for my company. They want me to pull the insights from their ad campaigns and put it in a CSV file. From here I will create a excel sheet that grabs this data and automates the plots that we send to our clients.
I have referenced the example code from the library and I believe where my confusion exists is in who I define 'me' to be in line 14.
token = 'temporary token from facebook API'
VOCO_id = 'AppID'
AppSecret = 'AppSecret'
me = 'facebookuserID'
AppTokensDoNotExpire = 'AppToken'
from facebook_business import FacebookSession
from facebook_business import FacebookAdsApi
from facebook_business.adobjects.campaign import Campaign as AdCampaign
from facebook_business.adobjects.adaccountuser import AdAccountUser as AdUser
session = FacebookSession(VOCO_id,AppSecret,AppTokensDoNotExpire)
api = FacebookAdsApi(session)
FacebookAdsApi.set_default_api(api)
me = AdUser(fbid=VOCO_id)
####my_account = me.get_ad_account()
When I run the following with the hashtag on my_account, I get a return stating that the status is "live" for these but the value of my permissions is not compatible.

Authenticating to use Google Sheets REST api with Python

I am trying to use a local (mac) python program to append a row to a google sheet. I naively thought the snippet below would be sufficient:
import requests
url = "https://sheets.googleapis.com/v4/spreadsheets/SHEETID/values/Expenses!A1:D1:append?valueInputOption=USER_ENTERED"
data = {
"range": "Expenses!A1:D1",
"majorDimension": "ROWS",
"values": [
[NEW ROW DATA]]
],
}
resp = requests.post(url, data)
I am getting the error:
401: "Request is missing required authentication credential.
Expected OAuth 2 access token, login cookie or other valid
authentication credential.
I am not to sure how to set-up the authentication for the google sheets rest api.
Can anyone provide an example of how to go about this.
You can try the sample python code in the documentation.
"""
BEFORE RUNNING:
---------------
1. If not already done, enable the Google Sheets API
and check the quota for your project at
https://console.developers.google.com/apis/api/sheets
2. Install the Python client library for Google APIs by running
`pip install --upgrade google-api-python-client`
"""
from pprint import pprint
from googleapiclient import discovery
# TODO: Change placeholder below to generate authentication credentials. See
# https://developers.google.com/sheets/quickstart/python#step_3_set_up_the_sample
#
# Authorize using one of the following scopes:
# 'https://www.googleapis.com/auth/drive'
# 'https://www.googleapis.com/auth/drive.file'
# 'https://www.googleapis.com/auth/spreadsheets'
credentials = None
service = discovery.build('sheets', 'v4', credentials=credentials)
# The ID of the spreadsheet to update.
spreadsheet_id = 'my-spreadsheet-id' # TODO: Update placeholder value.
# The A1 notation of a range to search for a logical table of data.
# Values will be appended after the last row of the table.
range_ = 'my-range' # TODO: Update placeholder value.
# How the input data should be interpreted.
value_input_option = '' # TODO: Update placeholder value.
# How the input data should be inserted.
insert_data_option = '' # TODO: Update placeholder value.
value_range_body = {
# TODO: Add desired entries to the request body.
}
request = service.spreadsheets().values().append(spreadsheetId=spreadsheet_id, range=range_, valueInputOption=value_input_option, insertDataOption=insert_data_option, body=value_range_body)
response = request.execute()
# TODO: Change code below to process the `response` dict:
pprint(response)
and also
Since you are working with the app that access data from the other user open this guide for Authorize Requests to know more about authentication credentials.

Pydrive authentication using

I was using gdata module to access, upload, download files from google doc. I have the oauth key and secret with me. Now I want to switch to google drive api. Learning and studying a bit on google drive api , it looks like a bit different in the authentication. I also have downloaded pydrive module so as I can start things up. But I am not able to authorize my server side python code to authorize/authenticate the user using my oauth keys and access my drive. Do any one has any spare know how on how I can use pydrive to access my drive with my previous auth keys. I just need a simple way to authenticate.
For using the gdata module we use either of these credentials-
1> username & password or
2> consumer oauth key and secret key.
Since you are trying to use oauth credentials, I think you want a Domain Wide Delegated Access for Google Drive, which will help you to achieve uploading/downloading files into any user's google drive through out the domain.
For this you need to generate a new Client ID of a Service Account Type from
Developer's Console
*.p12 file will get downloaded. Note the path where you save it.
Also note the email address of your Service account. These will be use while coding.
Below is the python code where u have to carefully edit-
PATH TO SERIVE ACCOUNT PRIVATE KEY, something#developer.gserviceaccount.com, EMAIL_ID#YOURDOMAIN.COM in order to run it properly and test it.
Hope this will help!
Resource- Google Drive API
import httplib2
import pprint
import sys
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
"""Email of the Service Account"""
SERVICE_ACCOUNT_EMAIL = 'something#developer.gserviceaccount.com'
"""Path to the Service Account's Private Key file"""
SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'PATH TO SERIVE ACCOUNT PRIVATE KEY'
def createDriveService(user_email):
"""Build and returns a Drive service object authorized with the service accounts
that act on behalf of the given user.
Args:
user_email: The email of the user.
Returns:
Drive service object.
"""
f = file(SERVICE_ACCOUNT_PKCS12_FILE_PATH, 'rb')
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials(SERVICE_ACCOUNT_EMAIL, key,
scope='https://www.googleapis.com/auth/drive', sub=user_email)
http = httplib2.Http()
http = credentials.authorize(http)
return build('drive', 'v2', http=http)
drive_service=createDriveService('EMAIL_ID#YOURDOMAIN.COM')
result = []
page_token = None
while True:
try:
param = {}
if page_token:
param['pageToken'] = page_token
files = drive_service.files().list().execute()
#print files
result.extend(files['items'])
page_token = files.get('nextPageToken')
if not page_token:
break
except errors.HttpError, error:
print 'An error occurred: %s' % error
break
for f in result:
print '\n\nFile: ',f.get('title')
print "\n"

listing out all the datastores in specific esx host from Pysphere

I want to get all the datastores from a specific cluster. I will be using this for my vapp deployment.
i tried the following snippet:
clusters = server.get_clusters()
for c_mor, c_name in clusters.items():
for ds_mor, name in server.get_datastores(from_mor=c_mor).items():
props = VIProperty(server, ds_mor)
print props.name
However, this does not give me the list. What am I doing wrong?
It's to late for answer this question. this my code.
from pysphere import VIServer, VIProperty
server = VIServer()
server.connect(server, username, password)
for ds_mor, name in server.get_hosts().items():
props = VIProperty(server, ds_mor)
for item in props.datastore :
print item.info.name
server.disconnect()
Old question but if anyone outside is looking for a solution (this is the first result in google), this will directly gather information from datastores:
from pysphere import VIServer, VIProperty
import ssl
default_context = ssl._create_default_https_context
server = VIServer()
#user = the-user-to-connect-to-vsphere
#password = the-password-from-the-user
#host = the-vsphere-hostname-or-ip
try:
ssl._create_default_https_context = ssl._create_unverified_context
server.connect(host, user, password)
for ds_mor, name in server.get_datastores().items():
props = VIProperty(server, ds_mor)
print "Datastore name: ", name
server.disconnect()
finally:
ssl._create_default_https_context = default_context
This will connect to self-signed VSphere, as is usual de case in an intranet.