Python SSH Connection with Paramiko & Netmiko libs - python

If anyone could give a help, i have an issue with hop ssh conections.
I can´t use (Netmiko SSH Proxy Support by Keith), maybe because i´m running in windows box.
So I connect via ssh to hop server and then to router using paramiko lib. Next I want to pull netmiko to send/retrive commands/outputs, but I allways receive errors with the ConnectHandler when I start the ssh connection with paramiko:
ERROR:
line 40, in <module>
net_connect = ConnectHandler(device_type='cisco_ios', ip='x', username='x', password='x')
File "build\bdist.win-amd64\egg\netmiko\ssh_dispatcher.py", line 96, in ConnectHandler
File "build\bdist.win-amd64\egg\netmiko\base_connection.py", line 89, in __init__
File "build\bdist.win-amd64\egg\netmiko\base_connection.py", line 396, in establish_connection
netmiko.ssh_exception.NetMikoTimeoutException: Connection to device timed-out: cisco_ios x.x.x.x:22
Below my (simple) code, i am really fresh in programming, so my code can be awful :(.
import paramiko
import netmiko
from netmiko import ConnectHandler
from getpass import getpass
import time
import re
import sys
# First ssh connection
remote_conn_pre=paramiko.SSHClient()
remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
remote_conn_pre.connect(ip, port=22, username=username,
password=password,
look_for_keys=False, allow_agent=False)
remote_conn = remote_conn_pre.invoke_shell()
output = remote_conn.recv(65535)
print output
# Second SSH connection
remote_conn.send("ssh x#ip x \n>")
time.sleep(3)
remote_conn.send("password\n")
output1 = remote_conn.recv(65535)
print output1
time.sleep(3)
# Trying to run netmiko...
net_connect = ConnectHandler(device_type='cisco_ios', ip='x.x.x.x', username='user', password='password')
net_connect.find_prompt()
CISCO_SHOW_ACL_x = net_connect.send_command("show run | s access-list x ")

instead of device_type='cisco_ios' => use 'device_type': 'cisco_ios', it might be a syntax thing

Related

Paramiko : Throwing error when trying to execute python on remote server

I have a program to execute python on a remote server using Paramiko . So it is just that the script to call python is located in one remote server and the script caling is located on another .
So i thought of using Paramiko . But it is throwing me error . tried to correct error using different methods obtained from stack but in vain . Can anyone kindy help .
import paramiko
import sys
import os
host = "powe76nk.dfrlpw.com"
port = 8015
username = "tre#dfrlpw"
password = "abcd"
command = "D:\***\FlaskTest\Callfunction.py"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, port, username, password)
stdin, stdout, stderr = ssh.exec_command(command)
lines = stdout.readlines()
print(lines)
and it is throwing me error
D:\Programs\FlaskAPICallTest\CallingPythonFile>python testingserver.py
Traceback (most recent call last):
File "testingserver.py", line 15, in <module>
ssh.connect(host, port, username, password)
File "C:\Users\fmxdev\AppData\Local\Programs\Python\Python38\lib\site-packages
\paramiko\client.py", line 368, in connect
raise NoValidConnectionsError(errors)
paramiko.ssh_exception.NoValidConnectionsError: [Errno None] Unable to connect t
o port 8015 on *****
was not able to solve this issue and is checking this for the last 2 days . Is there any alternate for this
Your username should be tre and not tre#dfrlpw.
Also can you manually ssh into the server using ssh command or putty?

SFTP hang and authentication failure with paramiko

I'm trying to connect via SFTP with paramiko and Python 2.7, to eventually get a file from remote server and put to my server. (Note it uses a non-standard port too)
But when I try to connect - it takes a really long time and then I get an authentication error. Have you have this issue have suggestions for fixing?
I don't have a key, it just uses a username/password. I can connect with a graphical SSH program without issues, so the credentials seem correct.
Here is code:
hostname = 'remotehostname.com'
username= 'AB1239'
password= ‘password’
port = 10022
import paramiko
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(hostname=hostname, username=username, password=password,port=port)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/paramiko/client.py", line 380, in connect
look_for_keys, gss_auth, gss_kex, gss_deleg_creds, gss_host)
File "/usr/lib/python2.7/site-packages/paramiko/client.py", line 597, in _auth
raise saved_exception
paramiko.ssh_exception.AuthenticationException: Authentication failed.
I am using:
>>> print paramiko.__version__
1.16.1
and python Python 2.7.5 (on linux)
http://docs.paramiko.org/en/2.4/api/transport.html# (these are for version 2.4, but note I'm using earlier version)
http://docs.paramiko.org/en/2.4/api/client.html
I also looked at this : Why does Paramiko hang if you use it while loading a module?
but still having connection issues.
I'm not quite sure if that answers your question 100 percent, but I thought better than no answer at all, especially since I'm pretty sure it can solve your problem, even though I haven't tested it in this release (no default port).
# coding: utf-8
from fabric.api import env, execute # hosts
from fabric.network import ssh
from fabric.operations import get, run, sudo # put
ssh.util.log_to_file("paramiko.log", 10)
env.host_string = 'remotehostname.com'
env.port = 10022
env.user = 'AB1239'
env.password = 'password'
# Attention: "rm -r" won't ask for password anymore!
env.warn_only = True
def blah():
sudo('ls')
get('/tmp/lolo*.xml', '/tmp', use_sudo=True) # from remote to local
# sudo('rm -r /tmp/what/no/')
execute(blah)

