How use Connection in Fabric 2? - python

I'm trying to connect to host and run command with module Fabric 2 and have this error:
Traceback (most recent call last):
File "Utilities/fabfile.py", line 4, in <module>
res.run('uname -s')
File "<decorator-gen-3>", line 2, in run
File "/usr/local/lib/python2.7/dist-packages/fabric/connection.py", line 29, in opens
self.open()
File "/usr/local/lib/python2.7/dist-packages/fabric/connection.py", line 501, in open
self.client.connect(**kwargs)
File "/home/trishnevskaya/.local/lib/python2.7/site-packages/paramiko/client.py", line 424, in connect
passphrase,
File "/home/username/.local/lib/python2.7/site-packages/paramiko/client.py", line 715, in _auth
raise SSHException('No authentication methods available')
paramiko.ssh_exception.SSHException: No authentication methods available
Simple code from docs (http://docs.fabfile.org/en/latest/getting-started.html):
from fabric import Connection
res = Connection('<host-ip>')
res.run('uname -s')
Accoding to docs, I don't need in special configs, but it's doesn't work...
fabric 2.1.3
python 2.7.14

Following works for me.
connect_kwargs = {"key_filename":['PATH/KEY.pem']}
with Connection(host="EC2", user="ubuntu", connect_kwargs=connect_kwargs) as c:
c.run("mkdir abds")

I run into the same issue. Rather than passing a SSH keyfile, as suggested previously, another trivial way to sort it out might be to pass a password (that would be fine just over the test/development stage).
import getpass
from fabric import Connection, Config
sudo_pass = getpass.getpass("What's your user password?\n")
config = Config(overrides={'user': '<host-user>', 'connect_kwargs': {'password': sudo_pass}})
c = Connection('<host-ip>', config=config)
c.run('uname -s')

Related

Nornir Netmiko connection to AWS EC2 Cisco IOS-XE router fails - can't connect because of SSH Key?

I try to connect via Nornir / Netmiko to an Cisco CSR1k Router. In AWS keys are used and the EC2-USER expect a key authentication.
This is my simple test Nornir Script:
from nornir_netmiko import netmiko_send_config, netmiko_send_command
from nornir import InitNornir
from nornir_utils.plugins.functions import print_result
from nornir.core.filter import F
nr = InitNornir(config_file="config.yaml")
cisco = nr.filter(F(platform="cisco_xe"))
result = cisco.run(
task=netmiko_send_command,
command_string="show arp"
)
print_result(result)
And this is my Inventroy:
---
Europe-Cisco-Site1:
hostname: "18.158.60.42"
username: "ec2-user"
password: ""
platform: "cisco_xe"
groups:
- cisco
I would expect that Nornir will handle the authentication automatically and use the keys. It seams this is not happening.
When I try to connect via ssh from the same host to the AWS EC2 Cisco CSR1k everthing works.
Question:
Do I need to give some extra options to use the SSH key?
I found something like this but it does not work:
connection_options:
paramiko:
port: 22
hostname:
username: "ec2-user"
password:
platform: "cisco_xe"
extras:
alt_host_keys: True
alt_key_file: "/home/coder/.ssh/id_rsa"
use_keys: True
And this is the error what I get:
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/coder/.local/lib/python3.8/site-packages/nornir/core/task.py", line 99, in start
r = self.task(self, **self.params)
File "/home/coder/.local/lib/python3.8/site-packages/nornir_netmiko/tasks/netmiko_send_command.py", line 26, in netmiko_send_command
net_connect = task.host.get_connection(CONNECTION_NAME, task.nornir.config)
File "/home/coder/.local/lib/python3.8/site-packages/nornir/core/inventory.py", line 494, in get_connection
self.open_connection(
File "/home/coder/.local/lib/python3.8/site-packages/nornir/core/inventory.py", line 546, in open_connection
conn_obj.open(
File "/home/coder/.local/lib/python3.8/site-packages/nornir_netmiko/connections/netmiko.py", line 59, in open
connection = ConnectHandler(**parameters)
File "/home/coder/.local/lib/python3.8/site-packages/netmiko/ssh_dispatcher.py", line 326, in ConnectHandler
return ConnectionClass(*args, **kwargs)
File "/home/coder/.local/lib/python3.8/site-packages/netmiko/cisco/cisco_ios.py", line 17, in __init__
return super().__init__(*args, **kwargs)
File "/home/coder/.local/lib/python3.8/site-packages/netmiko/base_connection.py", line 350, in __init__
self._open()
File "/home/coder/.local/lib/python3.8/site-packages/netmiko/base_connection.py", line 355, in _open
self.establish_connection()
File "/home/coder/.local/lib/python3.8/site-packages/netmiko/base_connection.py", line 972, in establish_connection
raise NetmikoAuthenticationException(msg)
netmiko.ssh_exception.NetmikoAuthenticationException: Authentication to device failed.
Common causes of this problem are:
1. Invalid username and password
2. Incorrect SSH-key file
3. Connecting to the wrong device
Device settings: cisco_xe 3.121.222.37:22
What I'm missing here?
Found the solution, this was missing in the inventory file:
connection_options:
netmiko:
extras:
use_keys: true
key_file: "/home/coder/.ssh/id_rsa"

Error when connecting to ESXI through python vsphere API

I am creating a script that asks the user for the FQDN of a host, then the script sets that host to maintenance mode. I am running the script on the Windows Management Computer that is obviously connected to the esxi-vcsa that has these hosts on it. 11.11.11.5 is the IP of the vcsa.
from pyvim import connect
from pyVmomi import vim
fqdnInput = input("Enter FQDN of host: ")
host = connect.ConnectNoSSL("11.11.11.5", 443, root, lassword)
searcher = host.content.searchIndex
host = searcher.FindByDnsName(dnsName=fqdnInput, vmSearch=False)
host.EnterMaintenanceMode(0)
When I run that script, I am getting the following error after I input the FQDN name. (I tried both just the host name and host.domain full name).
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\task4.py", line 14, in <module>
host = connect.ConnectNoSSL("11.11.11.5", 443, "root", "Pa$$w0rd")
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-packages\pyvim\connect.py", line 308, in ConnectNoSSL
mechanism=mechanism)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-packages\pyvim\connect.py", line 266, in Connect
keyFile, certFile, thumbprint, sslContext, connectionPoolTimeout)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-packages\pyvim\connect.py", line 390, in __Login
x = content.sessionManager.Login(user, pwd, None)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-packages\pyVmomi\VmomiSupport.py", line 706, in <lambda>
self.f(*(self.args + (obj,) + args), **kwargs)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-packages\pyVmomi\VmomiSupport.py", line 512, in _InvokeMethod
return self._stub.InvokeMethod(self, info, args)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-packages\pyVmomi\SoapAdapter.py", line 1397, in InvokeMethod
raise obj # pylint: disable-msg=E0702
pyVmomi.VmomiSupport.NoPermission: (vim.fault.NoPermission) {
dynamicType = <unset>,
dynamicProperty = (vmodl.DynamicProperty) [],
msg = 'Permission to perform this operation was denied.',
faultCause = <unset>,
faultMessage = (vmodl.LocalizableMessage) [],
object = 'vim.Folder:group-d1',
privilegeId = 'System.View'
}
Help would be appreciated.
It looks like you're dealing with a permissions issue and not a Python issue. I'm going to guess that the searcher is failing, meaning that the account you're using does not have access to the vCenter inventory at all.
Have you tried switching to a different account?
Perhaps the "Administrator#vsphere.local" account?

How to solve "paramiko.ssh_exception.SSHException: could not get keys from ssh-agent"

I'm trying to connect to remote server through SSH using Paramiko Python module. Installed using Python version 3.6.7 on CentOS 7 server. But getting this following error.
python
import paramiko
>>> ssh = paramiko.SSHClient()
>>> ssh.load_system_host_keys()
>>> ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
>>> ssh.connect("19.16.2.2", username="user1", password="pass")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/site-packages/paramiko/client.py", line 424, in connect
passphrase,
File "/usr/local/lib/python3.6/site-packages/paramiko/client.py", line 643, in _auth
self._agent = Agent()
File "/usr/local/lib/python3.6/site-packages/paramiko/agent.py", line 372, in __init__
self._connect(conn)
File "/usr/local/lib/python3.6/site-packages/paramiko/agent.py", line 68, in _connect
raise SSHException('could not get keys from ssh-agent')
paramiko.ssh_exception.SSHException: could not get keys from ssh-agent
Note that I don't want to use the SSH agent, just the Paramiko module alone.
I googled and tried the following solutions. Still I was not able to resolve this issue. Would appreciate if provided a solution. Thanks in advance.
https://myroughnotes.wordpress.com/2017/03/19/fabric-could-not-get-keys-from-ssh-agent/
https://access.redhat.com/solutions/3571001
https://unix.stackexchange.com/questions/82489/how-to-check-which-ssh-keys-are-currently-active
# eval ssh-agent -s
SSH_AUTH_SOCK=/tmp/ssh-PycvG5kzoTjt/agent.26174; export SSH_AUTH_SOCK;
SSH_AGENT_PID=26175; export SSH_AGENT_PID;
If you do not want to use authentication agent, you can avoid Paramiko trying to contact it using allow_agent argument of SSHClient.connect:
ssh.connect("19.16.2.2", username="user1", password="pass", allow_agent=False)

GCS boto authentication on RPi

I have this simple script that spits out the buckets in my GCS:
import boto
import gcs_oauth2_boto_plugin
import os
import shutil
import StringIO
import tempfile
import time
# URI scheme for Cloud Storage.
GOOGLE_STORAGE = 'gs'
# URI scheme for accessing local files.
LOCAL_FILE = 'file'
header_values = {"x-goog-project-id": "xxxxxxxxxxxx"}
uri = boto.storage_uri('', GOOGLE_STORAGE)
for bucket in uri.get_all_buckets(headers=header_values):
print bucket.name
The top of my ~/.boto file has the following (with real values for everything inside brackets):
# Google OAuth2 service account credentials (for "gs://" URIs):
gs_service_key_file = /home/pi/dev/camera/cl-camera-<id>.json
gs_service_client_id = '<user>#<id>.iam.gserviceaccount.com'
Everything works fine when running without sudo, but once I add sudo (I need access to GPIO pins since this is on a RPi), I get the following error:
Traceback (most recent call last):
File "gcs-test.py", line 24, in <module>
for bucket in uri.get_all_buckets(headers=header_values):
File "/usr/local/lib/python2.7/dist-packages/boto/storage_uri.py", line 584, in get_all_buckets
conn = self.connect()
File "/usr/local/lib/python2.7/dist-packages/boto/storage_uri.py", line 140, in connect
**connection_args)
File "/usr/local/lib/python2.7/dist-packages/boto/gs/connection.py", line 47, in __init__
suppress_consec_slashes=suppress_consec_slashes)
File "/usr/local/lib/python2.7/dist-packages/boto/s3/connection.py", line 191, in __init__
validate_certs=validate_certs, profile_name=profile_name)
File "/usr/local/lib/python2.7/dist-packages/boto/connection.py", line 569, in __init__
host, config, self.provider, self._required_auth_capability())
File "/usr/local/lib/python2.7/dist-packages/boto/auth.py", line 1021, in get_auth_handler
'Check your credentials' % (len(names), str(names)))
boto.exception.NoAuthHandlerFound: No handler was ready to authenticate. 3 handlers were checked. ['OAuth2Auth', 'OAuth2ServiceAccountAuth', 'HmacAuthV1Handler'] Check your credentials
Any ideas as to what's happening and why it's only when I run it with sudo?
I figure this one out. Since I'm running it as root now, it looks for the .boto file in a different place (/root/.boto instead of /home/pi/.boto), so I did the following to create a new config file and it worked:
$ sudo su
$ gsutil config -e

