Python Paramiko exec_command doesn't print few commands outputs - python

I am trying to build a Python script using Paramiko which should SSH Linux server and execute a command, some commands output is working for example df -f,netstat but some of them aren't for example onstat -,ifconfig. Need help solving this issue.
#!/usr/pkg/bin/python
#Importing modules
import paramiko
import time
#setting parameters like host IP, username, passwd and number of iterations to gather cmds
HOST = 'x.x.x.x'
USER = 'abc'
PASS = 'efg'
ITERATION = 3
client1=paramiko.SSHClient()
#Add missing client key
client1.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#connect to CUCM
client1.connect(HOST,username=USER,password=PASS)
print("SSH connection to %s established" %HOST)
#Gather commands and read the output from stdout
stdin, stdout, stderr = client1.exec_command("onstat -")
time.sleep(2)
for line in stdout.readlines():
print(line)
client1.close()
print("Logged out of device %s" %HOST)
Any thought how to resolve this?

Related

How can I send command to subprocess program with paramiko? [duplicate]

I am having issues passing responses to a bash script on a remote server over SSH.
I am writing a program in Python 3.6.5 that will SSH to a remote Linux server.
On this remote Linux server there is a bash script that I am running which requires user input to fill in. For whatever reason I cannot pass a user input from my original python program over SSH and have it fill in the bash script user input questions.
main.py
from tkinter import *
import SSH
hostname = 'xxx'
username = 'xxx'
password = 'xxx'
class Connect:
def module(self):
name = input()
connection = SSH.SSH(hostname, username, password)
connection.sendCommand(
'cd xx/{}/xxxxx/ && source .cshrc && ./xxx/xxxx/xxxx/xxxxx'.format(path))
SSH.py
from paramiko import client
class SSH:
client = None
def __init__(self, address, username, password):
print("Login info sent.")
print("Connecting to server.")
self.client = client.SSHClient() # Create a new SSH client
self.client.set_missing_host_key_policy(client.AutoAddPolicy())
self.client.connect(
address, username=username, password=password, look_for_keys=False) # connect
def sendCommand(self, command):
print("Sending your command")
# Check if connection is made previously
if (self.client):
stdin, stdout, stderr = self.client.exec_command(command)
while not stdout.channel.exit_status_ready():
# Print stdout data when available
if stdout.channel.recv_ready():
# Retrieve the first 1024 bytes
alldata = stdout.channel.recv(1024)
while stdout.channel.recv_ready():
# Retrieve the next 1024 bytes
alldata += stdout.channel.recv(1024)
# Print as string with utf8 encoding
print(str(alldata, "utf8"))
else:
print("Connection not opened.")
The final /xxxxxx in class Connect is the remote script that is launched.
It will open a text response awaiting a format such as
What is your name:
and I cannot seem to find a way to properly pass the response to the script from my main.py file within the class Connect.
Every way I have tried to pass name as an argument or a variable the answer seems to just disappear (likely since it is trying to print it at the Linux prompt and not within the bash script)
I think using the read_until function to look for the : at the end of the question may work.
Suggestions?
Write the input that your command needs to the stdin:
stdin, stdout, stderr = self.client.exec_command(command)
stdin.write(name + '\n')
stdin.flush()
(You will of course need to propagate the name variable from module to sendCommand, but I assume you know how to do that part).

robot - Paramiko package not executing command 'set management cwmp enable on' in windows while saving some configuration in remote host using ssh [duplicate]

I am having issues passing responses to a bash script on a remote server over SSH.
I am writing a program in Python 3.6.5 that will SSH to a remote Linux server.
On this remote Linux server there is a bash script that I am running which requires user input to fill in. For whatever reason I cannot pass a user input from my original python program over SSH and have it fill in the bash script user input questions.
main.py
from tkinter import *
import SSH
hostname = 'xxx'
username = 'xxx'
password = 'xxx'
class Connect:
def module(self):
name = input()
connection = SSH.SSH(hostname, username, password)
connection.sendCommand(
'cd xx/{}/xxxxx/ && source .cshrc && ./xxx/xxxx/xxxx/xxxxx'.format(path))
SSH.py
from paramiko import client
class SSH:
client = None
def __init__(self, address, username, password):
print("Login info sent.")
print("Connecting to server.")
self.client = client.SSHClient() # Create a new SSH client
self.client.set_missing_host_key_policy(client.AutoAddPolicy())
self.client.connect(
address, username=username, password=password, look_for_keys=False) # connect
def sendCommand(self, command):
print("Sending your command")
# Check if connection is made previously
if (self.client):
stdin, stdout, stderr = self.client.exec_command(command)
while not stdout.channel.exit_status_ready():
# Print stdout data when available
if stdout.channel.recv_ready():
# Retrieve the first 1024 bytes
alldata = stdout.channel.recv(1024)
while stdout.channel.recv_ready():
# Retrieve the next 1024 bytes
alldata += stdout.channel.recv(1024)
# Print as string with utf8 encoding
print(str(alldata, "utf8"))
else:
print("Connection not opened.")
The final /xxxxxx in class Connect is the remote script that is launched.
It will open a text response awaiting a format such as
What is your name:
and I cannot seem to find a way to properly pass the response to the script from my main.py file within the class Connect.
Every way I have tried to pass name as an argument or a variable the answer seems to just disappear (likely since it is trying to print it at the Linux prompt and not within the bash script)
I think using the read_until function to look for the : at the end of the question may work.
Suggestions?
Write the input that your command needs to the stdin:
stdin, stdout, stderr = self.client.exec_command(command)
stdin.write(name + '\n')
stdin.flush()
(You will of course need to propagate the name variable from module to sendCommand, but I assume you know how to do that part).

