paramiko模块学习笔记

SSHClient

基于用户名密码连接

import paramiko
# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname='',port='',username='',password='')
# 执行命令
stdin,stdout,stderr = ssh.exec_command('whoami')
# 获取命令执行结果
result = stdout.read()
# 关闭连接
ssh.close()

基于公钥连接

import paramiko
# 设置私钥路径
private_key = paramiko.RSAKey.from_private_key_file('/home/mark/.ssh/id_rsa')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='', port=22, username='', pkey=private_key)
stdin,stdout,stderr = ssh.exec_command('whoami')
result = stdout.read()
ssh.close()

SSHClient封装Transport

import paramiko

transport = paramiko.Transport(('127.0.0.1',22))
transport.connect(username='',password='')

ssh = paramiko.SSHClient()
ssh._transport = transport

stdin,stdout,stderr = ssh.exec_command('whoami')
print stdout.read().decode('utf-8')

transport.close()

SFTPClient

posted @ 2019-06-25 15:53  mark-zh  阅读(148)  评论(0编辑  收藏  举报