SSH into switch using paramiko module - python-2.7

I am able to open a ssh session into switch using paramiko. Able to enter the commands and gets it respective output.
My question is that I want to enter many command into the switch simultaneously. But before entering new command, wanted to know that previous command is successfully entered into the switch.For example
switch>enable
switch#
switch#config t
switch(config)
Enter the 2nd command, until i see # sign and 3rd command untill i see config.
Following is the code i am using
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('ip-address',username='username', password='password')
list =['enable','config t']
command = '\n'.join(list)
#for i in range(len(list)):
print command
stdin,stdout,stderr = ssh.exec_command(command)
print(stdout.read())

use interactive invoke shell
##invoke interactive shell chan = ssh.invoke_shell(); chan.send(command + '\n') ;
while not chan.recv_ready(): print 'waiting for challenge' time.sleep(1) ;
resp = chan.recv(1024) ; print resp

Related

Python2 - proc.stdin not passing password correctly to easyrsa

The idea to revoke users from the VPN, with an easyrsa command. Manually this works. However, when I perform this action with Python it fails.
The easyrsa command asks for 2 arguments, the first one is to continue, the second one is a password.
My current code is:
#!/usr/local/bin/python2.7
import time
from subprocess import Popen, PIPE
pass_phrase = "damn_good_password"
proc = Popen(['/usr/local/share/easy-rsa/easyrsa', 'revoke', 'user#somewhere.com'], stdin=PIPE)
time.sleep(1)
proc.stdin.write('yes\n')
proc.stdin.flush()
time.sleep(1)
proc.stdin.write(pass_phrase + "\n")
proc.stdin.flush()
The script outputs the following:
user#vpn $ sudo ./test.py
Type the word 'yes' to continue, or any other input to abort.
Continue with revocation: Using configuration from /usr/local/share/easy-rsa/openssl-1.0.cnf
Enter pass phrase for /etc/openvpn/pki/private/ca.key:
user#vpn $
User interface error
unable to load CA private key
5283368706004:error:0907B068:PEM routines:PEM_READ_BIO_PRIVATEKEY:bad password read:pem_pkey.c:117:
I think Python incorrectly passes the password to the process. When performing these steps manually and copying the password, it works.
Can someone point me in the right direction to fix this?

How to send escape sequences over ssh connection in Paramiko for example ESC+E.Can someone send a link to a list

I am trying to send ESC+E and other combinations with ESC key over ssh using Paramiko in Python but unable to find a list which can guide.
Can someone please help
import paramiko
import time
import os
import sys
time.sleep(1)
ip = "x"
host = ip
username = "aaa"
password = "ffffffffff"
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,username=username,password=password,port=5022)
channel=ssh.invoke_shell()
time.sleep(2)
channel.send("W2KTT\n")
time.sleep(5)
output=channel.recv(9999)
print output
channel.send("display alarms \n")
time.sleep(5)
output=channel.recv(9999)
print output
time.sleep(1)
channel.send("\t \t \t n \x1B3 ") #need to send ESC+E key combination here

Python script executable crashes immediately

