Extract backups from Mikrotik with python - python

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

Related

Executing passwd command in Python Paramiko to change a password on a Linux server

I am trying to write a Python 3 script to pragmatically ssh into a Linux server and change the password. I have put a script together using the Paramiko module.
I am running into issues when trying to run multiple shell commands. My script attempts to execute the commands but Paramiko times out after one shell command.
This is the script I am currently working on. Any insight would be greatly appreciated.
import paramiko
def change_pw():
hostname = "IP" #IP Address of Linux Server
username = "root" #username
password = "oldpw!" #password for Linux Server
#NOTE - This variable is suppose to define 3 shell commands. I do not believe the script is sending these commands as listed because the password does not update.
commands = [
"passwd",
"newpw!",
"newpw!"
]
#NOTE - Attempted to utilize '\n' to execute multiple commands and failed
# commands = [
# "passwd \n newpw! \n newpw!"
# ]
# initialize the SSH clientp0-
client = paramiko.SSHClient()
# add to known hosts
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname=hostname, username=username, password=password)
except:
print("[!] Cannot connect to the SSH Server")
exit()
# execute the commands
for command in commands:
print("="*50, command, "="*50)
stdin, stdout, stderr = client.exec_command(command)
print(stdout.read().decode())
err = stderr.read().decode()
if err:
print(err)
change_pw()
You do not have three commands. You have one command, the passwd, which takes two lines of input.
These two questions show how to provide an input to commands using Paramiko:
Pass input/variables to command/script over SSH using Python Paramiko
Executing command using "su -l" in SSH using Python
So specifically for passwd, you need to use:
stdin, stdout, stderr = client.exec_command('passwd')
# answer the new password prompts
stdin.write('newpw\n')
stdin.write('newpw\n')
stdin.flush()
# wait for the command to complete a print the output
stdout.channel.set_combine_stderr(True)
print(stdout.read().decode())
For the purpose of the Channel.set_combine_stderr, see Paramiko ssh die/hang with big output.
Obligatory warning: Do not use AutoAddPolicy – You are losing a protection against MITM attacks by doing so. For a correct solution, see Paramiko "Unknown Server".
The issue is that I was trying to utilize 3 input commands to change the password for root. I only needed to call the passwd command and then pass two input variables for "Enter new PW" and "Confirm new PW"
import paramiko
import time
hostname = 'IP'
username = 'root'
password = 'oldpw'
commands = ['passwd']
# initialize the SSH clientp
client = paramiko.SSHClient()
# add to known hosts
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname=hostname, username=username, password=password)
except:
print("[!] Cannot connect to the SSH Server")
exit()
# execute the commands
for command in commands:
print("="*50, 'PW change executed', "="*50)
stdin, stdout, stderr = client.exec_command(command)
stdin.write('newpw' '\n' 'newpw' '\n') #input varuables for "Enter new PW" and "re-enter new PW"
stdin.flush()
print(stdout.read().decode())
err = stderr.read().decode()
if err:
print(err)

Display message from remote ssh server to my html page with Python web framework

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()

Ssh cisco server with paramiko [duplicate]

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()

connect to third server using script

I can do ssh from one server to another using this:
# ssh root#1.2.4.148
The following code is doing the same in pythonic way:
import paraminko
#paramiko.util.log_to_file('ssh.log') # sets up logging
client = paramiko.SSHClient()
client.load_system_host_keys()
client.connect('1.2.4.148')
stdin, stdout, stderr = client.exec_command('ls -l')
But if I need to connect to third server from the second server, I can do this:
# ssh -t root#1.2.4.148 ssh root#1.2.4.149
How is this done in python?
My current server (250) has password less keys saved with 148 server for easy access. But connection to 149 from 148 will need password if that matters.
This python function will connect to middle_server first and then to last_server. It will execute the command "mycommand" on last_server and return it's output.
def myconnect():
middle_server='1.2.3.4'
middle_port=3232
middle_user='shantanu'
middle_key_filename='/root/.ssh/id_rsa.pub'
last_server='6.7.8.9'
last_port=1224
last_user='root'
last_password='xxxxx'
mycommand='pwd'
import paramiko
proxy_client = paramiko.SSHClient()
proxy_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
proxy_client.connect(middle_server, port=middle_port, username=middle_user, key_filename=middle_key_filename)
transport = proxy_client.get_transport()
dest_addr = (last_server, last_port)
local_addr = ('127.0.0.1', 1234)
channel = transport.open_channel("direct-tcpip", dest_addr, local_addr)
remote_client = paramiko.SSHClient()
remote_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
remote_client.connect('localhost', port=last_port, username=last_user, password=last_password, sock=channel)
(sshin1, sshout1, ssherr1) = remote_client.exec_command(mycommand)
print sshout1.read()
except:
print "error"
return 0

Paramiko hangs after connecting to custom shell

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.

Categories