sFTP with SSH Key & Password in Python [duplicate] - python

This question already has answers here:
Multi-factor authentication (password and key) with Paramiko
(3 answers)
Closed last year.
Trying to use pysftp to pull files from an sFTP server that requires both ssh key & password for authentication without much luck. Can use pysftp with just key and just password, but it breaks when I attempt to use both. Hoping someone has some experience with this. Open to using a different library if that works better.
Error output is:
paramiko.ssh_exception.BadAuthenticationType: Bad authentication type; allowed types: ['publickey']
import pysftp
connection_host = '1.1.1.1'
connection_user = 'username'
connection_password = 'password'
connection_private_key = '/path/to/key'
connection_dir='/dir/on/remote/host'
with pysftp.Connection(host=connection_host, username=connection_user, password=connection_password, private_key=connection_private_key) as sftp:
files = sftp.listdir(remotepath=connection_dir)
for file in files:
print("found the following file: {}".format(file))
with sftp.cd(connection_dir):
sftp.get(file)

Working code if anyone runs into the same issue:
connection_host = '0.0.0.0'
connection_user = 'username'
connection_password = 'password'
connection_private_key = '/path/to/key.pem'
connection_dir='/remote/path'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
ssh.connect(connection_host, username=connection_user, password=connection_password, key_filename=connection_private_key)
sftp_client = ssh.open_sftp()
files = sftp_client.listdir(connection_dir)
sftp_client.chdir(connection_dir)
for file in files:
print("found the following file {}".format(file))
sftp_client.get(file,file)
if sftp_client:
sftp_client.close()
if ssh:
ssh.close()

Related

Paramiko sftp upload with ppk file [duplicate]

This question already has answers here:
How to ssh connect through Python Paramiko with ppk public key
(4 answers)
Closed 2 years ago.
I am trying to create a python script with Paramiko Lib to upload a file on sftp which uses a "ppk" file and a passphrase to connect.
Unfortunately I cant crack the document or found anything which can connect sftp with ppk files.
Additional details:
SFTP can manually be connected with Filezilla, WinSCP is not allowing it.
Here is the code I can go upto only. Please help!
k = paramiko.RSAKey.from_private_key_file("/key.ppk")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect( hostname = "ftp.example.com", username = "user", pkey = k,passphrase="somephrase" )
Well that's the least of the problems, I need to upload afterwards when it gets connected.
i suggest that you convert .ppk to .pem !
see :
Conver ppk to pem
then like this :
import paramiko
k = paramiko.RSAKey.from_private_key_file("mykey.pem")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
print "connecting"
c.connect( hostname = "www.host.com", username = "ubuntu", pkey = k )
print "connected"
commands = [ "/home/ubuntu/firstscript.sh", "/home/ubuntu/secondscript.sh" ]
for command in commands:
print "Executing {}".format( command )
stdin , stdout, stderr = c.exec_command(command)
print stdout.read()
print( "Errors")
print stderr.read()
c.close()

Unable to connect to a clients SFTP using Python? [duplicate]

This question already has answers here:
Verify host key with pysftp
(9 answers)
Closed 2 years ago.
I have previously connected to a clients SFTP through vb.net script with WinSCP which has worked successfully however I don't want to use WinSCP.
I am newish to Python but think for my overall goal for the project will be better suited using python.
What I believe I am missing is potentially a public key and/or my privatekey is in the wrong format.
Would really appreciate some help on this as I have been stuck for days trying different things.
import pysftp
myHostname = 'sftp.name.com'
myUsername = 'username'
myPassword = 'password'
myKey = 'C:\\PrivateKey.ppk'
with pysftp.Connection(host=myHostname, username=myUsername, private_key=myKey, private_key_pass=myPassword) as sftp:
Error received
UserWarning: Failed to load HostKeys from C:\Users\name\.ssh\known_hosts.
The library is trying to find the known_hosts file to do a host key check. You can disable it, but as is written in the docs, it is strongly discouraged.
import pysftp
myHostname = 'sftp.name.com'
myUsername = 'username'
myPassword = 'password'
myKey = 'C:\\PrivateKey.ppk'
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
with pysftp.Connection(host=myHostname,
username=myUsername,
private_key=myKey,
private_key_pass=myPassword,
cnopts=cnopts) as sftp:
pass
A better way would be to set the known_hosts path using the CnOpts. I don't have a Windows machine, but based on this SA answer, maybe the following will work:
import os
import pysftp
myHostname = 'sftp.name.com'
myUsername = 'username'
myPassword = 'password'
myKey = 'C:\\PrivateKey.ppk'
knownhosts_path = os.path.join(os.environ['USERPROFILE'], '.ssh', 'known_hosts')
cnopts = pysftp.CnOpts(knownhosts=knownhosts_path)
cnopts.hostkeys = None
with pysftp.Connection(host=myHostname,
username=myUsername,
private_key=myKey,
private_key_pass=myPassword,
cnopts=cnopts) as sftp:
pass

