Paramiko SSHClient select an option from menu in shell - paramiko

I'm trying to run some commands on a linux machine using Paramiko.
After one command there is a menu, and I want to type "R" and press Enter.
Here is my code:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy() )
ssh.connect(hostname, port, username, password)
stdin = ssh.exec_command("")
conn = ssh.invoke_shell()
print("Interactive SSH session established")
output = conn.recv(1000)
conn.send("gohome\n")
conn.send("rollout\n")
conn.send("R")
conn.send("\n")
time.sleep(5)
output = str(conn.recv(10000))
print(output.replace("\\r", "").replace("\\n", "\n")[-500:])
This script does not take the "R" and "\n" in, and exits after "rollout\n"
The output shows that the R has not been input.
What can I do here?
Here is the menu after the 'rollout' command:

If anyone has a similar problem, I changed
conn.send("rollout\n")
to
conn.send("source rollout\n")
and that allowed to interact with the menu.

Related

Telnetlib doesn't seem to be passing .write commands

I'm a python noob here just trying to learn a new skill so please be gentle :)
After executing the following script it appears that my script creates a telnet session and I can see the cisco devices banner but is not passing the username/password when prompted.
I've tried changing tn.read_until() and tn.read_very_eager() neither of which is triggering the script to move on to write the desired input. I've also tried forcing the username and password to be input as a byte as well as adding + '\n' to my write functions. I've also used sleep to pass a little extra time to wait for the banner to finish printing out.
tldr: when executing the script I see the username prompt, but can't get further than that.
any assistance here is welcomed.
'''
from time import sleep
import telnetlib
from telnetlib import Telnet
from getpass import getpass
Username = input('please provide your username ')
password = getpass()
# f is the .txt document that lists the IP's we'll be using.
f = open('devicess.txt')
for line in f:
print ('Configuring Device ' + (line))
device = (line)
#open connection to variable
tn = telnetlib.Telnet(device)
#For those devices in the above list, connect and run the below commands
for device in f:
tn.expect('Username: ')
tn.write(Username)
tn.expect('Password: ')
tn.write(password)
tn.write('show ver')
print('connection established to ' + device)
tn.write('logout')
output = tn.read_all()
print(output)
print('script complete')
'''

KeyboardInterrupt handling is extremely slow. Where is the problem?

I'm currently trying to write a script to read a shell via paramiko and, by far, if I prompt a single command it works great.
the problem is that my actual goal is to handle a debug flow and of course I cannot use a timeout because the script should listen without time limitations.
So the other option is to let the user stop the flow with ctrl-c. I added a "try, except" handler like
except (IOError, SystemExit):
raise
except KeyboardInterrupt:
print ("Crtl+C Pressed. Shutting down.")
and it seemed like it wasn't working: nothing happened when pressing ctrl-c. But then I realized that it was just taking forever: after a few minutes the script actually stops and the message appears.
Does anyone know how to handle this problem?
just for the reference here's my code
import paramiko
import time
import re
import socket
import os
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
address = '192.168.1.1'
username = 'admin'
password = ''
ssh.connect(address, port=22, username = username, password = password)
shell = ssh.invoke_shell(height=400)
shell.settimeout(2)
def prompt_console(command = '', channel = shell, timeout = False):
print(channel.recv(9999).decode('utf-8')) #<-- this is for removing the initial prompt from buffer
if timeout == False:
shell.settimeout(3600) #<--increasing the timeout
channel.send(command+'\n')
log = ''
while True:
try:
log += channel.recv(1).decode('utf-8') #<--every loop it loads a char into the "log" variable
if log[-9:] == '--More-- ':
shell.send(" ")
log.replace('--More-- \r \r\t\t','\r\t\t')
if len(re.findall('.*\n',log))>0: #<--it yields every line to python console
yield log
log = ''
except (IOError, SystemExit):
raise
except KeyboardInterrupt:
print ("Crtl+C Pressed. Shutting down.")
I also tried to put the try-except outside the while loop but it didn't work. I also tried many suggestions that I've found on google but they didn't work either: they all stop the script eventually but for all of them it takes 5-10 minutes.

Why no one has answer for java.awt.AWTError: Can't connect to X11 window server using ':0.0' as the

