SSHClient paramiko Python? - python

I use this method to send file to remote server:
def runSendArchive(host, port, username, password, remote_directory, archive):
try:
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect(host, username, password, port)
sftp = s.open_sftp()
sftp.put(archive, remote_directory)
print "3 - The file was uploaded via SSH!"
except (BadHostKeyException, AuthenticationException, SSHException, socket.error) as e:
print "4 - Error! The file was not uploaded: ", e
It returns me an exception:
except (BadHostKeyException, AuthenticationException, SSHException, socket.error) as e: NameError: global name
'BadHostKeyException' is not defined
How to use this library right?
Now I get the following error:
File "run.py", line 65, in runSendArchive
sftp.put(archive, remote_directory)
File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 721, in put
return self.putfo(fl, remotepath, file_size, callback, confirm)
File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 677, in putfo
with self.file(remotepath, 'wb') as fr:
File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 338, in open
t, msg = self._request(CMD_OPEN, filename, imode, attrblock)
File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 774, in _request
return self._read_response(num)
File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 826, in _read_response
self._convert_status(msg)
File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 859, in _convert_status
raise IOError(text)
IOError: Failure
65 line is sftp.put(archive, remote_directory)

Judging from the line
paramiko.SSHClient()
you are calling import paramiko
Since BadHostKeyException is in paramiko.ssh_exception, you need to add an
from paramiko.ssh_exception import BadHostKeyException, AuthenticationException, SSHException
See http://docs.paramiko.org/en/2.3/api/ssh_exception.html
paramiko.ssh_exception.BadHostKeyException
paramiko.ssh_exception.AuthenticationException
paramiko.ssh_exception.SSHException
reside in that module.
For your example code snippet you would need to add the following before the runSendArchive function
import socket
import paramiko
from paramiko.ssh_exception import BadHostKeyException, AuthenticationException, SSHException

Related

Can't upload file to sftp server with Paramiko Python [duplicate]

This question already has an answer here:
Uploading file via Paramiko SFTP not working
(1 answer)
Closed 2 years ago.
I want to upload a file to a SFTP server using Paramiko, but I don't seem to get it right.
I thought I got the respective error cause of the file path '/' witch is the root on the server but I didn't get anywhare.
I keep getting this error:
File "c:\python\whitelistBot\whitelistBot.py", line 63, in on_message
sftp_client.put('C:/python/whitelistBot/whitelist1.json', '/')
File "C:\python\whitelistBot\lib\site-packages\paramiko\sftp_client.py", line 759, in put
return self.putfo(fl, remotepath, file_size, callback, confirm)
File "C:\python\whitelistBot\lib\site-packages\paramiko\sftp_client.py", line 714, in putfo
with self.file(remotepath, "wb") as fr:
File "C:\python\whitelistBot\lib\site-packages\paramiko\sftp_client.py", line 372, in open
t, msg = self._request(CMD_OPEN, filename, imode, attrblock)
File "C:\python\whitelistBot\lib\site-packages\paramiko\sftp_client.py", line 813, in _request
return self._read_response(num)
File "C:\python\whitelistBot\lib\site-packages\paramiko\sftp_client.py", line 865, in _read_response
self._convert_status(msg)
File "C:\python\whitelistBot\lib\site-packages\paramiko\sftp_client.py", line 898, in _convert_status
raise IOError(text)
OSError: Operation Unsupported
The code I'm running:
import paramiko
FTP_HOST = "********"
FTP_USER = "********"
FTP_PASS = "********"
FTP_PORT = ****
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname= FTP_HOST, username=FTP_USER, password=FTP_PASS, port=FTP_PORT)
sftp_client = ssh_client.open_sftp()
sftp_client.put('C:/python/whitelistBot/whitelist1.json', '/')
sftp_client.close()
ssh_client.close()
EDIT: I changed the directory where to put the file to "/home/container" cause that's what they told me in the site but except for the fact that I don't get that error message, the file does not appear on the server
Looks like I had to specify the name of the file '/whitelist1.json' like so:
sftp_client.put('C:/python/whitelistBot/whitelist1.json', '/whitelist1.json') # don't know why but yeah

How to fetch sizes of all SFTP files in a directory through Paramiko

