paramiko sftp can't delete remote folder, ioerror - python

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)

Related

Unable to transfer file from master node to minion nodes using sftp in a python script

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")
...

Python Paramiko Error

I wrote a python program. I have conf file, I wrote router configuration commands inside the conf file and I want to execute these commands inside paramiko. I have a problem - the error message is below. Can you help me please ?
CODE:
#!/usr/bin/env python
import paramiko
ip="10.100.1.200"
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,username="admin",password="pass")
text=open("conf")
for komut in text.readlines():
stdin, stdout, stderror = ssh.exec_command(komut)
for line in stdout.readlines():
print line.strip()
ssh.close()
text.close()
error message:
Traceback (most recent call last):
File "./configmaker.py", line 13, in <module>
stdin, stdout, stderror = ssh.exec_command(str(komut.strip()))
File "/usr/lib/python2.7/dist-packages/paramiko/client.py", line 370, in exec_command
chan = self._transport.open_session()
File "/usr/lib/python2.7/dist-packages/paramiko/transport.py", line 662, in open_session
return self.open_channel('session')
File "/usr/lib/python2.7/dist-packages/paramiko/transport.py", line 764, in open_channel
raise e
EOFError
Try with this code:
import paramiko
if __name__ == "__main__":
ip = "127.0.0.1"
username = "admin"
password = "root"
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,username=username,password=password)
ssh_transport = ssh.get_transport()
for command in ("ls /tmp", "date"):
chan = ssh_transport.open_session()
chan.exec_command(command)
exit_code = chan.recv_exit_status()
stdin = chan.makefile('wb', -1) # pylint: disable-msg=W0612
stdout = chan.makefile('rb', -1)
stderr = chan.makefile_stderr('rb', -1) # pylint: disable-msg=W0612
output = stdout.read()
print output
Try this code, first copy the conf file to remote server and execute the file.
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
host = str(host)
user = 'root'
pw = 'root123'
ssh.connect(host, username=user, password=pw)
filepath = "conf"
remote_path = "/root/qats_tool.tar"
sftp = ssh.open_sftp()
sftp.put(filepath, remote_path)
command="./conf"
stdin, stdout, stderr = ssh.exec_command(command)
sftp.close()

"No such file" error when using paramiko's sftp

I want to file transfer local to server using python
#!/usr/bin/env python
import os
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname, username="username", password="password")
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('ls /tmp')
print "output", ssh_stdout.read()
#Reading output of the executed command
error = ssh_stderr.read()
#Reading the error stream of the executed command
print "err", error, len(error)
#Transfering files to and from the remote machine
sftp = ssh.open_sftp()
#sftp.get("/home/developers/screenshots/ss.txt", "/home/e100075/python/ss.txt")
sftp.put('/home/e100075/python/ss.txt', '/home/developers/screenshots/ss.txt')
sftp.close()
ssh.close()
After running i got the errors below
File "file_copy.py", line 21, in <module>
sftp.put('/home/e100075/python/ss.txt', '/home/developers/screenshots/ss.txt')
File "/usr/lib/python2.7/dist-packages/paramiko/sftp_client.py", line 565, in put
fr = self.file(remotepath, 'wb')
File "/usr/lib/python2.7/dist-packages/paramiko/sftp_client.py", line 245, in open
t, msg = self._request(CMD_OPEN, filename, imode, attrblock)
File "/usr/lib/python2.7/dist-packages/paramiko/sftp_client.py", line 635, in _request
return self._read_response(num)
File "/usr/lib/python2.7/dist-packages/paramiko/sftp_client.py", line 682, in _read_response
self._convert_status(msg)
File "/usr/lib/python2.7/dist-packages/paramiko/sftp_client.py", line 708, in _convert_status
raise IOError(errno.ENOENT, text)
IOError: [Errno 2] No such file
If you know the answer. please let me know
thanks for reading..
The problem is most likely that the remote directory does not exist (/home/developers/screenshots). Create the directory and try again.

python paramiko: Permission denied

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 )

Paramiko SFTP problems when no password is used

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.

Categories

Resources