not able to get anything in output in python ssh - python

I am trying to connect to remote server and then try to login the sql server in that machine. however i am not getting any ouput of this script
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy() )
ssh.connect(hostname='172.18.109.244', username='bgf', password='bgf')
print "Logged In to EMS"
cmd = 'mysql -uroot -root'
stdin, stdout, stderr = ssh.exec_command(cmd)
stdin.write("show databases;")
stdin.write('\n')
stdin.flush()
print stdout.read()

As mentioned in a comment by #Charles,
read() consumes content to EOF. There is no EOF here because MySQL is
still open. The easy answer is to not just flush stdin, but close it.
you can not do that because MySQL is still open and your script will hang there. So if you just want to get the database, then pass the query to MySQL connection and will work fine :).
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy() )
ssh.connect(hostname='172.18.109.244', username='somuser',password='bgf')
print "Logged In to EMS"
cmd = 'mysql -h somehost.example.com -uroot -proot -e \'show databases;\''
stdin, stdout, stderr = ssh.exec_command(cmd)
# stdin.write("show databases;")
stdin.write('\n')
stdin.flush()
print stdout.read()

Related

Failing to start an .exe to a remote Windows server using Python and paramiko

I have written a simple script that I want to run remotely to a Windows server using Python and Paramiko. The script should execute commands in the cmd on the remote Windows server and I want it to start up an .exe program for a starter. Here is what I have up to now:
import paramiko
hostname = "IP_of_server"
username = "username"
password = "password"
command = "start Full_Path_To_Application\Program.exe"
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname, username=username, password=password, look_for_keys=True, allow_agent=False)
print("Connected to %s" % hostname)
except paramiko.AuthenticationException:
print("Failed to connect to %s due to wrong username/password" %hostname)
exit(1)
try:
stdin, stdout, stderr = ssh.exec_command(command)
for line in stdout.readlines():
print(line)
print("Application has been started")
except:
exit(2)
What I get is:
Connected to IP_of_server
Application has been started
When I check on the server using the same username and password the application is not running. Running it manually starts it up.
I have confirmed that the command has been sent to the server by replacing it with "ipconfig" and I get the correct information.
Any idea why the application is not starting? Once it starts it should open a separate cmd with all the logs that I'm not seeing.
Thanks a lot.

'Error opening terminal: unknown.' error when running a command in SSH server through Python

I am trying to SSH to a server with Python and I have been able to do so successfully. I am able to run the commands within Python successfully with one exception, the main command that is the focus of my program. It is a SIPp command that will only run within the SSH server and in a specific folder.
When I run the command in my terminal, it works perfectly fine; however, when I connect to the SSH server through PExpect or Paramiko (both work fine), I try to send my command but I get the
Error Opening Terminal: Unknown
I have so far, read the docs, tried using os, subprocess, and multiple different ways of connecting with Paramiko and Pxssh. The several people I work with were not able to figure it out either.
The SIPp command that I am trying to send and read the output of:
sipp -r 5 -m 20 -trace_msg -inf users.csv -sf register.xml -d 10000 -i [IP addresses]
# some of the command was left out for simplicity's sake
# there is no issue with the command
Connecting to SSH through Pxssh (PExpect):
from pexpect import pxssh
from getpass import getpass
try:
s = pxssh.pxssh()
hostname = input('hostname: ')
username = input('username: ')
password = getpass("password :", None)
s.login(hostname, username, password)
s.sendline('cd [location of the folder]')
s.prompt()
print(s.before)
s.sendline('sipp -r 5 -m 20 -trace_msg -inf users.csv -sf register.xml -d 10000 -i [IP addresses]') #this is the only line that doesn't work / output anything.
s.prompt()
print(s.before)
s.sendline('ls')
s.prompt()
print(s.before)
s.logout()
except pxssh.ExceptionPxssh as e:
print("Something went wrong. Try again with the correct Host Name, Username, and Password")
print(e)
Connecting to SSH through Paramiko:
from paramiko import client
from getpass import getpass
class ssh:
client = None
def __init__(self, address, username, password):
self.client = client.SSHClient()
self.client.set_missing_host_key_policy(client.AutoAddPolicy())
self.client.connect(address, username=username, password=password, look_for_keys=False)
def sendCommand(self, command):
if self.client:
stdin, stdout, stderr = self.client.exec_command(command)
output = stdout.readlines()
print(output, stderr.readlines())
while not stdout.channel.exit_status_ready():
if stdout.channel.recv_ready():
alldata = stdout.channel.recv(1024)
prevdata = b"1"
while prevdata:
prevdata = stdout.channel.recv(1024)
alldata += prevdata
print(str(alldata, "utf8"))
self.client.close()
else:
print("Connection not opened.")
connection = ssh([ssh info])
connection.sendCommand("cd [location] ; sipp -r 5 -m 20 -trace_msg -inf users.csv -sf register.xml -d 10000 -i [IP addresses]")
Both give me this error: Error opening terminal: unknown.
My guess is that it is not spawning an actual terminal but I can't figure out what to do at this point. Any help would be sincerely appreciated
Your command needs terminal emulation.
Either:
Try to find if there's a way to run the command, so that it does not require the terminal emulation. Maybe -bg switch can help.
Possibly this was a bug in an older version of SIPP. Make sure you have the latest version. See Startup failure when running from environment without TERM.
Or, enable the terminal emulation (what can bring unwanted side effects). With Paramiko SSHClient.exec_command, use its get_pty argument:
stdin, stdout, stderr = self.client.exec_command(command, get_pty=True)