error 10054 while trying to download binary file through ftp in python 2.7

I'm pretty new to python, so this very well be user error here, but I'm not quite sure what to do from here.
I'm trying to login to a zyxel gs2200 switch via ftp and download it's config file.
The command through cmd ftp is
get config X.log where X.log is whatever you decide to name it.
In python I can log in just fine, but I can not download a file without throwing an exception.
import ftplib
ftp = ftplib.FTP("my.ip.here")
ftp.login('user','Pass')
'230 Logged in'
ftp.retrbinary('RETR config', open('config', 'wb').write)
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
File "C:\Python27\lib\ftplib.py", line 398, in retrbinary
self.voidcmd('TYPE I')
File "C:\Python27\lib\ftplib.py", line 248, in voidcmd
self.putcmd(cmd)
File "C:\Python27\lib\ftplib.py", line 178, in putcmd
self.putline(line)
File "C:\Python27\lib\ftplib.py", line 173, in putline
self.sock.sendall(line)
File "C:\Python27\lib\socket.py", line 222, in meth
return getattr(self._sock,name)(*args)
error: [Errno 10054] An existing connection was forcibly closed by the remote host
I've also tried opening a file before and then just calling it in the method, but it still gives the same error.
does anyone have any idea on how I can get these config files in python?
I Can tell you easy method to do this.
Ftp Login Url: ftp://username:password#hostname/
Username: your Username
Password: Your Password
To download a file from FTP server you could:
import urllib
urllib.urlretrieve('ftp://username:password#hostname/yourconfigname', 'yourconfigname')
In your case you can do something like this.
===============================================================
As for your problem the python error clearly indicating that you did not establish connection correctly(Always Close Connection) or May be your destination had already connected to maximum destinations thats why your target destination closing your connection.

Categories