Difficulty in connecting to SFTP server with Python and Flask? - python

I am trying to connect to an SFTP server but I am getting an error:
pysftp.exceptions.ConnectionException: ('NAMEOFSERVER#sftp.NAMEOFHOST.gov', 22)
I have no clue why this is happening, here is the portion of the code that is causing problems:
myHostname = "NAMEOFHOST"
myUsername = "" #there is no username
myPassword = "PASSWORD"
import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
with pysftp.Connection(host=myHostname, username=myUsername, password=myPassword,cnopts=cnopts) as sftp:
print ("Connection succesfully stablished ... ")
Any help is appreciated, thank you!

If there is no username, why don't you put None, instead of an empty string. None != ""
So:
myHostname = "NAMEOFHOST"
myPassword = "PASSWORD"
import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
with pysftp.Connection(host=myHostname, password=myPassword,cnopts=cnopts) as sftp:
print ("Connection succesfully stablished ... ")
Give it a try and say whether this solves your issue.

Related

list files inside SFTP with Python to download files listdir

I have to download some files from sftp using Python, I've tried to use listdir to list all of them, but my first attempt to use pysftp.listdir I receive this message :
"module 'pysftp' has no attribute 'listdir'
import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
myHostname = "99.99.999.999"
myUsername = "user"
myPassword = "*********"
with pysftp.Connection(host=myHostname, username=myUsername, password=myPassword,cnopts=cnopts) as sftp:
print("Connection succesfully stablished ... ")
pysftp.cd('public')
pysftp.listdir()
Change:
pysftp.cd('public')
pysftp.listdir()
To:
sftp.cd('public')
sftp.listdir()
Since you are using the with keyword and then as sftp, that means you should use sftp.lisdir().

Download large files using pysftp

I have a file >500 MB to download using sftp connection, I tried using pysptp and getting error SSHException: Server connection dropped:
import pysftp
import sys
myHostname = "dbfiles.xyz.org"
myUsername = "XXXX"
myPassword = "YYYY"
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
with pysftp.Connection(host=myHostname, username=myUsername, password=myPassword,cnopts=cnopts) as sftp:
print("Connection succesfully stablished ... ")
localFilePath = 'c:/....'
remoteFilePath = sftp.listdir('/folder/')
for filename in remoteFilePath:
if 'string_to_match' in filename:
local_path = localFilePath + filename
print (filename)
print (local_path)
sftp.get("folder/" + filename, local_path)
And getting SSHException: Server connection dropped: EOF error after 18MB of file is downloaded. Is there any way I can put limit on amount to data downloaded or can delay this get process in order to get full file, i tried several ways but because of large file size, unable to download complete file. Any help appreciated.
Go to Paramiko library in stfp_file.py and change the MAX_REQUEST_SIZE to 1024. It worked for me. You can find the package here:
/home//.local/lib/python3.8/site-packages/paramiko/sftp_file.py

PySFTP put not always puts files, is it a coding problem?

So recently I wrote a code that put files from one folder to an SFTP folder. It works generally, but many times it fails to upload the data, and I have no clue way. Do you have any tips?
import os
import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
#Set these to make the code run
shared_aim_fd='' #the folder where you copy from
sftp_user=''
sftp_pw=''
sftp_site=''
sftp_folder_name='' #where you want to copy to
for od_files in os.listdir(shared_aim_fd):
myUsername =str(sftp_user)
myPassword =str(sftp_pw)
myHostname=str(sftp_site)
mySFTPFolderName=str(sftp_folder_name)
try:
with pysftp.Connection(host=myHostname, username=myUsername, password=myPassword, cnopts=cnopts) as sftp:
print ("Connection succesfully stablished ... ")
#Make sure we have the folder where we want to push it
if not sftp.isdir(mySFTPFolderName):
#if not, then create one
sftp.makedirs(mySFTPFolderName)
sftp.put(shared_aim_fd+od_files,str(mySFTPFolderName+'/'+od_files))
sftp.close()
except:
print("Upload failed")
pass

I want to copy a .wav file from my current system to linux server using python

Any one have idea then please suggest, This is how I'm doing now. bt not working.
Here I'm trying to copy my newtext.wav file to server location.
def copyToServer():
success = os.system("scp D:/AMRITESH/ContractMonitoring/newtext.wav
root#xxx.xxx.x.xxx:/usr/share/asterisk/sounds")
if (success != True):
print(success)
print "Connection Error"
else:
print "Connection Established"
def createSSHClient(server, port, user, password):
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(server, port, user, password)
print "Connection Established Here"
return client
ssh = createSSHClient('xxx.xxx.x.xxx', 'xx', 'username', 'password')
scp = SCPClient(ssh.get_transport())
print "Sending file to server"
scp.put('D:/AMRITESH/ContractMonitoring/'+fileName, '/usr/share/asterisk/sounds')

python ssh(paramiko) fail to connect to remote machine without password?

I want to connect to my remote machine with python module paramsiko. First, I try with password, it is ok, like this:
import paramiko
import socket
import os
paramiko.util.log_to_file('demo_sftp.log')
username = 'xxxxx'
hostname = 'dev81'
Port = 22
password = "xxxxx"
t = paramiko.Transport((hostname, Port))
t.connect(None, username, password)
sftp = paramiko.SFTPClient.from_transport(t)
# dirlist on remote host
dirlist = sftp.listdir('.')
print("Dirlist: %s" % dirlist)
then I want to remove password, use key, according to demo in demo_sftp like this:
import paramiko
import socket
import os
paramiko.util.log_to_file('demo_sftp.log')
username = 'xxxxx'
hostname = 'dev81'
Port = 22
password = None
host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
hostkeytype = host_keys[hostname].keys()[0]
hostkey = host_keys[hostname][hostkeytype]
print('Using host key of type %s' % hostkeytype)
t = paramiko.Transport((hostname, Port))
t.connect(hostkey, username, password, gss_host=socket.getfqdn(hostname),
gss_auth=True, gss_kex=True)
sftp = paramiko.SFTPClient.from_transport(t)
# dirlist on remote host
dirlist = sftp.listdir('.')
print("Dirlist: %s" % dirlist)
This fail with Exception paramiko.ssh_exception.BadAuthenticationType: ('Bad authentication type', [u'publickey', u'password']) (allowed_types=[u'publickey', u'password'])
And I can login with command ssh xxxxx#dev81 without password
If you Have passphrase for the Key pair
It throws this error
paramiko.ssh_exception.BadAuthenticationType: ('Bad authentication type', [u'publickey', u'password']) (allowed_types=[u'publickey', u'password'])
To Resolve this
ssh.connect('<your ip>', port=22, username='<username>',password='<passphrase for the RSA key>', key_filename='<full path of the private key>')

Categories