In my local Unix Ubuntu env I keep getting an error as
java.awt.AWTError: Can't connect to X11 window server using ':0.0' as the value of the DISPLAY variable.
I tried all the below options
1)-Djava.awt.headless
2) installed xvbf.
3) export DISPLAY=:0.0
I also gave command line as
./katalon -runMode=console -projectPath="/home/jenktran/Automation/Katalon First Proj/Katalon First Proj.prj" -retry=0 -testSuitePath="Test Suites/TimesheetTestCaseForChrome" -browserType="Chrome (headless)"
./katalon -runMode=console -projectPath="/home/jenktran/Automation/Katalon First Proj/Katalon First Proj.prj" -retry=0 -testSuitePath="Test Suites/TimesheetTestCaseForChrome" -browserType="Chrome (headless)" ---Djava.awt.headless
What else i can do?
Try the command
$xhost +
This will disable the access control and allows any client to connect

R - Rstudio suppress echo getpass

I'm trying to write a getpass function for R that will work with Rstudio. I've tried using the getpass C function (*nix, with Rcpp) as well as using the getpass from python using rPython, and both seem to work in the terminal, but cause the Rstudio prompt to freeze after entering a password and hitting return.
The output from python's get pass is,
/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/getpass.py:83: GetPassWarning: Can not control echo on the terminal.
passwd = fallback_getpass(prompt, stream)
Warning: Password input may be echoed.
and using getpass(const char *prompt); I just get the password prompt that never returns to the R prompt.
As requested some code snippets that work in the terminal but not in R-studio,
library(rPython)
python.exec("import getpass")
pass = python.get("getpass.getpass()")
the Rcpp/inline code,
library(inline)
str = 'std::string pass = (const char *) getpass("Password: ");\n;\n return(wrap(pass));'
testfun = cxxfunction(signature(),body=str,plugin="Rcpp")
testfun()
Note I'm on a mac but it should be the same on other *ix boxes that have getpass().
Any clues?

OptionParser in ipython notebook?

I am enjoying developing inside the ipython notebook, but I am having a problem when I want to write a main() function that reads the command line args (with OptionParser, for example). I want to be able to export the code to a .py file and run it from the command line, but I haven't found a way to have a main() that runs both in the notebook with predefined arguments or from the command line with python and command line args. What is the secret?
In case that is not clear, I would like to do something like this:
if __name__ == '__main__':
# if in the notebook
vals = {'debug':True, 'tag_file': 't.tags'}
options = Object()
for k,v in vals.items():
options.setattr(k,v)
args = 'fname1.txt'
# if running as a command line python script
from optparse import OptionParser
parser = OptionParser()
parser.add_option('-d','--debug',action='store_true',dest='debug')
parser.add_option('-t','--tags',action='store',dest='tag_file')
options,args = parser.parse_args()
You cannot determine that you are in an IPython notebook or a qtconsole, or a simple IPython shell, for the simple reason the 3 can be connected to the same kernel at the same time.
It would be like asking, what color is the current key the user is typing. You could get it by looking the plugged usb devices and look for images on the internet and guess the keyboard color, but nothing guarantees you it will be accurate, nor that it won't change, and user can have multiple keyboard plugged, or even painted keyboard.
It is really the same with the notebook, Even if you determine you are in ZMQKernel, are you speeking to qtconsole or webserver ? Again, you found that you were talking to the webserver, are you talking to JS or Emacs ? And so on and so forth.
The only thing you can do, you can ask the user.
What is reliable, is test wether you are in IPython or not.
If you really but reeaaalllyy want a way, as until now, the notebook is the only thing that can display Javascript. And javascript can execute code in pyton. So you might be able to create something that display JS that send back info to the kernel. And using thread and timer you can say that you were not in a notebook (but you will have a race condition).
Don't worry about the distinction. Just set default values, and unless they are overridden from the command line, use those.
if __name__ == '__main__':
parser = OptionParser()
parser.add_option('-d', '--debug', action='store_true', dest='debug',
default=True)
parser.add_option('-t','--tags',action='store',dest='tag_file',
default='t.tags')
options, args = parser.parse_args()
if not args:
args = ['fname1.txt']

Resources