Run interactive python class within paramiko [duplicate] - python

I'm having a problem with a ShoreTel voice switch, and I'm trying to use Paramiko to jump into it and run a couple commands. What I believe the problem might be, is that the ShoreTel CLI gives different prompts than the standard Linux $. It would look like this:
server1$:stcli
Mitel>gotoshell
CLI> (This is where I need to enter 'hapi_debug=1')
Is Python still expecting that $, or am I missing something else?
I thought it might be a time thing, so I put those time.sleep(1) between commands. Still doesn't seem to be taking.
import paramiko
import time
keyfile = "****"
User = "***"
ip = "****"
command1 = "stcli"
command2 = "gotoshell"
command4 = "hapi_debug=1"
ssh = paramiko.SSHClient()
print('paramikoing...')
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname = ip, username = User, key_filename = keyfile)
print('giving er a go...')
ssh.invoke_shell()
stdin, stdout, stderr = ssh.exec_command(command1)
time.sleep(1)
stdin, stdout, stderr = ssh.exec_command(command2)
time.sleep(1)
stdin, stdout, stderr = ssh.exec_command(command4)
time.sleep(1)
print(stdout.read())
ssh.close()
print("complete")
What I would expect from the successful execution of this code, would be for the hapi_debug level to be 1. Which means that when I SSH into the thing, I would see those HAPI debugs populating. When I do, I do not see those debugs.

I assume that the gotoshell and hapi_debug=1 are not top-level commands, but subcommands of the stcli. In other words, the stcli is kind of a shell.
In that case, you need to write the commands that you want to execute in the subshell to its stdin:
stdin, stdout, stderr = ssh.exec_command('stcli')
stdin.write('gotoshell\n')
stdin.write('hapi_debug=1\n')
stdin.flush()
If you call stdout.read afterwards, it will wait until the command stcli finishes. What it never does. If you wanted to keep reading the output, you need to send a command that terminates the subshell (typically exit\n).
stdin.write('exit\n')
stdin.flush()
print(stdout.read())

Related

I'm writing a paramiko common method to accept stdin and run command on other node [duplicate]

I'm having a problem with a ShoreTel voice switch, and I'm trying to use Paramiko to jump into it and run a couple commands. What I believe the problem might be, is that the ShoreTel CLI gives different prompts than the standard Linux $. It would look like this:
server1$:stcli
Mitel>gotoshell
CLI> (This is where I need to enter 'hapi_debug=1')
Is Python still expecting that $, or am I missing something else?
I thought it might be a time thing, so I put those time.sleep(1) between commands. Still doesn't seem to be taking.
import paramiko
import time
keyfile = "****"
User = "***"
ip = "****"
command1 = "stcli"
command2 = "gotoshell"
command4 = "hapi_debug=1"
ssh = paramiko.SSHClient()
print('paramikoing...')
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname = ip, username = User, key_filename = keyfile)
print('giving er a go...')
ssh.invoke_shell()
stdin, stdout, stderr = ssh.exec_command(command1)
time.sleep(1)
stdin, stdout, stderr = ssh.exec_command(command2)
time.sleep(1)
stdin, stdout, stderr = ssh.exec_command(command4)
time.sleep(1)
print(stdout.read())
ssh.close()
print("complete")
What I would expect from the successful execution of this code, would be for the hapi_debug level to be 1. Which means that when I SSH into the thing, I would see those HAPI debugs populating. When I do, I do not see those debugs.
I assume that the gotoshell and hapi_debug=1 are not top-level commands, but subcommands of the stcli. In other words, the stcli is kind of a shell.
In that case, you need to write the commands that you want to execute in the subshell to its stdin:
stdin, stdout, stderr = ssh.exec_command('stcli')
stdin.write('gotoshell\n')
stdin.write('hapi_debug=1\n')
stdin.flush()
If you call stdout.read afterwards, it will wait until the command stcli finishes. What it never does. If you wanted to keep reading the output, you need to send a command that terminates the subshell (typically exit\n).
stdin.write('exit\n')
stdin.flush()
print(stdout.read())

