how to do sftp python 3? - python

I am using the code below to do sftp:
#!/opt/python3/bin/python3
import paramiko
import sys
host = '192.168.1.2'
port = 22622
transport = paramiko.Transport((host, port))
password = "p#ssw0rd"
username = "web"
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport)
path = '/log/ERROR.LOG'
localpath = '/home/web/ERROR.LOG'
sftp.get(path, localpath)
sftp.close()
transport.close()
print ("Download done.")
But the output is:
Traceback (most recent call last):
File "c.py", line 2, in <module>
import paramiko
ImportError: No module named paramiko
Is there no Paramiko module for Python3?
What do I have to use to do sftp?

Paramiko does not yet officially support Python 3. I found a bug discussing it, and SFTP is one of the problem spots:
https://github.com/paramiko/paramiko/issues/16
I recommend using subprocess to run the sftp command-line tool.

Related

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

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?

Downloading CSV inside a .zip with pysftp

I'm trying to load a .csv file stored on a FTP Server (SFTP protocol). I'm using Python in combination with pysftp library. On the FTP server, the CSV file is inside a .zip file. Is there a way to open the zip and then retrieve only the csv file inside it?
Thank you in advance,
import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
# Make connection to sFTP
with pysftp.Connection(hostname,
username=sftp_username,
password=sftp_pw,
cnopts = cnopts
)
with pysftp.cd(download_directory):
with sftp.cd('download_directory'):
print(f'Downloading this file: {filename}')
sftp.get(filename, preserve_mtime=True)
sftp.close()
If you have ssh access to the remote host and know enough about the remote path to the zip file you want and the zip utilities on that host, you can use your ssh client to run the unzip command remotely and capture its output. Here, my target is a linux machine and the zipfile is in the login user's home directory path. I can use the paramiko ssh client to do the work
Its a good idea to log into the remote server via ssh and practice to see what the path structure is like
import sys
import paramiko
import shutil
def sshclient_exec_command_binary(sshclient, command, bufsize=-1,
timeout=None, get_pty=False):
"""Paramiko SSHClient helper that implements exec_command with binary
output.
"""
chan = sshclient._transport.open_session()
if get_pty:
chan.get_pty()
chan.settimeout(timeout)
chan.exec_command(command)
stdin = chan.makefile('wb', bufsize)
stdout = chan.makefile('rb', bufsize)
stderr = chan.makefile_stderr('rb', bufsize)
return stdin, stdout, stderr
# example gets user/pw from command line
if len(sys.argv) != 3:
print("usage: test.py username password")
exit(1)
username, password = sys.argv[1:3]
# put your host/file info here
hostname = "localhost"
remote_zipfile = "tmp/mytest.zip"
file_to_extract = "myfile"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname, username=username, password=password)
unzip_cmd = "unzip -p {} {}".format(remote_zipfile, file_to_extract)
print("running", unzip_cmd)
stdin, out, err = sshclient_exec_command_binary(ssh, unzip_cmd)
# if the command worked, out is a file-like object to read.
print("writing", file_to_extract)
with open(file_to_extract, 'wb') as out_fp:
shutil.copyfileobj(out, out_fp)

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)

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

Download files over SSH using Python

I am trying to make a script that downloads ( or upload ) files over ssh, as ftp port is disabled from firewall. This is my script :
import os
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('10.170.21.93', username="abhishek", password="#bhishek$")
sftp = ssh.open_sftp()
localpath = 'abc.txt'
remotepath = '/opt/crestelsetup/patchzip'
sftp.put(localpath, remotepath)
sftp.close()
ssh.close()
This is giving me "IOError: Failure", can any one help?
You need to explicitly specify the remote path:
import os
import paramiko
ssh = paramiko.SSHClient()
ssh.connect('10.170.21.93', username="abhishek", password="#bhishek$")
sftp = ssh.open_sftp()
localpath = 'abc.txt'
remotepath = '/opt/crestelsetup/patchzip/abc.txt'
sftp.put(localpath, remotepath)
sftp.close()
ssh.close()
As per Martin Prikryl's comment, the following code line is highly discouraged as it opens you up against man in the middle attack, however, it can be a temporary fix for missing host keys
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
Just modified the destination path to include the file name as well.Try to change.
remotepath = '/opt/crestelsetup/patchzip'
to
remotepath = '/opt/crestelsetup/patchzip/abc.txt'
You need to modify remotepath. Since, your remote path is /opt/crestelsetup/patchzip. Now need to upload file join with remote path. It can be done using following way.
fname = os.path.basename(localpath)
sftp.put(localpath, os.path.join(remotepath, fname))

Categories

Resources