Read user email contents using imaplib2 - python-2.7

I'm writing a python code to read email from mail server(neither google nor outlook) using imaplib2 package. I'm getting the following error with my code. Can anybody tell me how could I fix it. Do I need to use only port=993 and host=imap, if so how can I connect to the server I need to
import imaplib2
import base64
email_user = 'mailid'
email_pass = 'password'
email_server = 'ns21.interactivedns.com'
Mail = imaplib2.IMAP4_SSL(email_server, 995) # used this server and port since I'm trying to read mail contents from this server
Mail.login(email_user, email_pass)
Mail.select('Inbox')
type, messages = Mail.search(None, 'ALL')
Error I'm gertting:
Traceback (most recent call last):
File "C:/Users/user01/PycharmProjects/MongoAlchemy/client.py", line 6, in <module>
M = imaplib2.IMAP4_SSL('ns21.interactivedns.com', 995)
File "C:\Users\user01\PycharmProjects\MongoAlchemy\venv\lib\site-packages\imaplib2\imaplib2.py", line 2073, in __init__
IMAP4.__init__(self, host, port, debug, debug_file, identifier, timeout, debug_buf_lvl)
File "C:\Users\user01\PycharmProjects\MongoAlchemy\venv\lib\site-packages\imaplib2\imaplib2.py", line 392, in __init__
raise self.error('unrecognised server welcome message: %s' % repr(self.welcome))
imaplib2.imaplib2.error: unrecognised server welcome message: None

Related

How fix no basic auth credentials error wit hdockerpy and aws ecr repo?

I m trying to execute the folowing python code:
import logging
import sys
import docker, boto3
from base64 import b64decode
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
LOCAL_REPOSITORY = '111111111111.dkr.ecr.us-east-1.amazonaws.com/my_repo:latest'
image = '111111111111.dkr.ecr.us-east-1.amazonaws.com/my_repo'
ecr_registry, _ = image.split('/', 1)
client = docker.from_env()
# Get login credentials from AWS for the ECR registry.
ecr = boto3.client('ecr')
response = ecr.get_authorization_token()
token = b64decode(response['authorizationData'][0]['authorizationToken'])
username, password = token.decode('utf-8').split(':', 1)
# Log in to the ECR registry with Docker.
client.login(username, password, registry=ecr_registry)
logging.info("loggined")
client.images.pull(image, auth_config={
username: username,
password: password
})
And got exception:
C:\myPath>python app/pull_example.py
INFO:botocore.credentials:Found credentials in environment variables.
INFO:root:loggined
Traceback (most recent call last):
File "C:\Python3\lib\site-packages\docker\api\client.py", line 261, in _raise_for_status
response.raise_for_status()
File "C:\Python3\lib\site-packages\requests\models.py", line 940, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 500 Server Error: Internal Server Error for url: http+docker://localnpipe/v1.35/images/create?fromImage=111111111111.dkr.ecr.us-east-1.amazonaws.com%2Fmy_repo
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "app/pull_example.py", line 41, in <module>
password: password
File "C:\Python3\lib\site-packages\docker\models\images.py", line 445, in pull
repository, tag=tag, stream=True, **kwargs
File "C:\Python3\lib\site-packages\docker\api\image.py", line 415, in pull
self._raise_for_status(response)
File "C:\Python3\lib\site-packages\docker\api\client.py", line 263, in _raise_for_status
raise create_api_error_from_http_exception(e)
File "C:\Python3\lib\site-packages\docker\errors.py", line 31, in create_api_error_from_http_exception
raise cls(e, response=response, explanation=explanation)
docker.errors.APIError: 500 Server Error: Internal Server Error ("Get https://111111111111.dkr.ecr.us-east-1.amazonaws.com/v2/my_repo/tags/list: no basic auth credentials")
What is the problem? Why I can not pull image even after client.login call which happens wihtout any exeptions. What is the correct way to perform login and pull image from ECR repository and dockerpy?
This was happen due to - https://github.com/docker/docker-py/issues/2157
Deleting ~/.docker/config.json fixed the issue.

Sample connection for HIVE and Python

I am trying to connect python with hive data base .
Both are on different server.
hive resides on host xx.xxx.xxx.x and python is on my local system.
i am trying to use the below code , however its not working
import pyhive
from pyhive import hive
conn = hive.connect(host = 'xx.xxx.xx.xx', port = 8888, auth = 'KERBEROS', kerberos_service_name='adsuedscaihen01.aipcore.local', username ='user1', database = 'database1'
)
cur = conn.cursor()
cur.execute('SELECT * from table1')
result = cur.fetchall()
print(result)
while i run the above code , i am facing the below error:
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python2.7/site-packages/pyhive/hive.py", line 64, in connect
return Connection(*args, **kwargs)
File "/usr/lib/python2.7/site-packages/pyhive/hive.py", line 162, in init
self._transport.open()
File "/usr/lib/python2.7/site-packages/thrift_sasl/init.py", line 79, in open
message=("Could not start SASL: %s" % self.sasl.getError()))
thrift.transport.TTransport.TTransportException: Could not start SASL: Error in sasl_client_start (-1) SASL(-1): generic failure: GSSAPI Error: Unspecified GSS failure. Minor code may provide more information (Server not found in Kerberos database)