Python moving file on SFTP server to another folder [duplicate]

This question already has answers here:
Rename file on remote server on Python
(2 answers)
Closed 2 years ago.
I wrote this script to save a file from an SFTP remote folder to a local folder. It then removes the file from the SFTP. I want to change it so it stops removing files and instead saves them to a backup folder on the SFTP. How do I do that in pysftp? I cant find any documentation regarding it...
import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
myHostname = "123"
myUsername = "456"
myPassword = "789"
with pysftp.Connection(host=myHostname, username=myUsername, password="789", cnopts=cnopts) as sftp:
sftp.cwd("/Production/In/")
directory_structure = sftp.listdir_attr()
local_dir= "D:/"
remote_dir = "/Production/"
remote_backup_dir = "/Production/Backup/"
for attr in directory_structure:
if attr.filename.endswith(".xml"):
file = attr.filename
sftp.get(remote_dir + file, local_dir + file)
print("Moved " + file + " to " + local_dir)
sftp.remove(remote_dir + file)
Don't worry about my no hostkey or the password in plain. I'm not keeping it that way once i get the script working :)
Use Connection.rename:
sftp.rename(remote_dir + file, remote_backup_dir + file)
Obligatory warnings:
Do not set cnopts.hostkeys = None, unless you do not care about security. For the correct solution see Verify host key with pysftp.
Do not use pysftp. It's dead. Use Paramiko. See pysftp vs. Paramiko.

Python: Make SFTP connection using proxyhost and proxyport

I have trying to make a SFTP connection using a proxy
and print out the files in the SFTP directory
import pysftp
myHostname = "some.hostname.com"
myUsername = "test"
myPassword = "password"
myProxyHost = "10.10.10.10"
myProxyPort = "1010"
with pysftp.Connection(
host=myHostname,
username=myUsername,
password=myPassword,
proxy=myProxyHost,
proxyport=myProxyPort,
) as sftp:
print("Connection succesfully stablished ... ")
# Switch to a remote directory
sftp.cwd("/test/folder")
directory_structure = sftp.listdir_attr()
# Print data
for attr in directory_structure:
print(attr.filename, attr)
but I am getting a error of 'TypeError: init() got an unexpected keyword argument 'proxy''
could someone show me how to use proxy to make a successful connection.
Based on pysftp.Connection()'s documentation, it does not support proxy or proxyport parameters.
You may have better luck using the underlying Paramiko SFTPClient class – there's a gist over here that seems to have an explanation about proxying with Paramiko.

Python script to upload a file to a remote server

I am working on a project that requires us to upload a vile via SFTP to a remote server, and we are having troubles doing this. We tried following this youtube guide, but we are having some issues.
We are getting a "no such file" error when we run the script, and we know for sure that the file exists and that we have given the python script the right name and location for the file.
This is the script as we have it right now:
import pysftp as sftp
def sftpTry():
try:
s = sftp.Connection(host='babbage.cs.missouri.edu', username ='<username>', password = '<password>')
remotepath = '~it3001s14grp1/videos/newVideo/new.avi'
#localpath = '/etc/motion/capture/hello.txt'
localpath = '/etc/motion/capture/06--2014-05-15---16-16-25.avi'
s.put(localpath, remotepath)
s.close()
except Exception, e:
print str(e)
sftpTry();
You should begin your remote path with a forward slash "/". Also, check the directory you are specifying in the remotepath. You should try to do a pwd in the directory when you login into the server (say using ssh). The remote-path should be specified exactly like that.
Although you do have the filename name in the remote path, it would throw an error if you specify just the folder's name.
Another tip would be to use getpass instead of hard-coding the password:
passwd = getpass.getpass()
s = sftp.Connection(host='<host>', username = '<username>', password = passwd)

Categories

Resources