I need to upload some files using SFTP, this works from the command line:
$sftp myuser#my_remote_host
Connected to my_remote_host
sftp>
This is my Paramiko script:
#!/usr/bin/env python
import paramiko
import sys
import os
host = "my_remote_host"
port = 22
transport = paramiko.Transport((host, port))
username = "myuser"
LOCAL_PATH = "/tmp/"
REMOTE_PATH = "/dcs/tmp/"
FILE = "myfile"
transport.connect(username = username)
sftp = paramiko.SFTPClient.from_transport(transport)
path = LOCAL_PATH + FILE
sftp.put(LOCAL_PATH + FILE, REMOTE_PATH + FILE)
sftp.close()
transport.close()
print 'Upload done.'
When executing I get this error:
No handlers could be found for logger "paramiko.transport"
Traceback (most recent call last):
File "./my_sftp.py", line 19, in ?
sftp = paramiko.SFTPClient.from_transport(transport)
File "/usr/lib/python2.4/site-packages/paramiko/sftp_client.py", line 102, in from_transport
chan = t.open_session()
File "/usr/lib/python2.4/site-packages/paramiko/transport.py", line 655, in open_session
return self.open_channel('session')
File "/usr/lib/python2.4/site-packages/paramiko/transport.py", line 745, in open_channel
raise e
EOFError
When adding a private key I get this error:
path = os.path.join(os.environ['HOME'], '.ssh', 'id_dsa')
key = paramiko.DSSKey.from_private_key_file(path)
transport.connect(username = username, pkey=key)
Traceback (most recent call last):
File "./my_sftp.py", line 24, in ?
transport.connect(username = username, pkey=key)
File "/usr/lib/python2.4/site-packages/paramiko/transport.py", line 1007, in connect
self.auth_publickey(username, pkey)
File "/usr/lib/python2.4/site-packages/paramiko/transport.py", line 1234, in auth_publickey
return self.auth_handler.wait_for_response(my_event)
File "/usr/lib/python2.4/site-packages/paramiko/auth_handler.py", line 174, in wait_for_response
raise e
paramiko.AuthenticationException: Authentication failed.
In your first example, you can't authenticate with only a username, so the session can't be started.
I can't tell why your privatekey example isn't working without some more information. Is it possible that its the incorrect key for that server? SSH on the command line may be trying multiple keys, or getting it from an agent.
Anyway, it easier to start off with the SSHClient class. It will wrap up all the authentication, and host verification pieces in one package. It also has an open_sftp() convenience method to return an SFTPClient instance.
Related
I am trying to send a file from the master node to minion nodes using a python script but a single error OSError: Failure keeps on coming up.
I tried to code this file to send this file from one local machine to another local machine.
My code:
#! /usr/bin/python
#! /usr/bin/python3
import paramiko
import os
#Defining working connect
def workon(host):
#Making a connection
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #To add the missing host key and auto add policy
ssh_client.connect(hostname = host, username = 'username', password = 'password')
ftp_client = ssh_client.open_sftp()
ftp_client.put("/home/TrialFolder/HelloPython", "/home/")
ftp_client.close()
#stdin, stdout, stderr = ssh_client.exec_command("ls")
#lines = stdout.readlines()
#print(lines)
def main():
hosts = ['192.16.15.32', '192.16.15.33', '192.16.15.34']
threads = []
for h in hosts:
workon(h)
main()
Error:
Traceback (most recent call last):
File "PythonMultipleConnectionUsinhSSH.py", line 28, in <module>
main()
File "PythonMultipleConnectionUsinhSSH.py", line 26, in main
workon(h)
File "PythonMultipleConnectionUsinhSSH.py", line 15, in workon
ftp_client.put("/home/Sahil/HelloPython", "/home/")
File "/usr/local/lib/python3.6/site-packages/paramiko/sftp_client.py", line 759, in put
return self.putfo(fl, remotepath, file_size, callback, confirm)
File "/usr/local/lib/python3.6/site-packages/paramiko/sftp_client.py", line 714, in putfo
with self.file(remotepath, "wb") as fr:
File "/usr/local/lib/python3.6/site-packages/paramiko/sftp_client.py", line 372, in open
t, msg = self._request(CMD_OPEN, filename, imode, attrblock)
File "/usr/local/lib/python3.6/site-packages/paramiko/sftp_client.py", line 813, in _request
return self._read_response(num)
File "/usr/local/lib/python3.6/site-packages/paramiko/sftp_client.py", line 865, in _read_response
self._convert_status(msg)
File "/usr/local/lib/python3.6/site-packages/paramiko/sftp_client.py", line 898, in _convert_status
raise IOError(text)
OSError: Failure
First, you should make sure the target directory /home/ is writable for you. Then you should review documentation for the put method. It says this about the second argument (remotepath):
The destination path on the SFTP server. Note that the filename should be included. Only specifying a directory may result in an error.
Try including the filename in the path, like:
...
ftp_client.put("/home/TrialFolder/HelloPython", "/home/HelloPython")
...
I've found the following script on internet:
import paramiko
from paramiko import client
class ssh:
client = None
def __init__(self, address, username, password):
# Let the user know we're connecting to the server
print("Connecting to server.")
# Create a new SSH client
self.client = client.SSHClient()
# The following line is required if you want the script to be able to access a server that's not yet in the known_hosts file
self.client.set_missing_host_key_policy(client.AutoAddPolicy())
# Make the connection
self.client.connect(address, username=username, password=password, look_for_keys=False)
def sendCommand(self, command):
# Check if connection is made previously
if (self.client):
stdin, stdout, stderr = self.client.exec_command(command)
while not stdout.channel.exit_status_ready():
# Print stdout data when available
if stdout.channel.recv_ready():
# Retrieve the first 1024 bytes
alldata = stdout.channel.recv(1024)
while stdout.channel.recv_ready():
# Retrieve the next 1024 bytes
alldata += stdout.channel.recv(1024)
# Print as string with utf8 encoding
print(str(alldata, "utf8"))
else:
print("Connection not opened.")
paramiko.util.log_to_file('paramiko.log') # <----- added line
connessione = ssh("10.76.80.11","pi","raspberry")
connessione.sendCommand("arp -a")
I would like to send a commando to my raspberry with this script, I tried to run the program without the line:
paramiko.util.log_to_file('paramiko.log')
but when I tried to run the code I've got this runtime error:
/usr/bin/python /Users/Marco/PycharmProjects/ssh_control/ssh.py
Connecting to server.
No handlers could be found for logger "paramiko.transport"
Traceback (most recent call last):
File "/Users/Marco/PycharmProjects/ssh_control/ssh.py", line 43, in <module>
connessione = ssh("10.76.80.11","pi","raspberry")
File "/Users/Marco/PycharmProjects/ssh_control/ssh.py", line 16, in __init__
self.client.connect(address, username=username, password=password, look_for_keys=False)
File "/Users/Marco/Library/Python/2.7/lib/python/site-packages/paramiko/client.py", line 338, in connect
t.start_client()
File "/Users/Marco/Library/Python/2.7/lib/python/site- packages/paramiko/transport.py", line 493, in start_client
raise e
AttributeError: 'EntryPoint' object has no attribute 'resolve'
Process finished with exit code 1
So I searched on Internet and I found that the problem could be fixed with the paramiko.log line.
But now I've another error:
/usr/bin/python /Users/Marco/PycharmProjects/ssh_control/ssh.py
Connecting to server.
Traceback (most recent call last):
File "/Users/Marco/PycharmProjects/ssh_control/ssh.py", line 38, in <module>
connessione = ssh("10.76.80.11","pi","raspberry")
File "/Users/Marco/PycharmProjects/ssh_control/ssh.py", line 16, in __init__
self.client.connect(address, username=username, password=password, look_for_keys=False)
File "/Users/Marco/Library/Python/2.7/lib/python/site- packages/paramiko/client.py", line 338, in connect
t.start_client()
File "/Users/Marco/Library/Python/2.7/lib/python/site-packages/paramiko/transport.py", line 493, in start_client
raise e
AttributeError: 'EntryPoint' object has no attribute 'resolve'
Process finished with exit code 1
Can someone helps me please? because I can't understand where is the error.
Thanks in advance
Turns out you need to upgrade setuptools and then re-install the package. Seems the older version breaks something on installing the python cryptography package.
Try the following...
pip install -U setuptools
pin install -U paramiko
https://github.com/pyca/cryptography/issues/2853
I solved my problem with this:
# Make the connection
self.client.connect(address, port = 22, username=username, password=password, look_for_keys=False)
because the port before wasn't specificate
I'm just building my first login to a device script, and am having some issues, im getting the below error, all i have changed is the port no, but the issue seems to be with login, i have entered the correct user pass thats for sure.
Error:
Traceback (most recent call last):
File "ssh.py", line 11, in <module>
conn.login(account) # Authenticate on the remote host
File "/usr/local/lib/python2.7/dist-packages/Exscript-2.1.503-py2.7.egg/Exscript/protocols/Protocol.py", line 627, in login
self.authenticate(account, flush = False)
File "/usr/local/lib/python2.7/dist-packages/Exscript-2.1.503-py2.7.egg/Exscript/protocols/Protocol.py", line 651, in authenticate
self.app_authenticate(app_account, flush = flush)
File "/usr/local/lib/python2.7/dist-packages/Exscript-2.1.503-py2.7.egg/Exscript/protocols/Protocol.py", line 819, in app_authenticate
self._app_authenticate(account, password, flush, bailout)
File "/usr/local/lib/python2.7/dist-packages/Exscript-2.1.503-py2.7.egg/Exscript/protocols/Protocol.py", line 723, in _app_authenticate
raise TimeoutException(msg)
Exscript.protocols.Exception.TimeoutException: Buffer: ''
Config:
import hashlib
import Exscript
from Exscript.util.interact import read_login
from Exscript import Account
from Exscript.protocols import SSH2
account = read_login() # Prompt the user for his name and password
conn = SSH2() # We choose to use SSH2
conn.connect('10.66.118.250', 3008) # Open the SSH connection to port
conn.login(account) # Authenticate on the remote host
conn.execute('enable')
conn.execute('conf t')
conn.execute('interface g0/0/1')
conn.execute('description *** TEST ***')
conn.execute('end')
print conn.response
conn.execute('show ip route')
print conn.response
conn.send('exit\r') # Send the "exit" command
conn.close()
This is my code, to delete a remote directory using paramiko sftp.
import paramiko
host = "192.168.1.13"
port = 22
transport = paramiko.Transport((host, port))
username = "root"
password = "abc123"
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport)
filepath = '/root/test_folder'
sftp.rmdir(filepath)
Execute above code will output this error,
Traceback (most recent call last):
File "autom_test.py", line 36, in <module>
sftp.rmdir(filepath)
File "/usr/lib/python2.7/site-packages/paramiko/sftp_client.py", line 390, in rmdir
self._request(CMD_RMDIR, path)
File "/usr/lib/python2.7/site-packages/paramiko/sftp_client.py", line 729, in _request
return self._read_response(num)
File "/usr/lib/python2.7/site-packages/paramiko/sftp_client.py", line 776, in _read_response
self._convert_status(msg)
File "/usr/lib/python2.7/site-packages/paramiko/sftp_client.py", line 806, in _convert_status
raise IOError(text)
IOError: Failure
This is not the case when I'm using sftp.remove(path) for a single file. But sftp.rmdir causing IOError
The syntax is from the documentation.
The error is because the destination directory has got files inside it.
Try recurssive delete instead.. See below..
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host,username=username,password=password)
filepath="/root/test_folder"
cmd = "rm -rf " + filepath
stdin, stdout, stderr = ssh.exec_command(cmd)
while not stdout.channel.exit_status_ready():
time.sleep(5)
I have a sftp program called transmit. I use it to access a sftp server. I log in with username, password and everything works fine. I can delete, create and see everything.
Now I must access this sftp server with a python script. Therefore I installed parmiko. I set up everything as in the demo file but I strangly get the error message permisson denied:
hostname = "123.456.789.1"
port = 22
hostkeytype = None
hostkey = None
try:
host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
except IOError:
print '*** Unable to open host keys file'
host_keys = {}
if host_keys.has_key(hostname):
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( username="customUser", password="xyzpasswd", hostkey=hostkey, pkey=None )
sftp = paramiko.SFTPClient.from_transport(t)
print sftp.listdir() # <- works
sftp.get("~/myfolder/test.png",".", None ) # <- permission denied error
t.close()
And this is the output if I run it:
Using host key of type ssh-dss
['.ssh2', 'archiv', 'myfolder']
Traceback (most recent call last):
File "/path/to/myscript.py", line 539, in <module>
main()
File "/path/to/myscript.py", line 531, in main
ladeDatenVomSFTPServer()
File "/path/to/myscript.py", line 493, in ladeDatenVomSFTPServer
sftp.get("~/myfolder/test.png",".", None )
File "build/bdist.macosx-10.6-intel/egg/paramiko/sftp_client.py", line 606, in get
File "build/bdist.macosx-10.6-intel/egg/paramiko/sftp_client.py", line 245, in open
File "build/bdist.macosx-10.6-intel/egg/paramiko/sftp_client.py", line 635, in _request
File "build/bdist.macosx-10.6-intel/egg/paramiko/sftp_client.py", line 682, in _read_response
File "build/bdist.macosx-10.6-intel/egg/paramiko/sftp_client.py", line 712, in _convert_status
IOError: Permission denied, file: ~/myfolder/test.png
This all works fine in Transmit but with parmiko it fails. What did I wrong?
I think the second argument should be a filename, instead of a dot .
Replace
sftp.get("~/myfolder/test.png",".", None )
with something like
sftp.get("~/myfolder/test.png","~/test.png", None )