Getting Started with ansible-pylibssh¶
Now that you have read the installation guide and installed ansible-pylibssh on a your system.
Tip
The examples on this page use Python 3.8. If your interpreter is older, you may need to modify the syntax when copying the snippets.
Checking software versions¶
from pylibsshext import (
__full_version__, # string with both ansible-pylibssh and libssh versions
)
from pylibsshext import (
__libssh_version__, # linked libssh lib version as a string
)
from pylibsshext import __version__ # ansible-pylibssh version as a string
from pylibsshext import __version_info__ # ansible-pylibssh version as a tuple
print(f'{__full_version__=}')
print(f'{__libssh_version__=}')
print(f'{__version__=}')
print(f'{__version_info__=}')
Creating a SSH session¶
Attention
The APIs that are shown below, are low-level. You should take a great care to ensure you process any exceptions that arise and always close all the resources once they are no longer necessary.
from pylibsshext.errors import LibsshSessionException
from pylibsshext.session import Session
ssh = Session()
Connecting with remote SSH server¶
HOST = 'CHANGEME'
USER = 'CHANGEME'
PASSWORD = 'CHANGEME'
TIMEOUT = 30
PORT = 22
try:
ssh.connect(
host=HOST,
user=USER,
password=PASSWORD,
timeout=TIMEOUT,
port=PORT,
)
except LibsshSessionException as ssh_exc:
print(f'Failed to connect to {HOST}:{PORT} over SSH: {ssh_exc!s}')
print(f'{ssh.is_connected=}')
Passing a command and reading response¶
ssh_channel = ssh.new_channel()
cmd_resp = ssh_channel.write(b'ls')
print(f'stdout:\n{cmd_resp.stdout}\n')
print(f'stderr:\n{cmd_resp.stderr}\n')
print(f'return code: {cmd_resp.returncode}\n')
ssh_channel.close()
Opening a remote shell passing command and receiving response¶
chan_shell = ssh.invoke_shell()
chan_shell.sendall(b'ls')
data = chan_shell.read_bulk_response(timeout=2, retry=10)
chan_shell.close()
print(data)
Fetch file from remote host¶
Using SCP:
remote_file = '/etc/hosts'
local_file = '/tmp/hosts'
scp = ssh.scp()
scp.get(remote_file, local_file)
Using SFTP:
remote_file = '/etc/hosts'
local_file = '/tmp/hosts'
sftp = ssh.sftp()
sftp.get(remote_file, local_file)
sftp.close()
Copy file to remote host¶
Using SCP:
remote_file = '/etc/hosts'
local_file = '/tmp/hosts'
scp = ssh.scp()
scp.put(remote_file, local_file)
Using SFTP:
remote_file = '/etc/hosts'
local_file = '/tmp/hosts'
sftp = ssh.sftp()
sftp.put(remote_file, local_file)
sftp.close()
Closing SSH session¶
ssh.close()