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