Redirecting output from remote server to Python script

I am trying to create a python script that will gather some basic server's information and print it to the user who invoked the script.
def checks(argv):
host = argv[1]
sshclient = paramiko.SSHClient()
sshclient.set_missing_host_key_policy(paramiko.AutoAddPolicy)
if argv[2] == "22":
sshclient.connect(hostname=host, username='root', password=argv[3], port=argv[2])
stdin, stdout, stderr = sshclient.exec_command('top -n1')
data = stdout.read().decode("utf-8") + stderr.read().decode("utf-8")
print(data)
elif argv[2] == "22211":
sshclient.connect(hostname=host, username='root', key_filename=key_path, port=22211)
stdin, stdout, stderr = sshclient.exec_command('top -n1')
data = stdout.read() + stderr.read()
data.decode("utf-8")
print(data)
print(type(data))
#here I use my function
checks(sys.argv)
I am using SSH library to connect to server, then perform needed commands and save the data streams to my variable. Is there a possibility to, for example, invoke 'top' on remote machine and constantly redirect output from top to my Python variable so I can show it so it would like I am simply running 'top' on my machine and see the updating result?
The final thing I want to achieve is a simple program with GUI which will have several tabs, one of them will show running top output, another will show whole log file of some program (like Apache), etc etc.
Is that possible? Any recommendations on how I can do so?

How to connect Paramiko stdin to console? [duplicate]

I'm trying to run an interactive command through paramiko. The cmd execution tries to prompt for a password but I do not know how to supply the password through paramiko's exec_command and the execution hangs. Is there a way to send values to the terminal if a cmd execution expects input interactively?
ssh = paramiko.SSHClient()
ssh.connect(server, username=username, password=password)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("psql -U factory -d factory -f /tmp/data.sql")
Does anyone know how this can addressed? Thank you.
The full paramiko distribution ships with a lot of good demos.
In the demos subdirectory, demo.py and interactive.py have full interactive TTY examples which would probably be overkill for your situation.
In your example above ssh_stdin acts like a standard Python file object, so ssh_stdin.write should work so long as the channel is still open.
I've never needed to write to stdin, but the docs suggest that a channel is closed as soon as a command exits, so using the standard stdin.write method to send a password up probably won't work. There are lower level paramiko commands on the channel itself that give you more control - see how the SSHClient.exec_command method is implemented for all the gory details.
I had the same problem trying to make an interactive ssh session using ssh, a fork of Paramiko.
I dug around and found this article:
Updated link (last version before the link generated a 404): http://web.archive.org/web/20170912043432/http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/
To continue your example you could do
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("psql -U factory -d factory -f /tmp/data.sql")
ssh_stdin.write('password\n')
ssh_stdin.flush()
output = ssh_stdout.read()
The article goes more in depth, describing a fully interactive shell around exec_command. I found this a lot easier to use than the examples in the source.
Original link: http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/
You need Pexpect to get the best of both worlds (expect and ssh wrappers).
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(server_IP,22,username, password)
stdin, stdout, stderr = ssh.exec_command('/Users/lteue/Downloads/uecontrol-CXC_173_6456-R32A01/uecontrol.sh -host localhost ')
alldata = ""
while not stdout.channel.exit_status_ready():
solo_line = ""
# Print stdout data when available
if stdout.channel.recv_ready():
# Retrieve the first 1024 bytes
solo_line = stdout.channel.recv(1024)
alldata += solo_line
if(cmp(solo_line,'uec> ') ==0 ): #Change Conditionals to your code here
if num_of_input == 0 :
data_buffer = ""
for cmd in commandList :
#print cmd
stdin.channel.send(cmd) # send input commmand 1
num_of_input += 1
if num_of_input == 1 :
stdin.channel.send('q \n') # send input commmand 2 , in my code is exit the interactive session, the connect will close.
num_of_input += 1
print alldata
ssh.close()
Why the stdout.read() will hang if use dierectly without checking stdout.channel.recv_ready(): in while stdout.channel.exit_status_ready():
For my case ,after run command on remote server , the session is waiting for user input , after input 'q' ,it will close the connection .
But before inputting 'q' , the stdout.read() will waiting for EOF,seems this methord does not works if buffer is larger .
I tried stdout.read(1) in while , it works
I tried stdout.readline() in while , it works also.
stdin, stdout, stderr = ssh.exec_command('/Users/lteue/Downloads/uecontrol')
stdout.read() will hang
I'm not familiar with paramiko, but this may work:
ssh_stdin.write('input value')
ssh_stdin.flush()
For information on stdin:
http://docs.python.org/library/sys.html?highlight=stdin#sys.stdin
Take a look at example and do in similar way
(sorce from http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/):
ssh.connect('127.0.0.1', username='jesse',
password='lol')
stdin, stdout, stderr = ssh.exec_command(
"sudo dmesg")
stdin.write('lol\n')
stdin.flush()
data = stdout.read.splitlines()
for line in data:
if line.split(':')[0] == 'AirPort':
print line
You can use this method to send whatever confirmation message you want like "OK" or the password. This is my solution with an example:
def SpecialConfirmation(command, message, reply):
net_connect.config_mode() # To enter config mode
net_connect.remote_conn.sendall(str(command)+'\n' )
time.sleep(3)
output = net_connect.remote_conn.recv(65535).decode('utf-8')
ReplyAppend=''
if str(message) in output:
for i in range(0,(len(reply))):
ReplyAppend+=str(reply[i])+'\n'
net_connect.remote_conn.sendall(ReplyAppend)
output = net_connect.remote_conn.recv(65535).decode('utf-8')
print (output)
return output
CryptoPkiEnroll=['','','no','no','yes']
output=SpecialConfirmation ('crypto pki enroll TCA','Password' , CryptoPkiEnroll )
print (output)

