This question already has answers here:
Executing command using "su -l" in SSH using Python
(1 answer)
Execute (sub)commands in secondary shell/command on SSH server in Python Paramiko
(1 answer)
Closed 6 months ago.
this is my code:
import paramiko
import time
host = "123.456.789"
username = "myusername"
password = "mypassword"
client = paramiko.client.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, username=username, password=password)
_stdin, _stdout,_stderr = client.exec_command("sudo -i")
_stdin.write(password + '\n')
_stdin, _stdout,_stderr = client.exec_command("sudo wget -O- 'https://abc.com.gz' | gunzip | dd of=/dev/sda", get_pty=True)
_stdin.flush()
#Print content
for line in _stdout.readlines():
print(_stdout.read().decode())
# Close ssh connect
time.sleep(5)
client.close()
the result I get is the screen doesn't print anything, and after a period of ~30-40 minutes the server doesn't receive any files from the wget command....
Try to invoke the Shell instead:
import paramiko, time
host = "123.456.789"
username = "myusername"
password = "mypassword"
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, username=username, password=password)
remote_shell = client.invoke_shell()
remote_shell.send("sudo -i")
remote_shell.send(password + "\n")
remote_shell.send("sudo wget -O- 'https://abc.com.gz' | gunzip | dd of=/dev/sda")
# print reply
time.sleep(1)
print(remote_shell.recv(65535))
time.sleep(1)
client.close()
Related
I have to extract backups from Mikrotik with python and save them in my server so these backups are saved in my computer and also on the servers. I've been searching for info about it but didn't have any luck. Can someone help me?
""" Authentication for remote desktops through ssh protocol """
import paramiko
from getpass import getpass
import time
HOST = 'xxx.xxx.xxx.xxx'
PORT ='xxx'
USER = 'xxxxxxx'
""" data =dict(hostname=HOST, port=PORT, username=USER) """
if name == 'main':
# try:
client = paramiko.SSHClient()
client.set_missing_host_key_policy( paramiko.AutoAddPolicy())
password = getpass ('Insert password: ')
client.connect(HOST, PORT, username=USER, password=password)
stdin, stdout, stderr = client.exec_command('ls')
#tried everything here
time.sleep(1)
result = stdout.read().decode()
# except paramiko.ssh_exception.AuthenticationException as e:
# print('Failed authentication')
print(result)
You cannot do that with plain SSH. It will execute RouterOS commands (so no ls). The task can be done with FTP or SFTP (if you prefer SSH) client:
$ sftp admin#192.0.2.1
admin#192.0.2.1's password:
Connected to 192.0.2.1.
sftp> ls
flash
sftp> cd flash
sftp> ls
MikroTik-20210509-1756.backup MikroTik-20210509-1938.backup skins
sftp> get MikroTik-20210509-1756.backup
Fetching /flash/MikroTik-20210509-1756.backup to MikroTik-20210509-1756.backup
MikroTik-20210509-1756.backup 100% 345KB 808.0KB/s 00:00
sftp> exit
This question already has an answer here:
Executing command using Paramiko exec_command on device is not working
(1 answer)
Closed 3 months ago.
I've been trying to create a script that would back up our switches from a CSV file.
I'm using Paramiko to SSH into a switch and run "show run", but for some reason the only output I'm receiving is the name of the switch.
import pandas
import paramiko
# Connection info
USERNAME = "username"
PW = "password"
PORT = 22
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Backup \ import location
DEST = "C:\\temp\\test\\"
CSV = DEST+"Switches.csv"
device_list = pandas.read_csv(CSV)
for index, row in device_list.iterrows():
IP = row["IP"]
floor = row["Floor"]
side = row["Side"]
formatted_ip = IP.replace(".", "_")
filename = f"{formatted_ip}_{floor}{side}.txt"
ssh.connect(hostname=IP, username=USERNAME, password=PW, port=PORT)
stdin, stdout, stderr = ssh.exec_command('show running-config')
stdin.close()
output = stdout.readlines()
errors = stderr.read()
print(output)
print(stderr.readlines())
outfile = open(DEST + filename, "w")
for char in output:
outfile.write(char)
ssh.close()
outfile.close()
The output I'm receiving (and also writing into the created file) is SW-3A-48p-4>
I'm able to connect to the switch and run "show run".
I'm expecting to get the whole switch configuration but the output stops on the first line.
As #MarinPrikryl pointed, the devices I was trying to connect do not support the "exec" channel.
Here's how I managed to do it using the shell:
import pandas
import paramiko
from time import sleep
# Connection info
USERNAME = "username"
PW = "password"
PORT = 22
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # I know this isn't recommended, I'll find a better solution for it.
# Backup \ import location
DEST = "C:\\temp\\test\\"
CSV = DEST + "Switches.csv"
device_list = pandas.read_csv(CSV)
for index, row in device_list.iterrows():
IP = row["IP"]
floor = row["Floor"]
side = row["Side"]
formatted_ip = IP.replace(".", "_")
filename = f"{formatted_ip}_{floor}{side}.txt"
ssh.connect(hostname=IP, username=USERNAME, password=PW, port=PORT)
channel = ssh.invoke_shell()
stdout = channel.makefile('r')
channel.send('enable\r\n')
sleep(1)
channel.send('terminal length 0\r\n')
sleep(1)
channel.send('copy running-config startup-config\r\n')
sleep(1)
channel.send('y\r\n')
sleep(10)
channel.send('show running-config\r\n')
sleep(2)
data = channel.recv(5000)
data = data.decode("utf8", "ignore")
data = data.split('show running-config')
data = data[1][:len(data) - 15]
outfile = open(DEST + filename, "w")
for char in data:
outfile.write(char)
ssh.close()
outfile.close()
I'm sure there are better ways to do it, but this works for now.
Thanks a lot to everyone who helped.
I use Python flask and paramiko to execute command on my remote ssh server from my html form.
It should to display the message back to my html file:
(result from the executed file in ssh server)
Any Idea or Website Link are welcoming
Thank you.
You can use something like this within a function. Once the function is called return the "output" to the html.
import sys, paramiko
if len(sys.argv) < 4:
print "args missing"
sys.exit(1)
hostname = sys.argv[1]
password = sys.argv[2]
command = sys.argv[3]
username = "admin"
port = 22
try:
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
client.connect(hostname, port=port, username=username, password=password)
stdin, stdout, stderr = client.exec_command(command)
output = stdout.read(),
finally:
client.close()
This question already has an answer here:
how to use paramiko to execute remote commands
(1 answer)
Closed 3 years ago.
I have cisco server (c220) and i want to start to build scripts to automate tasks.
I just need to know how to start ssh session with paramiko and write linux commands with this library(in phycharm 2.7 if its matter)
I will be happy if you can write for me an example to ssh cisco c220 server with ip x.x.x.x and to ask for him the health status.
Thank you very much!
Avi
Try this:
#!/usr/bin/env python
import sys, paramiko
if len(sys.argv) < 4:
print "args missing"
sys.exit(1)
hostname = sys.argv[1]
password = sys.argv[2]
command = sys.argv[3]
username = "admin"
port = 22
try:
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy)
client.connect(hostname, port=port, username=username, password=password)
stdin, stdout, stderr = client.exec_command(command)
print stdout.read(),
finally:
client.close()
I have the following script to connect to an custom ssh shell.
When I execute the script it just hangs. It doesnt execute the command. I suspect problems with the shell because it does not have any prompt. Do you have any idea?
import sys
import os
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('10.115.130.22', username='admin', password='xxx', timeout = 30)
stdin, stdout, stderr = ssh.exec_command('xconfiguration SystemUnit Name: devicename')
print stdout.readlines()
ssh.close()`
I spent way too much time on this problem. I found that I needed to use the invoke_shell() to be able to get anything past the greeting banner on the Tandberg C/E series video endpoints. Here's my working code, FWIW:
import time
import paramiko
command = 'help'
host = 'x.x.x.x'
port = 22
user = 'admin'
passwd = 'TANDBERG'
def tbgShell(host,port,username,password,cmd):
"""send an arbitrary command to a Cisco/TBG gizmo's ssh and
get the result"""
transport = paramiko.Transport((host, port))
transport.connect(username = user, password = passwd)
chan = transport.open_channel("session")
chan.setblocking(0)
chan.invoke_shell()
out = ''
chan.send(cmd+'\n')
tCheck = 0
while not chan.recv_ready():
time.sleep(1)
tCheck+=1
if tCheck >= 6:
print 'time out'#TODO: add exeption here
return False
out = chan.recv(1024)
return out
output = tbgShell(host, port, user, passwd, command)
print output
This is a custom shell. It is a cisco ex90 video conferencing system.
But I tried different commands like xconfig which show you the config.