I have a form built via web2py that i need to use to validate and register a machine and store it into a database. The validation is not passing through. I am always getting error that "Houston there seems to be a problem with Machine name or super password". If i run the paramiko script outside the web2py environment it is working fine. Please help.
Form Details:
db.define_table('nsksystem',
Field('nskmachinename', length=128, requires = IS_NOT_EMPTY(error_message='Machine Name cant be empty'), label = T('Machine Name')),
Field('nskpassword', 'password', length=512,readable=False, label=T('Machine Password')),
Field('confirmnskpassword', 'password', length=512,readable=False, label=T('Confirm Machine Password')) )
Controller: default.py( for validating the form insertion before inserting)
def machinevalidate(form):
host = form.vars.nskmachinename
user ='superman'
pwd = form.vars.nskpassword
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(host, username=user,password=pwd)
return True
except Exception, e:
form.errors.nskpassword = 'Houston there seems to be a problem with Machine name or super password'
finally:
ssh.close()
Controller: default.py (for the insertion into database)
#auth.requires_login()
def machine():
form = SQLFORM(db.nsksystem)
if form.process(onvalidation=machinevalidate).accepted:
response.flash = 'The machine is now registered to the user.'
elif form.errors:
response.flash = 'Form has errors'
else:
response.flash = 'Please register a machine to your ID'
return dict(form=form)
After the suggestion I removed the try/ catch and here is the traceback of error. I have wintypes.py under Lib/ctypes. But still then couldnot figure out why there is an import error.
Traceback (most recent call last):
File "gluon/restricted.py", line 224, in restricted
File "C:/web2py/applications/click/controllers/default.py", line 53, in <module>
File "gluon/globals.py", line 393, in <lambda>
File "gluon/tools.py", line 3444, in f
File "C:/web2py/applications/click/controllers/default.py", line 39, in machine
if form.process(onvalidation=machinevalidate).accepted:
File "gluon/html.py", line 2303, in process
File "gluon/html.py", line 2240, in validate
File "gluon/sqlhtml.py", line 1461, in accepts
File "gluon/html.py", line 2141, in accepts
File "gluon/html.py", line 146, in call_as_list
File "C:/web2py/applications/click/controllers/default.py", line 33, in machinevalidate
ssh.connect(host, username=user,password=pwd)
File "C:\Python27\lib\site-packages\paramiko\client.py", line 307, in connect
look_for_keys, gss_auth, gss_kex, gss_deleg_creds, gss_host)
File "C:\Python27\lib\site-packages\paramiko\client.py", line 456, in _auth
self._agent = Agent()
File "C:\Python27\lib\site-packages\paramiko\agent.py", line 332, in __init__
from . import win_pageant
File "gluon/custom_import.py", line 105, in custom_importer
File "C:\Python27\lib\site-packages\paramiko\win_pageant.py", line 25, in <module>
import ctypes.wintypes
File "gluon/custom_import.py", line 105, in custom_importer
ImportError: No module named wintypes
Got the solution...
I was using the compiled version of web2py. When i used the source code, importing of modules were not a head ache any more. Thank you Andrew Magee for giving a heads up...
Related
I am trying to send a file from the master node to minion nodes using a python script but a single error OSError: Failure keeps on coming up.
I tried to code this file to send this file from one local machine to another local machine.
My code:
#! /usr/bin/python
#! /usr/bin/python3
import paramiko
import os
#Defining working connect
def workon(host):
#Making a connection
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #To add the missing host key and auto add policy
ssh_client.connect(hostname = host, username = 'username', password = 'password')
ftp_client = ssh_client.open_sftp()
ftp_client.put("/home/TrialFolder/HelloPython", "/home/")
ftp_client.close()
#stdin, stdout, stderr = ssh_client.exec_command("ls")
#lines = stdout.readlines()
#print(lines)
def main():
hosts = ['192.16.15.32', '192.16.15.33', '192.16.15.34']
threads = []
for h in hosts:
workon(h)
main()
Error:
Traceback (most recent call last):
File "PythonMultipleConnectionUsinhSSH.py", line 28, in <module>
main()
File "PythonMultipleConnectionUsinhSSH.py", line 26, in main
workon(h)
File "PythonMultipleConnectionUsinhSSH.py", line 15, in workon
ftp_client.put("/home/Sahil/HelloPython", "/home/")
File "/usr/local/lib/python3.6/site-packages/paramiko/sftp_client.py", line 759, in put
return self.putfo(fl, remotepath, file_size, callback, confirm)
File "/usr/local/lib/python3.6/site-packages/paramiko/sftp_client.py", line 714, in putfo
with self.file(remotepath, "wb") as fr:
File "/usr/local/lib/python3.6/site-packages/paramiko/sftp_client.py", line 372, in open
t, msg = self._request(CMD_OPEN, filename, imode, attrblock)
File "/usr/local/lib/python3.6/site-packages/paramiko/sftp_client.py", line 813, in _request
return self._read_response(num)
File "/usr/local/lib/python3.6/site-packages/paramiko/sftp_client.py", line 865, in _read_response
self._convert_status(msg)
File "/usr/local/lib/python3.6/site-packages/paramiko/sftp_client.py", line 898, in _convert_status
raise IOError(text)
OSError: Failure
First, you should make sure the target directory /home/ is writable for you. Then you should review documentation for the put method. It says this about the second argument (remotepath):
The destination path on the SFTP server. Note that the filename should be included. Only specifying a directory may result in an error.
Try including the filename in the path, like:
...
ftp_client.put("/home/TrialFolder/HelloPython", "/home/HelloPython")
...
I have a script:
ldapsearch -xLL -h 10.4.113.46 -D 'E900000#corp.privatedev' -W -b 'dc=corp,dc=privatedev' '(cn=lc_proxy_pentest)'
It runs well.
I programme with python to make the same query:
from ldap3 import Server, Connection, ALL
....
server = Server('10.4.113.46', get_info=ALL)
conn = Connection(server, 'uid=E900000#corp.privatedev,cn=lc_proxy_pentest,dc=corp,dc=privatedev', 'PaSsWoRd', auto_bind=True)
The error shows:
Traceback (most recent call last): File "<input>", line 1, in <module>
File "C:\Users\E900000\Python\lib\site-packages\ldap3\core\connection.py", line 278, in __init__
self.bind(read_server_info=True)
File "C:\Users\E900000\Python\lib\site-packages\ldap3\core\connection.py", line 427, in bind
response = self.post_send_single_response(self.send('bindRequest', request, controls))
File "C:\Users\E900000\Python\lib\site-packages\ldap3\strategy\sync.py", line 122, in post_send_single_response
responses, result = self.get_response(message_id)
File "C:\Users\E900000\Python\lib\site-packages\ldap3\strategy\base.py", line 298, in get_response
responses = self._get_response(message_id)
File "C:\Users\E900000\Python\lib\site-packages\ldap3\strategy\sync.py", line 168, in _get_response
dict_response = self.decode_response(ldap_resp)
File "C:\Users\E900000\Python\lib\site-packages\ldap3\strategy\base.py", line 403, in decode_response
result = bind_response_to_dict(component)
File "C:\Users\E900000\Python\lib\site-packages\ldap3\operation\bind.py", line 119, in bind_response_to_dict
'saslCreds': bytes(response['serverSaslCreds']) if response['serverSaslCreds'] is not None else None}
File "C:\Users\E900000\Python\lib\site-packages\pyasn1\type\univ.py", line 984, in __bytes__
return bytes(self._value) TypeError: cannot convert 'NoValue' object to bytes
If I programme just
server = Server('10.4.113.46')
conn = Connection(server)
conn.bind()
The third line brings the same error.
What's wrong?
I doubt that E900000#corp.privatedev corresponds to uid=E900000#corp.privatedev,cn=lc_proxy_pentest,dc=corp,dc=privatedev
I am assuming you are using Active Directory (based on E900000#corp.privatedev).
Try using dsquery to Determine the FDN for the user.
The reason of the failed connection can be refered https://github.com/etingof/pyasn1/issues/52.
But after I modify the library and enable a successful connection, the ldapsearch still doesnât work.
We have written a piece of code in python script using pymongo that connects to mongodb.
username = 'abc'
password = 'xxxxxx'
server = 'dns name of that server'
port = 27017
In program, the code looks like:
import pymongo
from pymongo import MongoClient
client = MongoClient(url, serverSelectionTimeoutMS=300)
database = client.database_name
data_insert = database.collection_name.insert_one({'id': 1, 'name': xyz})
When I tried to do these operations, it raises an error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 1114, in next
if len(self.__data) or self._refresh():
File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 1036, in _refresh
self.__collation))
File "/usr/local/lib/python2.7/dist-packages/pymongo/cursor.py", line 873, in __send_message
**kwargs)
File "/usr/local/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 905, in _send_message_with_response
exhaust)
File "/usr/local/lib/python2.7/dist-packages/pymongo/mongo_client.py", line 916, in _reset_on_error
return func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/pymongo/server.py", line 99, in send_message_with_response
with self.get_socket(all_credentials, exhaust) as sock_info:
File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()
File "/usr/local/lib/python2.7/dist-packages/pymongo/server.py", line 168, in get_socket
with self.pool.get_socket(all_credentials, checkout) as sock_info:
File "/usr/lib/python2.7/contextlib.py", line 17, in __enter__
return self.gen.next()
File "/usr/local/lib/python2.7/dist-packages/pymongo/pool.py", line 792, in get_socket
sock_info.check_auth(all_credentials)
File "/usr/local/lib/python2.7/dist-packages/pymongo/pool.py", line 512, in check_auth
auth.authenticate(credentials, self)
File "/usr/local/lib/python2.7/dist-packages/pymongo/auth.py", line 470, in authenticate
auth_func(credentials, sock_info)
File "/usr/local/lib/python2.7/dist-packages/pymongo/auth.py", line 450, in _authenticate_default
return _authenticate_scram_sha1(credentials, sock_info)
File "/usr/local/lib/python2.7/dist-packages/pymongo/auth.py", line 201, in _authenticate_scram_sha1
res = sock_info.command(source, cmd)
File "/usr/local/lib/python2.7/dist-packages/pymongo/pool.py", line 419, in command
collation=collation)
File "/usr/local/lib/python2.7/dist-packages/pymongo/network.py", line 116, in command
parse_write_concern_error=parse_write_concern_error)
File "/usr/local/lib/python2.7/dist-packages/pymongo/helpers.py", line 210, in _check_command_response
raise OperationFailure(msg % errmsg, code, response)
pymongo.errors.OperationFailure: Authentication failed.
In MongoDB, while performing queries we are getting the responses normally, without raising any errors.
Because the other answers to your question didn't work for me, I'm going to copy and paste my answer from a similar question.
If you've tried the above answers and you're still getting an error:
pymongo.errors.OperationFailure: Authentication failed.
There's a good chance you need to add ?authSource=admin to the end of your uri.
Here's a working solution that I'm using with MongoDB server version 4.2.6 and MongoDB shell version v3.6.9.
from pymongo import MongoClient
# Replace these with your server details
MONGO_HOST = "XX.XXX.XXX.XXX"
MONGO_PORT = "27017"
MONGO_DB = "database"
MONGO_USER = "admin"
MONGO_PASS = "pass"
uri = "mongodb://{}:{}#{}:{}/{}?authSource=admin".format(MONGO_USER, MONGO_PASS, MONGO_HOST, MONGO_PORT, MONGO_DB)
client = MongoClient(uri)
Similar fix for command line is adding --authenticationDatabase admin
Well, I have been stuck with the same error for almost 3-4 hours. I came across solution with the following steps:
from your shell connect to MongoDB by typing: mongo
afterwards, create a database: use test_database
Now create a user with the following command with readWrite and dbAdmin privileges.
db.createUser(
{
user: "test_user",
pwd: "testing12345",
roles: [ "readWrite", "dbAdmin" ]
}
);
This will prompt Successfully added user: { "user" : "test_user", "roles" : [ "readWrite", "dbAdmin" ] }
you can check by typing: show users.
It will also show you DB name you created before in the json.
now you should be able to insert data to your database:
client = MongoClient("mongodb://test_user:myuser123#localhost:27017/test_database")
db = client.test_database
data = {"initial_test":"testing"}
db["my_collection"].insert_one(data).inserted_id
I ran into this error, and my problem was with the password.
I had what I believe to be a special character in the Master account. Changing the password to be only alphanumeric fixed it for me.
Code snippet
client = pymongo.MongoClient(
'mongodb://username:alphaNumericPassword#localhost:27017/?ssl=true&ssl_ca_certs=rds-combined-ca-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'
)
# Specify the database to be used
db = client['prod-db']
I am running Neo4j 2.2.1 in ubuntu Amazon EC2 instance. When I am trying to connect through python using py2neo-2.0.7, I am getting following error :
py2neo.packages.httpstream.http.SocketError: Operation not permitted
I am able to access the web-interface through http://52.10.**.***:7474/browser/
CODE :-
from py2neo import Graph, watch, Node, Relationship
url_graph_conn = "https://neo4j:password#52.10.**.***:7474/db/data/"
print url_graph_conn
my_conn = Graph(url_graph_conn)
babynames = my_conn.find("BabyName")
for babyname in babynames:
print 2
Error message :-
https://neo4j:password#52.10.**.***:7474/db/data/
Traceback (most recent call last):
File "C:\Users\rharoon002\eclipse_workspace\peace\peace\core\graphconnection.py", line 39, in <module>
for babyname in babynames:
File "C:\Python27\lib\site-packages\py2neo\core.py", line 770, in find
response = self.cypher.post(statement, parameters)
File "C:\Python27\lib\site-packages\py2neo\core.py", line 667, in cypher
metadata = self.resource.metadata
File "C:\Python27\lib\site-packages\py2neo\core.py", line 213, in metadata
self.get()
File "C:\Python27\lib\site-packages\py2neo\core.py", line 258, in get
response = self.__base.get(headers=headers, redirect_limit=redirect_limit, **kwargs)
File "C:\Python27\lib\site-packages\py2neo\packages\httpstream\http.py", line 966, in get
return self.__get_or_head("GET", if_modified_since, headers, redirect_limit, **kwargs)
File "C:\Python27\lib\site-packages\py2neo\packages\httpstream\http.py", line 943, in __get_or_head
return rq.submit(redirect_limit=redirect_limit, **kwargs)
File "C:\Python27\lib\site-packages\py2neo\packages\httpstream\http.py", line 433, in submit
http, rs = submit(self.method, uri, self.body, self.headers)
File "C:\Python27\lib\site-packages\py2neo\packages\httpstream\http.py", line 362, in submit
raise SocketError(code, description, host_port=uri.host_port)
py2neo.packages.httpstream.http.SocketError: Operation not permitted
You are trying to access neo4j via https on the standard port for http (7474):
url_graph_conn = "https://neo4j:password#52.10.**.***:7474/db/data/"
The standard port for a https connection is 7473. Try:
url_graph_conn = "https://neo4j:password#52.10.**.***:7473/db/data/"
And make sure you can access the web interface via https:
https://52.10.**.***:7473/browser/
You can change/see the port settings in your neo4j-server.properties file.
Ugh, I have tried as many ways is I have been able to find online thus far, but to no avail. My primary objective is to send email from a django based web application on a private LAN. I don't care how it happens...smtp or win32com and outlook...anything, as long is it works.
Using django default settings and this code in a django shell:
from django.core.mail import send_mail
send_mail('subject','message','myemail#email.com',['myemail#email.com'])
I get this error:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python27_32\lib\site-packages\django\core\mail\__init__.py", line 50, in send_mail
connection=connection).send()
File "C:\Python27_32\lib\site-packages\django\core\mail\message.py", line 274, in send
return self.get_connection(fail_silently).send_messages([self])
File "C:\Python27_32\lib\site-packages\django\core\mail\backends\smtp.py", line 87, in send_messages
new_conn_created = self.open()
File "C:\Python27_32\lib\site-packages\django\core\mail\backends\smtp.py", line 48, in open
local_hostname=DNS_NAME.get_fqdn())
File "C:\Python27_32\lib\smtplib.py", line 250, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python27_32\lib\smtplib.py", line 311, in connect
(code, msg) = self.getreply()
File "C:\Python27_32\lib\smtplib.py", line 359, in getreply
+ str(e))
SMTPServerDisconected: Connection unexpectedly closed: [Errno 10057] A request to send or
receive data was disallowed because the socket is not connected and (when sending on a
datagram socket using a sendto call) no address was supplied
After digging into the code, I inserted a print statement in smtplib showing the address as ('localhost', 25). So I don't know why it says no address was supplied. That's when I discovered django-smtp-ssl.py and after installing added the following to my settings:
EMAIL_USE_TLS = True #also tried 1
EMAIL_BACKEND = 'django_smtp_ssl.SSLEmailBackend'
EMAIL_HOST = 'localhost'
EMAIL_HOST_USER = 'myemail#email.com'
EMAIL_HOST_PASSWORD = 'mypassword'
EMAIL_PORT = 465
Then executing the same code, I now get:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Python27_32\lib\site-packages\django\core\mail\__init__.py", line 50, in send_mail
connection=connection).send()
File "C:\Python27_32\lib\site-packages\django\core\mail\message.py", line 274, in send
return self.get_connection(fail_silently).send_messages([self])
File "C:\Python27_32\lib\site-packages\django\core\mail\backends\smtp.py", line 87, in send_messages
new_conn_created = self.open()
File "C:\Python27_32\lib\site-packages\django_smtp_ssl.py", line 12, in open
local_hostname=DNS_NAME.getfqdn())
File "C:\Python27_32\lib\smtplib.py", line 777, in __init__
SMTP.__init__(self, host, port, local_hostname, timeout)
File "C:\Python27_32\lib\smtplib.py", line 250, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python27_32\lib\smtplib.py", line 311, in connect
(code, msg) = self.getreply()
File "C:\Python27_32\lib\smtplib.py", line 355, in getreply
line = self.file.readline()
File "C:\Python27_32\lib\smtplib.py", line 186, in readline
chr = self.sslobj.read(1)
File "C:\Python27_32\lib\ssl.py", line 160, in read
return self._sslobj.read(len)
AttributeError: 'NoneType' object has no attribute 'read'
I have additionally tried sending mail via Outlook and win32com in a production environment using Apache. I have received a couple different exceptions trying this, such as: 'Server execution failed and 'Call was rejected by callee'. Although it works in a django shell (of course).
Has anyone seen these any of these errors and found resolution? Thank you for any help!
And it's the workaround, nothing short of shoddy, but it'll get the job done until a better solution presents itself.
First I created a custom command that can be called from manage.py as it is not executed from the Apache server (which further tells me that the system does not recognize Apache as a valid user for automatic email generation, certainly there's a way to tell the system "it's okay").
Following that, I created a task in Windows Task Scheduler to run every 30 min (which will suffice for the objective). Action:
Start a program C:\python27_32\python.exe C:\www\myproject\manage.py send_email
myapp/management/commands/send_email.py
from django.core.management.base import BaseCommand
from myapp.util.gen_email import AutoEmail #custom code to generate email via win32com
from myapp.models import MyModel
class Command(BaseCommand):
def __init__(self, *args, **kwargs):
super(Command, self).__init__(*args, **kwargs)
items = MyModel.objects.filter(status__in=['status_a','status_b'])
if items:
self.send_proc_email()
def send_proc_email(self):
subject = 'There are new items to process'
to = 'someemail#email.com'
message = ''
email = AutoEmail(subject, message, to)
def handle(self, *args, **kwargs):
pass
Far from optimal, I know, but hey if it works...