Python Paramiko - wait on more output from passed command before exiting

I have the following code
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())
privatekeyfile = 'PK_FILE_PATH'
username ="USERNAME"
mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile)
client.connect(hostname= IP, username=username, pkey=mykey)
command = SERVER_COMMAND
stdin, stdout, stderr = client.exec_command(command)
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
stdoutLines = stdout.readlines()
print stdoutLines
The command I'm executing takes about 10 seconds to run on the server. It initially returns some information (user profile and module version), then runs some code to check the status of some local server resources.
Paramiko is closing the connection after it receives the initial header information. I need it to wait for the full output of the serverside command to return. I've tried implementing tintin's solution here, with the same result
Any ideas?
add get_pty=True
This will wait until command execution completed.
stdin,stdout,stderr = self.ssh.exec_command(command,get_pty=True)
Paramiko is closing the connection after it receives the initial header information.
I do not think that's true. Try running a command like
command = 'echo first && sleep 60 && echo second'
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
stdoutLines = stdout.readlines()
print stdoutLines
You will get both lines (also note that I'm printing the lines within the loop, so you can see lines).
It must be something with your command, like:
The command print the final output on stderr, not stdout.
The command does not print the final output when executed without TTY.
The command is a script that executes the a sub-command on a background, hence the the script finishes before the sub-command.

How to pass local variable to remote echo command?

import paramiko, commands
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.load_system_host_keys()
ssh_client.connect('xx.xx.x', username='abc',
key_filename='rsa')
line ="Hello"
stdin, stdout, stderr=ssh_client.exec_command('echo $line')
print stdout.readlines()
I want to pass the "line" content to echo. But i get
[u'\n'] as output.
I have also tried echo \$line, echo "$line". But not getting hello as output.
The remote shell can't access to your program variables, the command must be composed before its launch.
stdin, stdout, stderr = ssh_client.exec_command('echo "{0}"'.format(line))
Be aware of safety issues (Thanks #Tripleee), in Python 3 use shlex.quote to increase the robustness of your code:
stdin, stdout, stderr = ssh_client.exec_command('echo {}'.format(quote(line)))

Categories