I want to transfer a file from a local server (that'll contain the code and file) to a remote server preferably using ssh. Here's the code:
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('Servername', port = 135, username='username', password='password')
print "connected successfully!"
sftp = ssh.open_sftp()
print sftp
sftp.put('G:\TestDocument.txt','G:\TestDocument.txt' )
sftp.close()
print "copied successfully!"
ssh.close()
But I get this error:
No handlers could be found for logger "paramiko.transport"
Traceback (most recent call last): File
"C:/Python27/testtransfer.py", line 5, in
ssh.connect('Servername', port = 135, username='username', password='password') File
"C:\Python27\lib\site-packages\paramiko\client.py", line 392, in
connect
t.start_client(timeout=timeout) File "C:\Python27\lib\site-packages\paramiko\transport.py", line 545, in
start_client
raise e SSHException: Error reading SSH protocol banner
Can you tell me why am I receiving this error? I have purposely used port 135 because port 22 is closed on the target server and 135 (among others) is open.
You can even suggest some other way in which I can transfer files from one server to another using Python.
SSHException: Error reading SSH protocol banner
the error usually means the remote service was not a ssh service. try to make sure the service on port 135 is actually ssh.
And what's the OS on your server? Windows? if so you may need to setup a 3rd-part ssh server on your server. In my opinion if you need to copy files from windows to windows ftp is a much simpler solution. python has a built-in lib ftplib.
Related
I am running a python script - ssh.py on my local machine to transfer file and directory from one remote server (ip = 35.189.168.20) to another remote server (ip = 10.243.96.94)
This is how my code looks:
HOST = "35.189.168.207"
USER = "sovith"
PASS = "xxx"
destHost = "10.243.96.94"
destUser = "root"
destPass = "xxx"
#SSH Connection
client1=paramiko.SSHClient()
client1.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client1.connect(HOST,username=USER,password=PASS)
#SFTP inside SSH server connection
with pysftp.Connection(host=destHost, username=destUser, password=destPass) as sftp:
#put build directory - sftp.put_r(source, destination)
sftp.put_r('/home/sovith/build' , '/var/tmp')
sftp.close()
client1.close()
Let me just tell you that all directory paths and everything is correct. I just feel that there's some logically mistake inside the code. The output i got after execution is :
Traceback (most recent call last):
File "ssh.py", line 108, in <module>
func()
File "ssh.py", line 99, in func
sftp.put_r('/home/sovith/nfmbuild' , '/var/tmp')
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/pysftp/__init__.py", line 427, in put_r
os.chdir(localpath)
FileNotFoundError: [Errno 2] No such file or directory: '/home/sovith/build'
Can you just correct the mistake from my code or suggest any better method to accomplish the task. In simpler words, i want a script to copy files and directory between two remote server.
That's not possible. Not the way you do it. The fact that you open a connection to one remote server, does not make the following code magically work, as if it was executed on that server. It still runs on the local machine. So the code is trying to upload local files (which do not exist).
There's actually no way to transfer files between two remote SFTP servers from local machine.
In general, you will need to download the files from the first server to a local temporary directory. And then upload them to the second server.
See Python PySFTP transfer files from one remote server to another remote server
Another option is to connect to one remote server using SSH and then run SFTP client on the server to transfer the files to/from the second server.
But that's not copying from one SFTP server to another SFTP server. That's copying from one SSH server to SFTP server. You need an SSH access, mere SFTP access is not enough.
To execute a command of a remote SSH server, use pysftp Connection.execute. Though using pysftp to execute a command on a server is a bit overkill. You can use directly Paramiko instead:
Python Paramiko - Run command
(pysftp is just a wrapper around Paramiko with more advanced SFTP functions)
From your error message, can you confirm that the source directory /home/sovith/build (or /home/bgnanasekaran/nfmbuild) exists?
A good practice would be to check that before the call to sftp.put_r(), ie :
from pathlib import Path
d = Path('/home/sovith/build')
if d.exists():
sftp.put_r('/home/sovith/build' , '/var/tmp')
else:
print("Your source doesn't exist")
I wrote a generic script on Python that supports Windows and Unix ssh connection from Unix.
When I try Unix command from Unix to create dir in Windows, I get exit 53
/usr/bin/ssh2 --password pass -l admin ip_address mkdir "C:\Temp\ALEX_TEST_EX" &
When I write only /usr/bin/ssh2 --password pass -l admin ip_address, it is Ok. I login to Windows
When I try C:\Temp\ALEX_TEST_EX on this machine manually it is also Ok.
What is problem?
I also try to use with Python ssh2 command like
import paramiko
ssh = paramiko.SSHClient()
ssh.connect("ip_address", username="admin", password="pass")
but I get exceptions
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/python3.5/site-packages/paramiko/client.py", line 402, in connect
self, server_hostkey_name, server_key
File "/python3.5/site-packages/paramiko/client.py", line 768, in missing_host_key
'Server {!r} not found in known_hosts'.format(hostname)
paramiko.ssh_exception.SSHException: Server 'X.Y.Z.W' not found in known_hosts
You have not configued the client machine to allow you to know the server you are trying to connect to. You can either configure the client, or as a work around you can set the MissingHostKeyPolicy on paramiko like:
Code:
To warn when host not in known hosts:
ssh.set_missing_host_key_policy(paramiko.WarningPolicy)
To auto add host to know hosts:
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
Full Code:
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.WarningPolicy)
ssh.connect("localhost", username="admin", password="pass")
I am trying to connect to SFTP server using Paramiko in Python 2.7.
Here is my code:
# Python 2.7
# -*- coding: utf-8 -*-
import paramiko
# Connect to Server
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('ip_address',port = 22,username='user',password='password')
I get this error:
Traceback (most recent call last):
File "C:\Python27\lib\socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 10061] No connection could be made because the target machine actively refused it
I have searched this issue in different places but still haven't found any decisions.
Port and other credentials to this server are correct. That's for sure, because I can connect to it through SFTP client FileZilla.
The code above is working from my personal machine, but it doesn't work from my corporate computer. That's why I think it's because of proxy.
Do you have any suggestions how can I go through proxy in this case?
I already have had environment variables
http_proxy='http://username:password#proxy:port'
https_proxy='https://username:password#proxy:port'
Any help would be valuable!
The Paramiko itself does not implement proxies.
You have to provide a custom implementation of a "socket" via the sock parameter of the connect method.
The httplib.HTTPConnection can be used as such implementation for HTTP proxies.
For some examples, see:
https://web.archive.org/web/20200208133623/https://www.adimian.com/blog/2014/10/paramiko-and-corporate-proxies/
How to ssh over HTTP proxy in Python Paramiko?
Hi I have this sample path "\10.81.67.162" which is a remote server (windows OS)
I want to be able to transfer files (local) to the remote server using paramiko in python.
I can make it work if the server is in linux.
This is my sample code
import paramiko
import base64
username = 'username'
password = 'password'
host = "10.81.67.162"
port = 22
transport = paramiko.Transport((host,port))
transport.connect(username = username, password = password)
stfp = paramiko.SFTPClient.from_transport(transport)
But having thhis error in windows:
Traceback (most recent call last):
File "ssh.py", line 9, in <module>
transport = paramiko.Transport((host,port))
File "build\bdist.win32\egg\paramiko\transport.py", line 289, in __init__
File "C:\Python27\lib\socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 10061] No connection could be made because the target machi
ne actively refused it
Python version 2.7
Paramiko version 1.7.5
Thanks!
There is no SSH server running on Windows. Thats why you are not able to connect.
Windows doesn't support SSH natively. You need to install third-party SSH server on your remote windows hosts like cygwin, bitwise ssh or freeSSHD.
Or if you are interested to run only commands on windows host then you can use winrm protocol which is natively supported by Windows. For this you need a python library pywinrm. I have used this and works fine:
https://github.com/diyan/pywinrm
If you're trying to connect to a network drive, you can use win_unc:
import os
from win_unc import UncCredentials, UncDirectory, UncDirectoryConnection
creds = UncCredentials('USERNAME', 'PASSWORD')
unc = UncDirectory(r'\\<computername>\c$', creds)
conn = UncDirectoryConnection(unc)
conn.connect()
print list(os.listdir(r'\\<computer_name>\c$\<folder>'))
I have an error on a script I have wrote since few months, it worked very good with a raspberry pi, but now with an orange pi I have this:
>>> import paramiko
>>> transport = paramiko.Transport("192.168.2.2", 22)
>>> transport.connect(username = "orangepi", password = "my_pass")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/paramiko/transport.py", line 978, in connect
self.start_client()
File "/usr/lib/python2.7/dist-packages/paramiko/transport.py", line 406, in start_client
raise e
paramiko.ssh_exception.SSHException: Incompatible ssh server (no acceptable macs)
I can connect in console with ssh without problem.
Somebody has an idea ?
You should check if any of those MACs algorithms are available on your SSH server (sshd_config, key: MACs) :
HMAC-SHA1
HMAC-MD5
HMAC-SHA1-96
HMAC-MD5-96.
They are needed in order for Paramiko to connect to your SSH server.
On your remote server, edit /etc/ssh/sshd_config and add a MACs line or append to the existing one, with one or more of hmac-sha1,hmac-md5,hmac-sha1-96,hmac-md5-96 (values are comma-separated), for example:
MACs hmac-sha1
Now restart sshd: sudo systemctl restart ssh.
If the above solutions do not work, you need to upgrade Paramiko as found out by this answer.