Pass input/variables to command/script over SSH using Python Paramiko

I am having issues passing responses to a bash script on a remote server over SSH.
I am writing a program in Python 3.6.5 that will SSH to a remote Linux server.
On this remote Linux server there is a bash script that I am running which requires user input to fill in. For whatever reason I cannot pass a user input from my original python program over SSH and have it fill in the bash script user input questions.
main.py
from tkinter import *
import SSH
hostname = 'xxx'
username = 'xxx'
password = 'xxx'
class Connect:
def module(self):
name = input()
connection = SSH.SSH(hostname, username, password)
connection.sendCommand(
'cd xx/{}/xxxxx/ && source .cshrc && ./xxx/xxxx/xxxx/xxxxx'.format(path))
SSH.py
from paramiko import client
class SSH:
client = None
def __init__(self, address, username, password):
print("Login info sent.")
print("Connecting to server.")
self.client = client.SSHClient() # Create a new SSH client
self.client.set_missing_host_key_policy(client.AutoAddPolicy())
self.client.connect(
address, username=username, password=password, look_for_keys=False) # connect
def sendCommand(self, command):
print("Sending your command")
# Check if connection is made previously
if (self.client):
stdin, stdout, stderr = self.client.exec_command(command)
while not stdout.channel.exit_status_ready():
# Print stdout data when available
if stdout.channel.recv_ready():
# Retrieve the first 1024 bytes
alldata = stdout.channel.recv(1024)
while stdout.channel.recv_ready():
# Retrieve the next 1024 bytes
alldata += stdout.channel.recv(1024)
# Print as string with utf8 encoding
print(str(alldata, "utf8"))
else:
print("Connection not opened.")
The final /xxxxxx in class Connect is the remote script that is launched.
It will open a text response awaiting a format such as
What is your name:
and I cannot seem to find a way to properly pass the response to the script from my main.py file within the class Connect.
Every way I have tried to pass name as an argument or a variable the answer seems to just disappear (likely since it is trying to print it at the Linux prompt and not within the bash script)
I think using the read_until function to look for the : at the end of the question may work.
Suggestions?
Write the input that your command needs to the stdin:
stdin, stdout, stderr = self.client.exec_command(command)
stdin.write(name + '\n')
stdin.flush()
(You will of course need to propagate the name variable from module to sendCommand, but I assume you know how to do that part).

SSH to Switch and redirect the printout of command

I am trying to connect to switch and redirect the output of command but it does not work. It only connect and disconnect from switch
#!/usr/pkg/bin/python
#importing modules
import paramiko
import sys
import time
# setting parameters like host IP, username, passwd and port
# to gather cmds
HOST = "10.50.170.21"
USER = "user"
PASS= "password"
PORT = 2024
# A function that logins and execute commands
def fn():
client1=paramiko.SSHClient()
#add missing client key
client1.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#connect to switch
client1.connect(HOST,username=USER,password=PASS,port=2024)
print "SSH connection to %s established" %HOST
stdin,stdout,stderr =client1.exec_command('show-config \n')
print stdout.read()
fn()
and the printout like this :
root#cic-1:~# python test-con.py
SSH connection to 10.50.171.22 established
********************************************************************************
BSP 8100
This system is provided for authorized users only. If you are not
an authorized user, please exit IMMEDIATELY.
********************************************************************************
root#cic-1:~#
anybody knows what can be the issue here ?
I changed the Code as below and now it works fine:
#!/usr/pkg/bin/python
#importing modules
import paramiko
import sys
import time
import pdb
#pdb.set_trace()
# setting parameters like host IP, username, passwd and number of iteration
# to gather cmds
HOST = "10.50.171.22"
USER = "advanced"
PASS = "ett,30"
PORT = 2024
ITERATION = 3
# A function that logins and execute commands
def fn():
client1=paramiko.SSHClient()
#add missing client key
client1.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#connect to switch
client1.connect(HOST,username=USER,password=PASS,port=PORT)
print "SSH connection to %s established" %HOST
remote_conn = client1.invoke_shell()
remote_conn.send("\n")
remote_conn.send("show \n")
time.sleep(2)
output = remote_conn.recv(10000)
print output
# stdin,stdout,stderr =client1.exec_command("config /n")
# stdin,stdout,stderr =client1.exec_command("show /n")
# print stdout.read()
client1.close()
fn()