can't login with Paramiko ssh client

local-host --->Aterm server (security server ) -----> target-machine(
I am trying to write a code in Python using Paramiko to first SSH from local-host to the target-machine. From the target-machine, I want to capture some outputs and store them locally either as a variable or as a file (havent got to that point yet). I found an example from stackoverflow where they talk about using nested SSH with paramiko, and I follow it but I get stuck here:
i need just reaching the target-machine
My code:
import paramiko
import sys
import subprocess
hostname = '10.10.10.1'
port = 22
username = 'mohamed.hosseny'
password ='Pass#1'
client = paramiko.Transport((hostname, port))
client.connect(username=username, password=password)
client.close()
but i found the below error message :
Traceback (most recent call last):
File "C:/Users/mohamed.hosseny/Desktop/Paramiko.py", line 13, in <module>
client = paramiko.Transport((hostname, port))
File "C:\Python27\lib\site-packages\paramiko\transport.py", line 332, in
__init__
'Unable to connect to {}: {}'.format(hostname, reason))
SSHException: Unable to connect to 10.10.10.1: [Errno 10060] A connection
attempt failed because the connected party did not properly respond after
a period of time, or established connection failed because connected host
has failed to respond
paramiko.Transport is a lower level API. Don't use it unless you have a good reason. Instead, you can use paramiko.SSHClient.

how to do sftp python 3?

I am using the code below to do sftp:
#!/opt/python3/bin/python3
import paramiko
import sys
host = '192.168.1.2'
port = 22622
transport = paramiko.Transport((host, port))
password = "p#ssw0rd"
username = "web"
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport)
path = '/log/ERROR.LOG'
localpath = '/home/web/ERROR.LOG'
sftp.get(path, localpath)
sftp.close()
transport.close()
print ("Download done.")
But the output is:
Traceback (most recent call last):
File "c.py", line 2, in <module>
import paramiko
ImportError: No module named paramiko
Is there no Paramiko module for Python3?
What do I have to use to do sftp?
Paramiko does not yet officially support Python 3. I found a bug discussing it, and SFTP is one of the problem spots:
https://github.com/paramiko/paramiko/issues/16
I recommend using subprocess to run the sftp command-line tool.

Port forwarding with Paramiko

I'm trying to do some port forwarding from a python app using Paramiko. I can set up the SSH connection just fine, but I'm a bit stumped as to how to use paramiko.Transport. I've already found this file, but I can't work out what's going on in it. From looking at the paramiko.Transport docs, it seems that a single line using the open_channel function, but I can't work out how to implement that. I'm trying to replicate a simple ssh -L 8000:localhost:8000.
Can anyone help me out?
Please find some code using paramiko-1.7.7.1, pycrypto-2.6 and the forward.py script from which I did remove code from the line 115 to the end (to avoid options parsing).
import paramiko, sys
from forward import forward_tunnel
remote_host = "target_host"
remote_port = 8000
local_port = 8000
ssh_host = "my_ssh_host"
ssh_port = 22
user = "login"
password = "s3cr3t"
transport = paramiko.Transport((ssh_host, ssh_port))
# Command for paramiko-1.7.7.1
transport.connect(hostkey = None,
username = user,
password = password,
pkey = None)
try:
forward_tunnel(local_port, remote_host, remote_port, transport)
except KeyboardInterrupt:
print 'Port forwarding stopped.'
sys.exit(0)
I've tested it successfully from a Windows station, using a ssh server under Red Hat and pointing to a 3rd server. (I'm using Python 2.7.2)
Hope it helps,
You can use https://github.com/pahaz/sshtunnel
pip install sshtunnel
Code example:
import sshtunnel
with sshtunnel.open(
(ssh_host, ssh_port),
ssh_host_key=None,
ssh_username=ssh_user,
ssh_password=ssh_password,
ssh_private_key=None,
remote_bind_address=(REMOTE_HOST, REMOTE_PORT)) as server:
def do_something(port):
# Do something with port
pass
print("LOCAL PORT:", server.local_bind_port)
do_something(server.local_bind_port)

Categories

Resources