import paramiko
from socket import error as socket_error
import os
server =['10.10.0.1','10.10.0.2']
path='/home/test/'
for hostname in server:
try:
ssh_remote =paramiko.SSHClient()
ssh_remote.set_missing_host_key_policy(paramiko.AutoAddPolicy())
privatekeyfile = os.path.expanduser('~/.ssh/id')
mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile, password='test123')
ssh_remote.connect(hostname, username = 'test1', pkey = mykey)
sftp=ssh_remote.open_sftp()
for i in sftp.listdir(path):
info = sftp.stat(i)
print info.st_size
except paramiko.SSHException as sshException:
print "Unable to establish SSH connection:{0}".format(hostname)
except socket_error as socket_err:
print "Unable to connect connection refused"
This is my code. I tried to get file size of remote server files. But below error was throwing. Can some please guide on this?
Error
Traceback (most recent call last):
File "<stdin>", line 15, in <module>
File "/usr/lib/python2.6/site-packages/paramiko/sftp_client.py", line 337, in stat
t, msg = self._request(CMD_STAT, path)
File "/usr/lib/python2.6/site-packages/paramiko/sftp_client.py", line 624, in _request
return self._read_response(num)
File "/usr/lib/python2.6/site-packages/paramiko/sftp_client.py", line 671, in _read_response
self._convert_status(msg)
File "/usr/lib/python2.6/site-packages/paramiko/sftp_client.py", line 697, in _convert_status
raise IOError(errno.ENOENT, text)
IOError: [Errno 2] No such file
SFTPClient.listdir returns file names only, not a full path. So to use the filename in another API, you have to add a path:
for i in sftp.listdir(path):
info = sftp.stat(path + "/" + i)
print info.st_size
Though that's inefficient. Paramiko knows the size already, you are just throwing the information away by using SFTPClient.listdir instead of SFTPClient.listdir_attr (listdir calls listdir_attr internally).
for i in sftp.listdir_attr(path):
print i.st_size

paramiko sftp script works on test server not on production

I'm a newb at python, so please excuse the hack job I created in order to transfer the contents of a folder into an ssh server.
The problem is that it works great in my test server, but as soon as run it against the actual server that I need to upload files for I receive the error below, and I'm not sure what it means.
I've googled it, but I can't figure it out, please help.
Thanks.
import paramiko
import glob
import os
from shutil import move
host = "192.168.1.87" #hard-coded
port = 22
password ="passwd" #hard-coded
username = "administator" #hard-coded
remotepath ='' #hard-coded
localpath = 'D:\\PH/PH_PROD\\PowerConnectInterf1_WINS\\bin\\data\\Sheex\\bc\\945\\'
#build filename array
os.chdir("D:/PH/PH_PROD/PowerConnectInterf1_WINS/bin/data/Sheex/bc/945")
filelist=[]
for files in glob.glob( "2016*" ):
f = open(files, 'r')
filelist.append(f.name)
f.close()
if (len(filelist)>0):
transport = paramiko.Transport((host, port))
transport.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(transport)
for s in filelist:
#print remotepath+s
sftp.put(localpath+s,remotepath+s)
#os.rename(localpath+s,localpath+"945back/"+s)
sftp.close()
transport.close()
#print 'Upload done.'
Error:
D:\Scripts>python mysftp.py
Traceback (most recent call last):
File "mysftp.py", line 37, in <module>
sftp.put(localpath+s,remotepath+s)
File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 676, in put
return self.putfo(fl, remotepath, file_size, callback, confirm)
File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 634, in put
fo
with self.file(remotepath, 'wb') as fr:
File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 327, in ope
n
t, msg = self._request(CMD_OPEN, filename, imode, attrblock)
File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 730, in _re
quest
return self._read_response(num)
File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 781, in _re
ad_response
self._convert_status(msg)
File "C:\Python27\lib\site-packages\paramiko\sftp_client.py", line 807, in _co
nvert_status
raise IOError(errno.ENOENT, text)
IOError: [Errno 2] Invalid file ID
It sounds like the path you are writing on the server doesn't exist. You should check and create if doesn't exist.

error 501 on ftp.retrbinary (ftplib)

