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

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?

Related

Paramiko SSH command execution failing with `ValueError: [digital envelope routines: EVP_DigestInit_ex] disabled for FIPS`

Executing a command on remote machine using SSH is failing with the below error:
Traceback (most recent call last):
File "ssh.py", line 4, in <module>
ssh_client.connect(hostname='10.x.x.x', username='admin', password='password')
File "/usr/lib/python3.6/site-packages/paramiko/client.py", line 407, in connect
self, server_hostkey_name, server_key
File "/usr/lib/python3.6/site-packages/paramiko/client.py", line 790, in missing_host_key
key.get_name(), hostname, hexlify(key.get_fingerprint())
File "/usr/lib/python3.6/site-packages/paramiko/pkey.py", line 151, in get_fingerprint
return md5(self.asbytes()).digest()
ValueError: [digital envelope routines: EVP_DigestInit_ex] disabled for FIPS
The code snippet I'm using is as follows:
import paramiko
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname='10.x.x.x', username='admin', password='password')
command = "sudo sh ~/script.sh"
ssh_client.exec_command(command)
I was facing this error too.
This is because Paramiko uses MD5 encryption and the machine you want to connect to use FIPS, FIPS not allowed MD5 anymore.
So there is open PR in the Paramiko project.
In this issue above someone named neutronscott suggested editing the Pkey.py file.
Instead
return md5(self.asbytes()).digest()
Change to
return md5(self.asbytes(), usedforsecurity=False).digest()
So we can do something called 'Monkey patching'
Monkey patching is a technique to add, modify, or suppress the default behavior of a piece of code at runtime without changing its original source code.
This is worked for me:
class _PkeyChild(paramiko.PKey):
def get_fingerprint_improved(self):
"""
Declare that the use of MD5 encryption is not for security purposes.
This declaration is to overcome connection to servers with FIPS security standards.
"""
return md5(self.asbytes(), usedforsecurity=False).digest()
...
paramiko.PKey.get_fingerprint = _PkeyChild.get_fingerprint_improved
connection = paramiko.SSHClient()
connection.set_missing_host_key_policy(paramiko.AutoAddPolicy())
connection.connect(hostname="host_name", username="username", password="password")

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.

Python SSH Connection with Paramiko & Netmiko libs

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

Creating and logging into a linux virtual machine in automation with python

I currently have a working python script that SSHs into a remote Linux machine and executes commands on that machine. I'm using paramiko to handle ssh connectivity. Here is the code in action, executing an hostname -s command:
blade = '192.168.1.15'
username='root'
password=''
# now, connect
try:
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
print '*** Connecting...'
client.connect(blade, 22, username, password)
# print hostname for verification
stdin, stdout, stderr = client.exec_command('hostname --short')
print stdout.readlines()
except Exception, e:
print '*** Caught exception: %s: %s' % (e.__class__, e)
traceback.print_exc()
try:
client.close()
except:
pass
sys.exit(1)
This works fine, but what I'm actually trying to do is more complicated. What I would actually like to do is SSH into that same Linux machine, as I did above, but then create a temporary virtual machine on it, and execute a command on that virtual machine. Here is my (nonworking) attempt:
blade='192.168.1.15'
username='root'
password=''
# now, connect
try:
# client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
print '*** Connecting...'
client.connect(blade, 22, username, password)
# create VM, log in, and print hostname for verification
stdin, stdout, stderr = client.exec_command('sudo kvm -m 1024 -drive file=/var/lib/libvirt/images/oa4-vm$
time.sleep(60) #delay to allow VM to initialize
stdin.write(username + '\n') #log into VM
stdin.write(password + '\n') #log into VM
stdin, stdout, stderr = client.exec_command('hostname --short')
print stdout.readlines()
except Exception, e:
print '*** Caught exception: %s: %s' % (e.__class__, e)
traceback.print_exc()
try:
client.close()
except:
pass
sys.exit(1)
When I run this, I get the following:
joe#computer:~$ python automata.py
*** Connecting...
/home/joe/.local/lib/python2.7/site-packages/paramiko/client.py:95: UserWarning: Unknown ssh-rsa host key for 192.168.1.15: 25f6a84613a635f6bcb5cceae2c2b435
(key.get_name(), hostname, hexlify(key.get_fingerprint())))
*** Caught exception: <class 'socket.error'>: Socket is closed
Traceback (most recent call last):
File "automata.py", line 32, in function1
stdin.write(username + '\n') #log into VM
File "/home/joe/.local/lib/python2.7/site-packages/paramiko/file.py", line 314, in write
self._write_all(data)
File "/home/joe/.local/lib/python2.7/site-packages/paramiko/file.py", line 439, in _write_all
count = self._write(data)
File "/home/joe/.local/lib/python2.7/site-packages/paramiko/channel.py", line 1263, in _write
self.channel.sendall(data)
File "/home/joe/.local/lib/python2.7/site-packages/paramiko/channel.py", line 796, in sendall
raise socket.error('Socket is closed')
error: Socket is closed
I'm not sure how to interpret this error -- "socket is closed" makes me think the SSH connection is terminating one I try to create the VM. Does anyone have any pointers?
update
I'm attempting to use the pexpect wrapper and having trouble getting it to interact with the un/pw prompt. I'm testing the process by ssh'ing into a remote machine and running a test.py script which prompts me for a username, then saves the username in a text file. Here is my fab file:
env.hosts = ['hostname']
env.user = 'userame'
env.password = 'password'
def vm_create():
run("python test.py")
And the contents of test.py on the remote machine are:
#! /usr/bin/env python
uname = raw_input("Enter Username: ")
f = open('output.txt','w')
f.write(uname + "\n")
f.close
So, I can execute "fab vm_create" on the local machine and it successfully establishes the SSH connection and prompts me for the username, as defined by test.py. However, if I execute a third python file on my local machine with the pexpect wrapper, like this:
import pexpect
child = pexpect.spawn('fab vm_create')
child.expect ('Enter Username: ')
child.sendline ('password')
Nothing seems to happen. I get no errors, and no output.txt is created on the remote machine. Am I using pexpect incorrectly?
As much as I love paramiko, this may be better suited to using Fabric.
Here's a sample fabfile.py:
from fabric.api import run
from fabric.api import sudo
from fabric.api import env
env.user = 'root'
env.password = ''
env.host = ='192.168.1.15'
def vm_up():
sudo("kvm -m 1024 -drive file=/var/lib/libvirt/images/oa4-vm$...")
run("hostname --short")
To then run this, use
$ fab vm_up
If you don't set the host and password in the fabfile itself (rightly so), then you can set these at the command line:
$ fab -H 192.168.1.15 -p PASSWORD vm_up
However, your kvm line is still expecting input. To send input (and wait for the expected prompts), write another script that uses pexpect to call fab:
child = pexpect.spawn('fab vm_up')
child.expect('username:') # Put this in the format you're expecting
child.send('root')
use fabric http://docs.fabfile.org/en/1.8/
Fabric is a Python (2.5 or higher) library and command-line tool for streamlining the use of SSH for application deployment or systems administration tasks
from fabric.api import run
def host_name():
run('hostname -s')

Categories

Resources