ansible-pylibssh 入门¶
现在您已经阅读了 安装指南 并在您的系统上安装了 ansible-pylibssh。
提示
本页上的示例使用 Python 3.8。如果您使用的是旧的解释器,则可能需要在复制代码段时修改语法。
检查软件版本¶
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__=}')
创建 SSH 会话¶
注意
下面显示的 API 是底层的。您应该非常小心地确保处理任何发生的异常,并且在不再需要时始终关闭所有资源。
from pylibsshext.errors import LibsshSessionException
from pylibsshext.session import Session
ssh = Session()
连接到远程 SSH 服务器¶
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=}')
通过 GSSAPI 连接¶
注意
这要求您的 libssh 编译时启用了 GSSAPI 支持。
使用 GSSAPI,密码或私钥不是必需的,但可以指定客户端和服务主体。
ssh.connect(
host=HOST,
user=USER,
timeout=TIMEOUT,
port=PORT,
# These parameters are not necessary, but can narrow down which token
# should be used to connect, similar to specifying a ssh private key
# gssapi_client_identity="client_principal_name",
# gssapi_server_identity="server_principal_hostname",
)
传递命令并读取响应¶
ssh_channel = ssh.new_channel()
try:
cmd_resp = ssh_channel.exec_command(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')
finally:
ssh_channel.close()
打开远程 shell 传递命令并接收响应¶
chan_shell = ssh.invoke_shell()
try:
chan_shell.sendall(b'ls\n')
data_b = chan_shell.read_bulk_response(timeout=2, retry=10)
print(data_b.decode())
finally:
chan_shell.close()
从远程主机获取文件¶
使用 SCP
remote_file = '/etc/hosts'
local_file = '/tmp/hosts'
scp = ssh.scp()
scp.get(remote_file, local_file)
使用 SFTP
remote_file = '/etc/hosts'
local_file = '/tmp/hosts'
sftp = ssh.sftp()
try:
sftp.get(remote_file, local_file)
finally:
sftp.close()
将文件复制到远程主机¶
使用 SCP
remote_file = '/etc/hosts'
local_file = '/tmp/hosts'
scp = ssh.scp()
scp.put(remote_file, local_file)
使用 SFTP
remote_file = '/etc/hosts'
local_file = '/tmp/hosts'
sftp = ssh.sftp()
try:
sftp.put(remote_file, local_file)
finally:
sftp.close()