I'm coding a script to check a FTP directory and download the new files. This is part of the code:
from ftplib import FTP
import os
ftp = FTP(ftp_lance)
ftp.login(login, password)
ftp.cwd('xxxxxx')
FTP_list = ftp.nlst()
lista_diferenca = [file for file in FTP_list if file not in local_list]
for file in lista_diferenca:
local_filename = os.path.join(cache, file)
ftp.retrbinary('REST ' + file, open(local_filename, 'wb').write)
When I run it, I get this error message:
Traceback (most recent call last):
File "D:\Scripts\Istari\Radagast\Radagast.py", line 44, in <module>
ftp.retrbinary('REST tabela14_pag5.pdf', open(local_filename, 'wb').write)
File "D:\Portable Python 2.7.6.1\App\lib\ftplib.py", line 414, in retrbinary
conn = self.transfercmd(cmd, rest)
File "D:\Portable Python 2.7.6.1\App\lib\ftplib.py", line 376, in transfercmd
return self.ntransfercmd(cmd, rest)[0]
File "D:\Portable Python 2.7.6.1\App\lib\ftplib.py", line 339, in ntransfercmd
resp = self.sendcmd(cmd)
File "D:\Portable Python 2.7.6.1\App\lib\ftplib.py", line 249, in sendcmd
return self.getresp()
File "D:\Portable Python 2.7.6.1\App\lib\ftplib.py", line 224, in getresp
raise error_perm, resp
error_perm: 501 Bad parameter. Numeric value required
I check several sites searching for this kind of error and find nothing. It seems that my retrbinaty is broken, but the arguments looks right (first the 'Rest' + file, and then the callback function).
Some idea about my error?
You need to specify the FTP command RETR, not REST:
ftp.retrbinary('RETR ' + file, open(local_filename, 'wb').write)

'put' in SFTP using Paramiko

I've installed and written the following Paramiko which is unable to put the file. It is easily able to 'get' a file and execute ls commands on it.
#set username & password
username='runaway'
password='runaway'
port=22
source= '/Unzip.sh'
destination ='/var/mpx/www/http'
#SFTP
client.load_system_host_keys()
print " hostname =%s \n username=%s \n password=%s \n" (hostname,username,password)
t = paramiko.Transport((hostname, port))
t.connect(username=username,password=password)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put(source,destination)
#sftp.close()
#t.close()
Using a 'put' command gives the following error & stack trace -
File "upload_file.py", line 84, in ?
sftp.put(source,destination)
File "/usr/lib/python2.4/site-packages/paramiko/sftp_client.py", line 522, in put
fr = self.file(remotepath, 'wb')
File "/usr/lib/python2.4/site-packages/paramiko/sftp_client.py", line 221, in open
t, msg = self._request(CMD_OPEN, filename, imode, attrblock)
File "/usr/lib/python2.4/site-packages/paramiko/sftp_client.py", line 572, in _request
return self._read_response(num)
File "/usr/lib/python2.4/site-packages/paramiko/sftp_client.py", line 619, in _read_response
self._convert_status(msg)
File "/usr/lib/python2.4/site-packages/paramiko/sftp_client.py", line 649, in _convert_status
raise IOError(text)
IOError: Failure
How do I overcome this?
The solution seemed very funny to me!
source= '/Unzip.sh'
destination ='/var/mpx/www/http/Unzip.sh'
Just modified the destination path to include the file name as well.
Didn't expect some error like this coming from a Python package.
This also occurs in 2.0.2 when you try to sftp.mkdir('/exists'):
Traceback (most recent call last):
...
File "/usr/local/lib/python2.7/site-packages/paramiko/sftp_client.py", line 380, in mkdir
self._request(CMD_MKDIR, path, attr)
File "/usr/local/lib/python2.7/site-packages/paramiko/sftp_client.py", line 730, in _request
return self._read_response(num)
File "/usr/local/lib/python2.7/site-packages/paramiko/sftp_client.py", line 781, in _read_response
self._convert_status(msg)
File "/usr/local/lib/python2.7/site-packages/paramiko/sftp_client.py", line 811, in _convert_status
raise IOError(text)
IOError: Failure
This was my Python 2.7.9 fix:
try:
sftp.mkdir(remote_dir)
except IOError:
logging.debug('%s already exists.', remote_dir)

Categories