简介
paramiko 是python的一个实现SSHv2协议的一个库,使用paramiko我们可以很方便使用python ssh连接到其它主机.
核心组件
client: 入口组件,主要用于创建ssh连接,执行命令等入口
transport: 核心功能组件,控制ssh连接,管理channel,处理ssh server返回数据,发送数据
channel: 用于执行ssh命令以及interactive 交互方式shell处理
packet: 解析数据包和压缩数据包
client
SSHClient作为client里面主要类,是作为paramiko一个主要入口类,起到一个门面的作用
简单使用
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(*args, **kwargs)
stdin, stdout, stderr = ssh.exec_command('ls -a')
print(stdout.read().decode('utf-8'))
ssh.close()
首先初始化一个SSHClient,后面connect和exec_command都是通过transport来执行,下面会具体讲transport
transport
最重要的一个核心类Transport,整个库核心功能都集中到这个类里面,在client.connect方法里面会初始化一个Transport对象,设置一下Transport对象的SSH相关的属性,然后进行相关的认证工作
def _auth(
self,
username,
password,
pkey,
key_filenames,
allow_agent,
look_for_keys,
gss_auth,
gss_kex,
gss_deleg_creds,
gss_host,
passphrase,
):
"""
Try, in order:
- The key(s) passed in, if one was passed in.
- Any key we can find through an SSH agent (if allowed).
- Any "id_rsa", "id_dsa" or "id_ecdsa" key discoverable in ~/.ssh/
(if allowed).
- Plain username/password auth, if a password was given.
(The password might be needed to unlock a private key [if 'passphrase'
isn't also given], or for two-factor authentication [for which it is
required].)
"""
saved_exception = None
two_factor = False
allowed_types = set()
two_factor_types = {"keyboard-interactive", "password"}
if passphrase is None and password is not None:
passphrase = password
# If GSS-API support and GSS-PI Key Exchange was performed, we attempt
# authentication with gssapi-keyex.
if gss_kex and self._transport.gss_kex_used:
try:
self._transport.auth_gssapi_keyex(username)
return
except Exception as e:
saved_exception &