其他分享
首页 > 其他分享> > Paramiko

Paramiko

作者:互联网

Paramiko模块

pip install paramiko -i https://pypi.tuna.tsinghua.edu.cn/simple

基于用户名和密码

import paramiko

# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname='xxx.xxx.xxx.xxx', port=22, username='root', password='xxxxxxxxx')
stdin, stdout, stderr = ssh.exec_command('df -h')
# stdin 传值
# stdin.write('y')
# 获取命令的结果
result = stdout.read()
# 返回byte类型
print(result.decode('utf-8'))
# 关闭连接
ssh.close()

基于公钥和私钥

private_key = paramiko.RSAKey.from_private_key_file('id/rsa')

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='', port=22, username='root', key_filename=private_key)
stdin, stdout, stderr = ssh.exec_command('df -h')
# 获取命令的结果
result = stdout.read()
# 返回byte类型
print(result.decode('utf-8'))
# 关闭连接
ssh.close()

SFTPClient

transport=paramiko.Transport(('hostname',22))
transport.connect(username='root',password='123')

sftp = paramiko.SFTPClient.from_transport(transport)
# location.py上传到服务器test.py
stfp.put('/tmp/location.py','/tmp/test.py')
# 将remove_path下载到本地local_path
stfp.get('remove_path',local_path)
transport.close()

标签:py,transport,Paramiko,ssh,key,path,paramiko
来源: https://www.cnblogs.com/20190707wdd/p/16370089.html