Are my telnetlib imports wrong? - python

Been having an issue with this code:
from telnetlib import Telnet
class doTelnet:
def login(self):
# Configure login variables for input
self.user = self.user.encode('ascii') + b'\n'
self.password = self.password.encode('ascii') + b'\n'
self.terminal_type = self.terminal_type.encode('ascii') + b'\n'
# Do login
# TODO Add functionality for user control of expected login prompt (some servers send 'Username: ', I'm sure theres other options)
self.telnet.read_until('login: ')
self.telnet.write(self.user)
self.telnet.read_until('Password: ')
try:
self.telnet.write(self.password)
print('[*]\tSuccessfully authenticated to {0}:{1}'.format(self.host, self.port))
self.login_status = 1
except Exception as self.e:
print('[!]\tError authenticating to {0}:{1}\n{2}'.format(self.host, self.port, self.e)
# Set terminal type
self.telnet.write(self.terminal_type)
It consistently fails on the "self.telnet.write" section, which I can't understand why that might be. Anyone a wizard?
File "C:\Users\user\Downloads\CiscoIOSSNMPToolkit\doTelnet.py", line 45
self.telnet.write(self.terminal_type)
^
SyntaxError: invalid syntax
Is the error.
https://github.com/GarnetSunset/CiscoIOSSNMPToolkit/blob/master/doTelnet.py

You are missing a parenthesis at the end of your print statement in the exception block which is why you are throwing your current syntax error.

Related

i am gettin an error "[Errno 5] Input/output error" while running an api on django

Django API Code:
def post(self,request)-> JsonResponse:
try:
self.email = request.data['email']
self.mobile = request.data['mobile']
self.password = request.data['password']
except Exception as e:
return JsonResponse(create_failure('400',f"invalid payload {e}","fail"))
try:
res = {}
jwt_token = ''
if self.email:
password = Customer.objects.get(email=self.email).password
username = Customer.objects.get(email=self.email).username
print(password)
if check_password(self.password,password) :
jwt_token = make_jwt_token({'username':username})
else:
return JsonResponse(create_failure('500',f"Invalid password","fail"))
elif self.mobile:
password = Customer.objects.get(mobile=self.mobile).password
username = Customer.objects.get(mobile=self.mobile).username
if check_password( password,self.password) :
jwt_token = make_jwt_token({'username':username})
else:
return JsonResponse(create_failure('500',f"Invalid password","fail"))
res['token'] = jwt_token
except Exception as e:
return JsonResponse(create_failure('400',f"error in verifying the password {e}","fail"))
return JsonResponse(create_success('User Verified',res))
Error while running it on the postman
{
"StatusCode": "400",
"Message": "error in verifying the password [Errno 5] Input/output error",
"ReplyCode": "fail",
"Data": []
}
Above code is working fine on the local machine, but it creates this error when I deploy it to the server. I am using cpanel for the hosting which uses CentOS
Resolved I just had to remove the print from the code.
This might happen if your server has nowhere to put the print statements.
For example, I was running a server in one terminal window, then somehow the window got closed but the server was still running. There are 2 options, depending on your situation:
Kill the process. Start a new server: sudo kill -9 $(sudo lsof -t -i:8000). (or search "find port and kill process [YOUR_OS]" to find OS-specific information. More details
Pipe your command output: python MY_SCRIPT.py >/dev/null More details

Does celery worker run differently?

I have a block of code which runs fine in my python application. When the celery worker runs this code, it fails to do so. Here is the code block:
def send_case_complete_email(owner_name, case_name, email):
try:
with open("utility/email/buildCompleteEmail.txt", 'rb') as email_file:
text = email_file.read().decode("utf-8")
text = text.replace("<owner>", owner_name).replace("<caseName>", case_name)
msg = MIMEText(text)
msg['Subject'] = "Case \'" + case_name + "\' is ready"
msg['From'] = config_access.app_configs['email']['from']
msg['To'] = email
server = smtplib.SMTP(config_access.app_configs['email']['host'])
if config_access.app_configs['email']['tls']:
server.starttls()
server.login(config_access.app_configs['email']['user'], config_access.app_configs['email']['password'])
server.sendmail(config_access.app_configs['email']['from'], email, msg.as_string())
print("Case completion email sent to " + email)
except Exception as e:
print(e)
With the error from the celery worker:
[2017-06-02 15:07:19,031: WARNING/PoolWorker-1] (500, b"5.3.3 Unrecognized command 'bm8ucmVwbHlAcGx1cmlsb2NrLmNvbQ==' [BN3PR03CA0080.namprd03.prod.outlook.com]")
Why would this happen?
The message you have posted is just a warning message. Are you sure the error here is from this piece of code. You can use logging here. Python Logging
Or if you are using Django then,Django Logging
. You can use logger.exception to get the full stacktrace. This shall tell you where exactly is the error coming from.

python - how register user with xmpp

I'm trying to register a new user, but not work. I get the following error:
AttributeError: Client instance has no attribute 'SendAndWaitForResponse'
this is my code:
import xmpp, sys
usuario = 'test1#localhost'
password = 'mypassword'
jid = xmpp.JID(usuario)
cli = xmpp.Client(jid.getDomain(), debug=[])
cli.connect()
if xmpp.features.register(cli,jid.getDomain(),{'username':jid.getNode(),'password':password}):
sys.stderr.write('Success\n')
sys.exit(0)
else:
sys.stderr.write('Error\n')
sys.exit(1)
i use linux
I also met this issue. When you remove "debug=[]" from the connect param list. You can get the debug output. In my side, this issue is because the server can not be reached.

Python: how to setup python-ldap to ignore referrals?

how can I avoid getting (undocumented) exception in following code?
import ldap
import ldap.sasl
connection = ldap.initialize('ldaps://server:636', trace_level=0)
connection.set_option(ldap.OPT_REFERRALS, 0)
connection.protocol_version = 3
sasl_auth = ldap.sasl.external()
connection.sasl_interactive_bind_s('', sasl_auth)
baseDN = 'ou=org.com,ou=xx,dc=xxx,dc=com'
filter = 'objectclass=*'
try:
result = connection.search_s(baseDN, ldap.SCOPE_SUBTREE, filter)
except ldap.REFERRAL, e:
print "referral"
except ldap.LDAPError, e:
print "Ldaperror"
It happens that baseDN given in example is a referral. When I run this code I get referral as output.
What would I want is that python-ldap just would skip it or ignore without throwing strange exception (I cannot find documentation about it)?
(this may help or not) The problem happened when I was searching baseDN upper in a tree. When I was searching 'ou=xx,dc=xxx,dc=com' it started to freeze on my production env when on development env everything works great. When I started to looking at it I found that it freezing on referral branches. How can I tell python-ldap to ignore referrals? Code above does not work as I want.
This is a working example, see if it helps.
def ldap_initialize(remote, port, user, password, use_ssl=False, timeout=None):
prefix = 'ldap'
if use_ssl is True:
prefix = 'ldaps'
# ask ldap to ignore certificate errors
ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
if timeout:
ldap.set_option(ldap.OPT_NETWORK_TIMEOUT, timeout)
ldap.set_option(ldap.OPT_REFERRALS, ldap.OPT_OFF)
server = prefix + '://' + remote + ':' + '%s' % port
l = ldap.initialize(server)
l.simple_bind_s(user, password)

Verifying Authentication to a Telnet Session in Python

I am trying to telnet into a Cisco Switch and run a couple of commands on it. I am able to check if the host doesn't exist, not sure how to check if the username or password is correct. This is what I got so far(This is part of my class)
def login(self):
if self.user_name and self.password:
try:
self.connection=telnetlib.Telnet(self.telnet_host)
try:
self.connection.read_until('sername:',1)
self.connection.write(self.user_name+'\r\n')
self.connection.read_until('assword:',1)
self.connection.write(self.password+'\r\n')
self.connection.read_until(self.prompt,1)
print "Connected"
self.loggedON=True
except EOFError:
print "Authentication to "+ self.telnet_host+" failed.\n"
return
except:
print "Can't connect to "+self.telnet_host+"\n"
return
else:
if not self.user_name:
self.user_name=raw_input("Username: ")
self.login()
else:
self.password=raw_input("Password: ")
self.login()
It will still say it is connected even if the wrong password or username.
You could also try Exscript:
from Exscript.util.start import quickstart
def do_something(conn):
conn.autoinit()
conn.execute('show version')
quickstart('telnet://localhost', do_something)
The quickstart() function asks the user for username and password (use start() if that is not what you want). Login failure (and other errors) are handeled automatically. You may also want to look at Exscript.util.start.
First of all, you shouldn't have a blanket try/except block like that. Catch exceptions more narrowly. Also, as others have commented, you might consider SNMP.
Having said that, if you push ahead with Telnet, you might as well just reuse someone else's code. I found this for example with a simple Google search.

Categories

Resources