Paramiko start_server Not Working - python-2.7

I created a program for accessing a server via Paramiko and sockets.
#make imports
from socket import *
from datetime import datetime
from pickle import load, dump
from Crypto.Hash import SHA256
from subprocess import check_output as exeCMD
from sqlite3 import connect as SQLconnect
import paramiko, sys, threading, os
#get password from file
pasword = load(open("usrData/pswd.txt", "rb"))
#class for initiating server connection with client
class Server(paramiko.ServerInterface):
#initialize object
def __init__(self):
self.event = threading.Event()
#check password for user entry
def check_auth_password(self, username, password):
#where the error is
givenpswdHash = SHA256.new(password)
print(givenpswdHash.hexdigest())
if (username in unameList) and (givenpswdHash.hexdigest() == pasword):
return paramiko.AUTH_SUCCESSFUL
return paramiko.AUTH_FAILED
#what to execute in command line
def terminal(hostIP, hostPort, hostKeyPath, hostKeyPswd):
#create sockets before this etc...
#create server instance
server = Server()
#get server onto session
#where we call out server function
session.start_server(server=server)
#continue talking to client
When I launch the server, and get a client to connect to it, I get this error :
No handlers could be found for logger "paramiko.transport"
Traceback (most recent call last):
File "./terminalServer.py", line 212, in <module>
main()
File "./terminalServer.py", line 209, in main
terminal(ip, port, keyPath, keyPswd)
File "./terminalServer.py", line 142, in terminal
session.start_server(server=server)
File "/usr/local/lib/python2.7/dist-packages/paramiko/transport.py", line 471, in start_server
raise e
ValueError: CTR mode needs counter parameter, not IV
It has something to do with the Crypto I added for password authentication. If anyone knows howto solve this issue, please
leave a comment. Thank you in advance.

All I had to do is replace all the alpha versions of pycrypto with the stable version. The current stable version (Sept. 1st 2015) for pycrypto is 2.6.1 and for paramiko it's 1.14.2.

Related

Problems using Gmail with Python 2.7

New guy here....
I have searched all over this site and tried multiple variations on my code, but I am still receiving a login error when I attempt to send an email through Gmail using Python 2.7. I have enabled the "less secure apps" thing on my Gmail account and I am still receiving this error:
Traceback (most recent call last):
File "T:\OC\Projects\Aquadat\Scripting\RawArcPyScripts\sendEmailWithAttachment_Aquadat.py", line 28, in
svr.login(sender,pwd)
File "C:\Python27\ArcGIS10.3\lib\smtplib.py", line 615, in login
raise SMTPAuthenticationError(code, resp)
SMTPAuthenticationError: (534, '5.7.14 Please log in via your web browser and\n5.7.14 then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 z33sm11383168qta.48 - gsmtp')
Here is the problematic code. I grabbed a lot of it off of this site and tried to adapt it to my application. Any help would be most appreciated.
import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
svr = smtplib.SMTP_SSL('smtp.gmail.com',465)
svr.ehlo()
svr.starttls()
svr.ehlo()
sender = 'my_name'
pwd = 'my_pwd'
svr.login(sender,pwd)
rcvr = sender #Change to arcpy.GetParameterAsText(x) when working
def send_mail(send_from,send_to,subject,text,files,
server):
assert isinstance(send_to, list)
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach(MIMEText(text))
for f in files or []:
with open(f, "rb") as fil:
part = MIMEApplication(
fil.read(),
Name=basename(f)
)
part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
msg.attach(part)
smtp = smtplib.SMTP_SSL(server)
smtp.sendmail(send_from, send_to, msg.as_string())
smtp.close()

How to enable HTTPS on Python 2.7 web.py?

