Reputation: 133
I have the following code which successfully connects to an SFTP server and copies a file from remote to local.
But how can I list directory contents?
Running the command 'ls' fails
import pssh.clients, pssh.utils
pssh.utils.enable_logger(pssh.utils.logger)
hosts = OPT['ftp']['host']
client = pssh.clients.SSHClient(hosts, port=OPT['ftp']['port'], user=OPT['ftp']['user'], password=OPT['ftp']['pass']) # ParallelSSHClient SSHClient
cmds = client.copy_remote_file('1223d_ca.zip', '/dev/shm/hi.zip')
# cmds = client.run_command('ls') # fails
with the following error:
Traceback (most recent call last):
File "./app.py", line 1594, in <module>
cmds = client.run_command('ls')
File "/home/da/py38/lib/python3.8/site-packages/pssh/clients/base/single.py", line 555, in run_command
channel = self.execute(_command, use_pty=use_pty)
File "/home/da/py38/lib/python3.8/site-packages/pssh/clients/native/single.py", line 301, in execute
self._eagain(channel.execute, cmd)
File "/home/da/py38/lib/python3.8/site-packages/pssh/clients/native/single.py", line 349, in _eagain
return self._eagain_errcode(func, LIBSSH2_ERROR_EAGAIN, *args, **kwargs)
File "/home/da/py38/lib/python3.8/site-packages/pssh/clients/base/single.py", line 576, in _eagain_errcode
ret = func(*args, **kwargs)
File "ssh2/channel.pyx", line 79, in ssh2.channel.Channel.execute
File "ssh2/utils.pyx", line 174, in ssh2.utils.handle_error_codes
ssh2.exceptions.ChannelRequestDenied
Upvotes: 0
Views: 251
Reputation: 133
Here's how to do it using ssh2-python
import socket,ssh2.session # ssh2-python is a low-level wrapper around C libssh2
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((OPT['ftp']['host'], OPT['ftp']['port']))
sess = ssh2.session.Session()
sess.handshake(sock)
sess.userauth_password(OPT['ftp']['user'], OPT['ftp']['pass'])
sftp = sess.sftp_init() # https://ssh2-python.readthedocs.io/en/latest/sftp.html
# with sftp.open('1223d_ca.zip', ssh2.sftp.LIBSSH2_FXF_READ, ssh2.sftp.LIBSSH2_SFTP_S_IRUSR) as fp: # opendir()
# for size,data in fp:
# print(size,data)
with sftp.opendir('/') as fp:
for size,buf,attrs in fp.readdir():
print(size,buf,attrs)
sock.close()
Upvotes: 0