Python Psphere Issue - python

Looking at using psphere. I've successfully installed it via pip but run into an issue when I execute the following code (taken from the psphere documentation site):
from psphere.client import Client
from psphere.managedobjects import HostSystem
Client = Client("server", "username", "password")
hs_list = HostSystem.all(Client)
len(hs_list)
After running that command I get the following:
"could not found expected ':'", self.get_mark())
yaml.scanner.ScannerError: while scanning a simple key
in "C:\Users\thor/.psphere/config.yaml", line 5, column 1
could not found expected ':'
in "C:\Users\thor/.psphere/config.yaml", line 6, column 1
There was no .psphere directory or config.yaml. I created both and no joy (although I must be honest - I don't really know what should be in the yaml file.)
There are no : in my file so I don't know why it's raising an exception.
Help would be appreciated. Thanks.

in the distribution's examples/ directory there is a sample_config.yaml file you can use.
# Copy this file into ~/.psphree/config.yaml and edit to your liking
general:
server: your.esxserver.com
username: Administrator
password: strongpassword
template_dir: ~/.psphere/templates/
logging:
destination: ~/.psphere/psphere.log
level: INFO # DEBUG, INFO, etc

Related

Pyinfra - host/config objects

I was trying to run through some of the examples from pyinfra's docs to see if this tool would work for me (so I could manage some servers using good old Python) and I even found they had an example for installing virtualbox on a host machine, but I can't get even the example working. I'm getting a weird error that makes me think there's been an update to the tool since the examples, and even the docs, have been updated. Just wondering if anyone else has a way to get this to work with pyinfra (currently trying with version 1.5).
The example code:
from pyinfra import config, host
from pyinfra.facts.server import LinuxDistribution, LinuxName, OsVersion
from pyinfra.operations import apt, python, server
config.SUDO = True
virtualbox_version = '6.1'
def verify_virtualbox_version(state, host, version):
command = '/usr/bin/virtualbox --help'
status, stdout, stderr = host.run_shell_command(state, command=command, sudo=config.SUDO)
assert status is True # ensure the command executed OK
if version not in str(stdout):
raise Exception('`{}` did not work as expected.stdout:{} stderr:{}'.format(
command, stdout, stderr))
if host.get_fact(LinuxName) == 'Ubuntu':
code_name = host.get_fact(LinuxDistribution)['release_meta'].get('DISTRIB_CODENAME')
apt.packages(
name='Install packages',
packages=['wget'],
update=True,
)
apt.key(
name='Install VirtualBox key',
src='https://www.virtualbox.org/download/oracle_vbox_2016.asc',
)
apt.repo(
name='Install VirtualBox repo',
src='deb https://download.virtualbox.org/virtualbox/debian {} contrib'.format(code_name),
)
# install kernel headers
# Note: host.get_fact(OsVersion) is the same as `uname -r` (ex: '4.15.0-72-generic')
apt.packages(
{
'Install VirtualBox version {} and '
'kernel headers for {}'.format(virtualbox_version, host.get_fact(OsVersion)),
},
[
'virtualbox-{}'.format(virtualbox_version),
'linux-headers-{}'.format(host.get_fact(OsVersion)),
],
update=True,
)
server.shell(
name='Run vboxconfig which will stop/start VirtualBox services and build kernel modules',
commands='/sbin/vboxconfig',
)
python.call(
name='Verify VirtualBox version',
function=verify_virtualbox_version,
version=virtualbox_version,
)
Here is the error that I'm seeing:
File "install_virtualbox.py", line 21, in <module>
if host.get_fact(LinuxName) == 'Ubuntu':
AttributeError: module 'pyinfra.api.host' has no attribute 'get_fact'
I checked the source and I can't argue with my editor when it says it 'cannot find a reference to config' or 'init', as I don't see them either. But then how is anyone getting facts about hosts? Looks like the logic may have been moved to the 'pyinfra.api.host' and 'pyinfra.api.config' packages, but the logic there looks totally different.
Hoping I'm just missing something that someone who's been using the tool can help explain to me.

import-im6.q16: not authorized `boto3' # error/constitute.c/WriteImage/1037

I use AWS CLI . i installed boto3 and i try run that code. i have three errors
import boto3
s3 = boto3.resource('s3')
# Get list of objects for indexing
images=[('afridi.jpg','Shahid Afridi'),
('sakib.jpg','Sakib Al Hasan'),
('kohli.jpg','Birat Kohli'),
('masrafi.jpg','Mashrafe Bin Mortaza'),
('ganguli.jpg','Sourav Ganguly')
]
Iterate through list to upload objects to S3
for image in images:
file = open(image[0],'rb')
object = s3.Object('taifur12345bucket',image[0])
ret = object.put(Body=file,
Metadata={'FullName':image[1]}
)
the errors
import-im6.q16: not authorized `boto3' # error/constitute.c/WriteImage/1037.
./code1.py: line 2: syntax error near unexpected token `('
./code1.py: line 2: `s3 = boto3.resource('s3')'
Your script is missing the shebang line #!/usr/bin/env python3 at the top. Because of this, your script is being run by the bash shell, not by the Python interpreter. bash doesn't understand Python code, hence the errors you are getting.
Add the shebang line to the top of your script and try again.
If you are not running this code from a permissioned ec2 instance, you will need to configure your credentials appropriately.
see configuration section here

Integrate airbrake with Python

When I'm trying to integrate python logging with airbrake, I get following errors:
main.py
import pybrake
from config2.config import config
airbrake_handler = None
def filter_airbrake_msgs(notice):
if config.environment in ['production', 'staging']:
return notice
return None
def config_airbrake():
print(config.py_brake)
notifier = pybrake.Notifier(
project_id=config.py_brake.project_id,
project_key=config.py_brake.project_key
)
config_airbrake()
ENV=development python3 main.py
Error :
ERROR pybrake get_git_revision failed: [Errno 2] No such file or directory: '/user/xxx/xxx/xxx/.git/HEAD'
That looks like a log message coming from https://github.com/airbrake/pybrake/blob/master/pybrake/git.py#L12. I see why it is confusing but it is actually harmless and you can ignore it. I've created an issue to remove that log message. And feel free to use Github issues for such questions in future.
Overall pybrake checks if directory stored in context.rootDirectory contains a Git folder. If there is a git folder there it tries to extract some info like git revision, checkout date etc. Otherwise it logs the first error.

Python- Google voice

I am trying to use http://sphinxdoc.github.io/pygooglevoice/examples.html#send-sms-messages and I am getting the error
File "build/bdist.macosx-10.6-intel/egg/googlevoice/voice.py", line 72, in login
AttributeError: 'NoneType' object has no attribute 'group'
My code is:
from googlevoice import Voice
from googlevoice.util import input
import sys
username, password = "email#gmail.com", "password"
voice = Voice()
voice.login(username, password)
phoneNumber = input('Number to send message to: ')
text = input('Message text: ')
voice.send_sms(phoneNumber, text)
I was wondering if that is a login error or error in the code? If so, how can I edit the code so that it works?
Thank you so much!
EDIT: I have been researching this and apparently it's a common problem and I have to change line 72 in the file voice.py but I can't find the file:
/usr/local/lib/python2.7/dist-packages/googlevoice/voice.py
To install, I did:
$ pip install python python-setuptools
$ sudo easy_install simplejson
$ sudo easy_install -U pygooglevoice
And now I can't find the voice.py file. I have been looking for a while on my mac but found nothing.
Other questions with the same problem:
https://code.google.com/archive/p/pygooglevoice/issues/76
googlevoice will not programatically login (Python)
python: pygooglevoice unable to login
Please please please help!
After struggling through errors and replacing the one line (which never worked...) I downloaded https://github.com/pettazz/pygooglevoice and put the googlevoice file in the same file I was working on. Hope this helps anyone with the same question.

Getting WindowsError when trying ot copy a file from one directory to another w/ paramiko

Good afternoon,
I am getting the following error whenever I am trying to copy a test file from one directory to another on a remote server:
Traceback (most recent call last):
File "", line 1, in
File "C:\Python27\lib\site-packages\paramiko-1.12.0-py2.7.egg\paramiko\sftp_client.py", line 612, in put
file_size = os.stat(localpath).st_size
WindowsError: [Error 3] The system cannot find the path specified: '/brass/prod/bin/chris/test1/km_cust'
The file I am looking to copy is called km_cust.
I am executing these commands in python 2.7.
Please note that the hostname, uid, and password were changed to generic versions and the real hostname, uid, and password can be used to ssh to the box in question and preform all functionality.
Here is my code:
import paramiko
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect('hostname',username='test',password='pw')
filepath = '/brass/prod/bin/chris/test1/km_cust'
localpath = 'brass/prod/bin/chris/test2'
sftp = s.open_sftp()
sftp.put(filepath, localpath)
Any help will be apprecaited. Let me know if any other information is needed.
The problem is that put copies a local file—that is, a file n your Windows box—to the server. As the documentation says:
put(self, localpath, remotepath, callback=None, confirm=True)
Copy a local file (localpath) to the SFTP server as remotepath.
Note that you're also specifying (or at least naming) the paths backward… but that doesn't really matter here, because neither one is actually a local path. So when you do this:
sftp.put(filepath, localpath)
… it's looking for a file named '/brass/prod/bin/chris/test1/km_cust' on your Windows box, and of course it can't find such a file.
If you want to copy a remote file to a different remote file, you need to do something like this:
f = sftp.open(filepath)
sftp.putfo(f, localpath)
Or:
f = sftp.open(localpath, 'wx')
sftp.getfo(filepath, f)
Also, I'm guessing your filepath is supposed to start with a /.
However, this probably isn't what you wanted to do in the first place. Copying a file from the remote server to the remote server via sftp involves downloading all of the bytes to your Windows machine and then uploading them back to the remote machine. A better solution would be to just tell the machine to do the copy itself:
s.exec_command("cp '{}' '{}'".format(filepath, localfile))
s.close()
Note that in anything but the most trivial of cases, you're going to have to deal with the Channel and its in/out/err and wait on its exit status. But I believe that for this case, you should be fine.

Categories