Connect to Django test database

Is there a way to connect to django test database using connections?
I have tried
cursor = connections['test_name_of_main_db'].cursor()
and also specified the test db name in settings but I still receive errors:
Traceback (most recent call last):
File "/home/tets/4d/lib/python3.5/site-packages/django/db/utils.py", line 176, in ensure_defaults
conn = self.databases[alias]
KeyError: 'auto_tests'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/tets/healthware_server/component/medical/tests.py", line 72, in test_model_observation
cursor = connections['auto_tests'].cursor()
File "/home/tets/4d/lib/python3.5/site-packages/django/db/utils.py", line 208, in __getitem__ self.ensure_defaults(alias)
File "/home/tets/4d/lib/python3.5/site-packages/django/db/utils.py", line 178, in ensure_defaults
raise ConnectionDoesNotExist("The connection %s doesn't exist" % alias)
django.db.utils.ConnectionDoesNotExist: The connection auto_tests doesn't exist
According to the docs:
The default test database names are created by prepending test_ to the value of each NAME in DATABASES.
But in your stacktrace the error says:
django.db.utils.ConnectionDoesNotExist: The connection auto_tests doesn't exist
Are you sure you are using the right alias? According to the error, it is looking for a database named auto_tests.
As another debugging step, you could print all the aliases during the test to see which ones are available
for alias in connections:
print(alias)
Of course, you could also try to use the default database and see if that works for you during the tests:
# note that it is 'connection' and not 'connections'
from django.db import connection
cursor = connection.cursor()

How to connect Python and neo4j?

I am new to neo4j and want it to connect with Python. I am using neo4j version 3.0.3 and following this tutorial.
I put the code below in my Python file, I have changed the password, since my password is root:
from neo4j.v1 import GraphDatabase, basic_auth
driver = GraphDatabase.driver("bolt://localhost", auth=basic_auth(user = "neo4j", password = "root"))
session = driver.session()
session.run("CREATE (a:Person {name:'Bob'})")
result = session.run("MATCH (a:Person) RETURN a.name AS name")
for record in result:
print(record["name"])
session.close()
But on running it, I am getting following errors:
Traceback (most recent call last):
File "D:/Work/MySQL_neo4j_Importer/dumping_ingredients.py", line 3, in <module>
session = driver.session()
File "C:\Python27\lib\site-packages\neo4j\v1\session.py", line 148, in session
session = Session(self)
File "C:\Python27\lib\site-packages\neo4j\v1\session.py", line 461, in __init__
self.connection = connect(driver.host, driver.port, driver.ssl_context, **driver.config)
File "C:\Python27\lib\site-packages\neo4j\v1\connection.py", line 403, in connect
s = create_connection((host, port))
File "C:\Python27\lib\socket.py", line 557, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno 11004] getaddrinfo failed
I have also tried this StackOverFlow answer as well, but, the result remains same.
For Neo4j 1.8 / 1.9 / 2.0 / 2.1 / 2.2 / 2.3 you could use Py2neo.
Here you can find an exhaustive list of python drivers

pyhs2 error connective to kerberos enabled hive

I am trying to connect to hive using python 2(miniconda2 installation ).
Below is the code I am trying-
connection = hive.connect(host='psvlxihpnn1', port= '10000', authMechanism='KERBEROS', user='***',password='****', configuration={'krb_host': 'psvlxihpnn1', 'krb_service': 'ITEDM'} )
kerberos host is installed on the same host machine and has service name 'ITEDM'
Strangely, I am getting below error-
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/export/home/itedm/miniconda2/lib/python2.7/site-packages/pyhs2-0.6.0-py2.7.egg/pyhs2/__init__.py", line 7, in connect
File "/export/home/itedm/miniconda2/lib/python2.7/site-packages/pyhs2-0.6.0-py2.7.egg/pyhs2/connections.py", line 46, in __init__
File "/export/home/itedm/miniconda2/lib/python2.7/site-packages/pyhs2-0.6.0-py2.7.egg/pyhs2/cloudera/thrift_sasl.py", line 66, in open
thrift.transport.TTransport.TTransportException: Could not start SASL: Error in sasl_client_start (-1) SASL(-1): generic failure: GSSAPI Error: Unspecified GSS failure. Minor code may provide more information (Server krbtgt/INFORMATICA.COM#ITEDM not found in Kerberos database)
I am not passing 'krbtgt' as user, not sure why this error is coming.
Thanks for any help.
This connection string will work as long as the user running the script has a valid kerberos ticket:
import pyhs2
with pyhs2.connect(host='beeline_host',
port=10000,
authMechanism="KERBEROS") as conn:
with conn.cursor() as cur:
print cur.getDatabases()
Username, password and any other configuration parameters are not passed through the KDC.