I am using Python 2.7.5 with web.py (v0.38) installed on a Linux machine. Below is my code in the most basic form (webhooks.py)
#!/usr/bin/python
import web
urls = ('/.*','WebHooks')
app = web.application(urls, globals())
class WebHooks:
def POST(self):
raw_payload = web.data()
json_encode = json.loads(raw_payload)
if __name__ == '__main__':
app.run()
I execute python webhooks.py 9999
It opens up a local port http://0.0.0.0:9999/
My issue: I have read the documentation located here and I am stumped. Would somebody be able to help me open an HTTPS URL? https://0.0.0.0:9999/
What I have tried
Add the following into my code for testing:
response = app.request("/.*", https=True)
I would get an error: AttributeError: 'module' object has no attribute 'request'
I solved that issue with pip install urllib.py and then adding import urllib to the top of my code but I ended up with a bunch of errors:
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/web/application.py", line 239, in process
return self.handle()
File "/usr/lib/python2.7/site-packages/web/application.py", line 230, in handle
return self._delegate(fn, self.fvars, args)
File "/usr/lib/python2.7/site-packages/web/application.py", line 461, in _delegate
cls = fvars[f]
KeyError: u'WebHooks'
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/web/application.py", line 239, in process
return self.handle()
File "/usr/lib/python2.7/site-packages/web/application.py", line 229, in handle
fn, args = self._match(self.mapping, web.ctx.path)
AttributeError: 'ThreadedDict' object has no attribute 'path'
You're headed down the wrong path, but not to worry. The response = app.request("/.*", https=True) bit you're trying has to do with your application making an https request, rather then handling an https request.
See http://webpy.org/cookbook/ssl
Internally, web.py uses a CherryPyWSGIServer. To handle https, you need to provide the server with an ssl_certificate and ssl_key. Very simply, add a few lines before you invoke app.run():
if __name__ == '__main__':
from web.wsgiserver import CherryPyWSGIServer
ssl_cert = '/path-to-cert.crt'
ssl_key = '/path-to-cert.key'
CherryPyWSGIServer.ssl_certificate = ssl_cert
CherryPyWSGIServer.ssl_private_key = ssl_key
app.run()
Of course, in a full solution, you'll probably want apache or nginx to handle the https portion, but the above is perfect for small applications and testing.

Why does Flask + SocketIO + Gevent give me SSL EOF errors?