Making SSH from a jumpserver(linux) to Devices(modem) using Python

I'm trying to execute few commands in a Jump server(linux) to access certain devices(modems) using SSH. And then get some device details after login in to the device(modem)
I'm using Paramiko to access jump server, the below code
import paramiko
import time
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('jump server ip', username='user', password='pass', key_filename='D:\New folder\id_rsa')
stdin, stdout, stderr = ssh.exec_command('pwd') #prints the correct pwd
This works fine
So from the jump server I need to ssh a device(modem) using its ipv6 mac address.
the command is
sudo stbsshv6 'ipv6address'/n
But when I execute any command after ssh the device(modem), I'm not getting anything in stdout. Example:
import paramiko
import time
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('jump server ip', username='user', password='pass', key_filename='D:\New folder\id_rsa')
stdin, stdout, stderr = ssh.exec_command('sudo stbsshv6 "ipv6address"')
stdin.write('ifconfig wlan0\n')#some working command
print stdout.readlines() # prints nothing
I can do manually the above steps using putty,
I'm new to python, can anyone suggest the right solution for this or any alternate way is also great. Thanks

Create a SSH session connect to device through a terminal server

I want to connect to a network device. But in out policy, I have to ssh successfully to a terminal server first, then from this one, ssh to network device. In Python, I use Paramiko :
import paramiko
ssh = paramiko.SSHClient()
print("OTP : ")
otp = raw_input()
ssh.port=9922
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.load_system_host_keys()
ssh.connect('10.0.0.1',9922,username='khangtt',password=str('12345')+str(otp))
stdin, stdout, stderr = ssh.exec_command('whoami')
stdin.close()
for line in stdout.read().splitlines():
print(line)
Connect to server sucessfully, I can see my username in the output. But I don't know how to SSH to device. I used this but nothing happen to set input user/pass :
stdin, stdout, stderr = ssh.exec_command('telnet 10.80.1.120')
stdin.close()
for line in stdout.read().splitlines():
print(line)
Since you are using paramiko, use the documentation here: https://pynet.twb-tech.com/blog/python/paramiko-ssh-part1.html. Its very explicit.
Or you can also try the codes here to connect:
ssh.connect('10.0.0.1', 'khangtt', str('12345')+str(otp), look_for_keys=False, allow_agent=False)
Or
ssh.connect('10.0.0.1', 'khangtt', str('12345')+str(otp))
in case you don't need look for keys and allow agent.

python ssh connection problem

I tried this code:
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.0.222', username='sshuser', password='pass')
stdin, stdout, stderr = ssh.exec_command("pwd")
stdout.readlines()
and the ssh connection works, but as soon as I use:
stdin, stdout, stderr = ssh.exec_command("pwd")
I get this error message:
Exception in thread Thread-1 (most likely raised during interpreter shutdown)
How can I just do the "pwd" command and get the output?
Thanks!
try:
stdin, stdout, stderr = ssh.exec_command("pwd")
except SSHException:
ssh.close()
That will keep it from crashing like that, but won't fix your problem. Make sure you can connect with a regular ssh client and run pwd. Then make sure your login credentials are correct.

Categories