Creating multiple SSH connections at a time using Paramiko

The code below runs grep in one machine through SSH and prints the results:
import sys, os, string
import paramiko
cmd = "grep -h 'king' /opt/data/horror_20100810*"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('10.10.3.10', username='xy', password='xy')
stdin, stdout, stderr = ssh.exec_command(cmd)
stdin.write('xy\n')
stdin.flush()
print stdout.readlines()
How can I grep five machines all at once (so that I don't have major delay), than put all that in five variables and print them all out.
You'll need to put the calls into separate threads (or processes, but that would be overkill) which in turn requires the code to be in a function (which is a good idea anyway: don't have substantial code at a module's top level).
For example:
import sys, os, string, threading
import paramiko
cmd = "grep -h 'king' /opt/data/horror_20100810*"
outlock = threading.Lock()
def workon(host):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username='xy', password='xy')
stdin, stdout, stderr = ssh.exec_command(cmd)
stdin.write('xy\n')
stdin.flush()
with outlock:
print stdout.readlines()
def main():
hosts = ['10.10.3.10', '10.10.4.12', '10.10.2.15', ] # etc
threads = []
for h in hosts:
t = threading.Thread(target=workon, args=(h,))
t.start()
threads.append(t)
for t in threads:
t.join()
main()
If you had many more than five hosts, I would recommend using instead a "thread pool" architecture and a queue of work units. But, for just five, it's simpler to stick to the "dedicated thread" model (especially since there is no thread pool in the standard library, so you'd need a third party package like threadpool... or a lot of subtle custom code of your own of course;-).
In my case i have to execute commands on server with one ip and port and after complete need to do sftp to other ip and different port.Condition is one connection should be live while doing sftp to another ip due to port forwarding.
Both connection are working separably but while combining both second sftp connection is not working.
#! /usr/bin/env python3
import sys, os, string, threading
try:
import paramiko
#import paramiko package
except:
im = input("Paramiko module is missing. Do you want to install[Y/N]:")
im = im.upper()
if im == "Y":
try:
try:
os.system("pip install paramiko")
except:
os.system("pip3 install paramiko")
except:
print("Please install paramiko package manually")
else:
print("Rerun and type 'y' to install")
#Running paramiko module with interactive password sending function
#this function helps to send password when sudo command is executed
def sudossh():
host = "type host ip"
port = 22
username = "type username"
password = "type password"
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, port, username, password)
ssh.get_transport()
#In this example we will run HTTP module on server in port 80
command = "sudo su -c 'sudo python -m SimpleHTTPServer 80'"
print(f"Running: {command}\n")
stdin, stdout, stderr = ssh.exec_command(command=command,get_pty=True)
stdin.write("password\n")
print("sent password\n")
print("HTTP service is running now\n")
stdin.flush()
if stderr.channel.recv_exit_status() != 0:
print(f"Error: {stderr.readlines()}")
else:
print(f"Output: \n{stdout.readlines()}")
ssh.close()
except Exception as err:
print(str(err));
print("Thanks for using my application");
#Running another paramiko module with interactive password sending function
def grepverification():
host = "type host ip"
port = 22
username = "type username"
password = "type password"
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, port, username, password)
ssh.get_transport()
#Open new session and check port 80 status on server
command = "sudo su -c 'netstat | grep 80'"
print(f"Running: {command}\n")
stdin, stdout, stderr = ssh.exec_command(command=command,get_pty=True)
stdin.write("password\n")
print("sent password\n")
print("Connection is established. Check below output\n")
stdin.flush()
if stderr.channel.recv_exit_status() != 0:
print(f"Error: {stderr.readlines()}")
else:
print(f"Output: \n{stdout.readlines()}")
ssh.close()
except Exception as err:
print(str(err));
print("Thanks for using my application");
def main():
#Multithreading helps to run both at a same time. Useful for verification.
# creating thread
th1 = threading.Thread(target=sudossh)
th2 = threading.Thread(target=grepverification)
# starting thread 1
th1.start()
# starting thread 2
th2.start()
# wait until thread 1 is completely executed
th1.join()
# wait until thread 2 is completely executed
th2.join()
# both threads completely executed
print("Completed!")
#you can use for loop to reduce lines but for understanding & smooth multithreading process will keep it as separate functions
#Comments are welcome. Thanks. Follow me on https://www.linkedin.com/in/dinesh-kumar-palanivelu-858441128/
#you need to change line - 23-26,36,51-54,64
if __name__=='__main__':
main()

Categories

Resources