This is a simple code snippet that consistently repeats the issue I'm having. I'm using Python 2.7.12, Flask 0.11, Flask-SocketIO 2.7.1, and gevent 1.1.2. I understand that this is probably an issue better brought up to the responsible package's mailing list, but I can't figure out which one is responsible. However, I'm pretty sure it is a problem with gevent because that's what raises the exception.
from flask import Flask
from flask_socketio import SocketIO
from gevent import monkey
monkey.patch_all()
import ssl
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
socketio = SocketIO(app, async_mode='gevent')
#app.route('/')
def index():
return "Hello World!"
#socketio.on('connect')
def handle_connect_event():
print('Client connected')
if __name__ == '__main__':
socketio.run(app, host='127.0.0.1', port=8443,
certfile='ssl/server/server.cer', keyfile='ssl/server/server.key',
ca_certs='ssl/server/ca.cer', cert_reqs=ssl.CERT_REQUIRED,
ssl_version=ssl.PROTOCOL_TLSv1_2)
And here is the error I get when the client connects:
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/gevent/greenlet.py", line 534, in
result = self._run(*self.args, **self.kwargs)
File "/usr/lib/python2.7/site-packages/gevent/baseserver.py", line 25, in
return handle(*args_tuple)
File "/usr/lib/python2.7/site-packages/gevent/server.py", line 126, in wr
ssl_socket = self.wrap_socket(client_socket, **self.ssl_args)
File "/usr/lib/python2.7/site-packages/gevent/_sslgte279.py", line 691, i
ciphers=ciphers)
File "/usr/lib/python2.7/site-packages/gevent/_sslgte279.py", line 271, i
raise x
SSLEOFError: EOF occurred in violation of protocol (_ssl.c:590)
<Greenlet at 0x7fdd593c94b0: _handle_and_close_when_done(<bound method WSGInd method WSGIServer.do_close of <WSGIServer a, (<socket at 0x7fdd590f4410 SSLEOFError
My system also has OpenSSL version 1.0.2.j if that helps. Any thoughts would be appreciated!
Use patch_all on top of the code. Even before flask and socketio import.
from gevent import monkey
monkey.patch_all()
from flask import Flask
from flask_socketio import SocketIO
import ssl

django tornado getting 403 error on start

Following a tutorial I have written a management command to start tornado and it looks like:
import signal
import time
import tornado.httpserver
import tornado.ioloop
from django.core.management.base import BaseCommand, CommandError
from privatemessages.tornadoapp import application
class Command(BaseCommand):
args = '[port_number]'
help = 'Starts the Tornado application for message handling.'
def sig_handler(self, sig, frame):
"""Catch signal and init callback"""
tornado.ioloop.IOLoop.instance().add_callback(self.shutdown)
def shutdown(self):
"""Stop server and add callback to stop i/o loop"""
self.http_server.stop()
io_loop = tornado.ioloop.IOLoop.instance()
io_loop.add_timeout(time.time() + 2, io_loop.stop)
def handle(self, *args, **options):
if len(args) == 1:
try:
port = int(args[0])
except ValueError:
raise CommandError('Invalid port number specified')
else:
port = 8888
self.http_server = tornado.httpserver.HTTPServer(application)
self.http_server.listen(port, address="127.0.0.1")
# Init signals handler
signal.signal(signal.SIGTERM, self.sig_handler)
# This will also catch KeyboardInterrupt exception
signal.signal(signal.SIGINT, self.sig_handler)
print "start"
tornado.ioloop.IOLoop.instance().start()
print "end"
Here I when I run this management command I get tornado tornado.access:403 GET /2/ (127.0.0.1) 1.92ms error
For test purpose I have printed "start" and "end". I guess when this command is executed successfully "end" should be printed.
Here only "start" is printed not "end". I guess there is something error on tornado.ioloop.IOLoop.instance().start() but I dont know what it is.
Can anyone guide me what is wrong in here ?
You forgot to put self.http_server.start() before starting the ioloop.
...
self.http_server = tornado.httpserver.HTTPServer(application)
self.http_server.listen(port, address="127.0.0.1")
self.http_server.start()
...
Update
Along with the httpserver start missing, are you using this library?
Your management command is exactly this one
Their tutorial is in russian and honestly, I don't read russian.
Update2:
What is see in their code, is that the url /(?P<thread_id>\d+)/ is a websocket handler:
application = tornado.web.Application([
(r"/", MainHandler),
(r'/(?P<thread_id>\d+)/', MessagesHandler),
])
...
class MessagesHandler(tornado.websocket.WebSocketHandler):
...
But the error you posted seems like something tried to access it in http via GET.
Honestly, without a debugger and the same environment, I can't figure out the issue.

google admin sdk directory api 403 python

i want to use admin sdk directory api to create eamil account of users.
i am using google-api-python-client-1.2 library.
in folder /samples/service_account/tasks.py works for me.
but when i chance that file to list users from admin directory api it doesn't works and throws errors.
below is the code i am using.
import httplib2
import pprint
import sys
import inspect
from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
def main(argv):
f = file('my-privatekey.p12', 'rb')
key = f.read()
f.close()
credentials = SignedJwtAssertionCredentials(
'my#developer.gserviceaccount.com',
key,
scope=['https://www.googleapis.com/auth/admin.directory.user', 'https://www.googleapis.com/auth/admin.directory.user.readonly'])
http = httplib2.Http()
http = credentials.authorize(http)
service = build("admin", "directory_v1", http)
list_of_apis = service.users().list(domain='mydomain.com').execute(http=http)
pprint.pprint(list_of_apis)
if __name__ == '__main__':
main(sys.argv)
when i run the above code i get below errors.
$python tasks.py
No handlers could be found for logger "oauth2client.util"
Traceback (most recent call last):
File "tasks.py", line 77, in <module>
main(sys.argv)
File "tasks.py", line 66, in main
list_of_apis = service.users().list(domain='messycoders.com').execute(http=http)
File "/usr/local/lib/python2.7/dist-packages/oauth2client/util.py", line 132, in positional_wrapper
return wrapped(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/apiclient/http.py", line 723, in execute
raise HttpError(resp, content, uri=self.uri) apiclient.errors.HttpError: <HttpError 403 when requesting https://www.googleapis.com/admin/directory/v1/users?domain=messycoders.com&alt=json returned "Not Authorized to access this resource/api">
Try:
credentials = SignedJwtAssertionCredentials(
'my#developer.gserviceaccount.com',
key,
sub='superadmin#mydomain.com',
scope=['https://www.googleapis.com/auth/admin.directory.user',])
You don't need both scopes, use readonly if you're doing read operations only, use the above if you're doing read and write.
sub= defines which Google Apps account the service account should impersonate to perform the directory operations, it's necessary and the account needs to have the right permissions.
Lastly, be sure that you've granted the service account's client_id access to the directory scopes you need in the Control Panel. The steps to do this are listed in the Drive documentation, just sub in the correct scope(s) for Admin Directory.