I work with python 2.7 and I have a python script that ssh to remote servers and it works fine using python command from cmd but when I convert this script to executable file using py2exe or cx_freeze or Pyinstaller and try to run it, the window open and close immediately like if the program crashes. I tried another simple scripts like print function or some math function the executable files work fine so any one could help what would be the reason?
Thanks
Here is my code:
import sys
import paramiko
import getpass
def print_menu():
print 30 * "-", "MENU", 30 * "-"
print "1. LAB1"
print "2. LAB2"
print "3. LAB3"
print "4. Exit"
print 67 * "-"
def ssh_command(ssh):
while True:
command = raw_input("Enter command or q :")
ssh.invoke_shell()
stdin, stdout, stderr = ssh.exec_command(command)
stdout = stdout.readlines()
if command == "q":
break
for line in stdout:
if "Size" in line:
print "found the string"
break`enter code here`
else:
print "There was no output for this command"
def ssh_connect(host, user, password):
try:
ssh = paramiko.SSHClient()
print('Connecting...')
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=host, username=user, password=password)
ssh_command(ssh)
except Exception as e:
print('Connection Failed')
print(e)
def ssh_close():
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.close()
def credentials(host):
user = raw_input("Username:")
password = getpass.getpass("password for " + user + ":")
ssh_connect(host, user, password)
loop = True
while loop:
print_menu()
choice = input("Enter your choice [1-3]: ")
if choice == 1:
credentials('x.x.x.x')
elif choice == 2:
credentials('x.x.x.x')
elif choice == 3:
credentials('x.x.x.x')
elif choice == 4:
loop = False
print "Closing SSH connection"
print
ssh_close()
else:
raw_input("Wrong option selection. Enter any key to try again..")
You can check the error by running the exe file in command prompt.
This will give you an upper hand.
Especially in cx_freeze you have to mention the dependencies.
I think you are facing some dependency problem.
When you specifiy --debug=all after your pyinstall command when packaging, you will see specific errors when starting your applicataion in the dist folder.
Read here https://pyinstaller.readthedocs.io/en/stable/when-things-go-wrong.html to get more information on debugging specific errors and how to fix them.
you can use the pyinstaller with -F argument to fully package the python interpreter then open windows cmd and run it
pyinstaller -F <your_script>.py
Worry not, my friend! Just add a window.mainloop() call at the end of your program. Then, everything should work properly. I was stumped by the same problem got revelation from your words:
I tried another simple scripts like print function or some math function the executable files work fine
So, I compared both programs side by side and received my answer.
Running pyinstaller with the F flag should solve the problem of immediate close after startup.

socket.gaierror: [Errno -2] Name or service not known No DNS issue

I am trying to learn network scripting via Python. I am trying to extract device names from file "Device_List" and then ssh to the device, executing a command on it and printing the output.
It works fine when I use IP address in the file however it does not if I use a hostname. I tried this on an Ubuntu Trusty as well as Mac OSX.
I get the following error:
FWIP = socket.gethostbyname(name)
socket.gaierror: [Errno -2] Name or service not known
I am able to resolve the hostname on both machines so it is not a DNS issue.
Moreover, if I input the device name from keyboard instead of file, it works fine.
Could you please help me find the issue?
My Code:
import datetime
import paramiko
import socket
import time
import sys
import getpass
with open("Device_List") as dev:
for name in dev:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
Uname = raw_input("Username : ")
Pw = getpass.getpass()
print "Connected to ", name
FWIP = socket.gethostbyname(name)
ssh.connect(FWIP, username=Uname,password=Pw)
remote_conn = ssh.invoke_shell()
remote_conn.send("set cli pager off\n")
sys.stdout.flush()
command = raw_input("Enter Command to run : ")
remote_conn.send(command + "\n")
time.sleep(2)
output = remote_conn.recv(65534)
print output
print "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
print "Moving Onto Next Device..."
print "Device List Over"
When you iterate over lines in a text file, e.g. your
with open("Device_List") as dev:
for name in dev:
the default I/O subsystem always includes the '\n' line ending character. One reason is that this way you can tell when a text file ends without ending the final line.
Get used to using (e.g.) dev.rstrip() when you don't want that.

How to get ping output from cmd shell in python without stop the script

Recently I spent a few hours to find How can I get output while this script running
ping = subprocess.check_output(["start", "cmd.exe", "/k", "ping", "-t", SomeIP], shell=True)
All the answers I've found in the internet proposed to use communicte(), subprocess.call and other unusable commands because all of this command forcing me to stop the script.
Please help me :)
My python is 2.7
Another solution is saving the results of the ping to a file then reading from it...
import subprocess, threading
class Ping(object):
def __init__(self, host):
self.host = host
def ping(self):
subprocess.call("ping %s > ping.txt" % self.host, shell = True)
def getping(self):
pingfile = open("ping.txt", "r")
pingresults = pingfile.read()
return pingresults
def main(host):
ping = Ping(host)
ping.ping()
#startthread(ping.ping) if you want to execute code while pinging.
print("Ping is " + ping.getping())
def startthread(method):
threading.Thread(target = method).start()
main("127.0.0.1")
Basically, I just execute the cmd ping command and in the cmd ping command I used the > ping.txt to save the results to a file. Then you just read from the file and you have the ping details. Notice, you can start a thread if you want to execute ping while executing your own code.