在python3中使用密钥文件方式的ssh。
#encoding: utf-8
#author: walker
#date: 2017-03-29
#summary: 在python代码中使用ssh
#Python sys.version 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)]
import paramiko
class SSHUser(object):
def __init__(self, host, port, usr, pwd, pkeyFile, pkeyPwd='walker'):
self.client = paramiko.SSHClient()
key = paramiko.RSAKey.from_private_key_file(pkeyFile, password=pkeyPwd)
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #通过公共方式进行认证 (不需要在known_hosts 文件中存在)
self.client.connect(host, port, username=usr, password=pwd, pkey=key)
def exec_cmd(self, cmd):
return self.client.exec_command(cmd)
def close(self):
self.client.close()
if __name__ == '__main__':
ssh = SSHUser(host='192.168.2.3',
port=22,
usr='walker',
pwd='walker',
pkeyFile=r'D:\key\id_rsa', #密钥文件
pkeyPwd='walker')
stdin, stdout, stderr=ssh.exec_cmd('hostname')
print(stdout.read().decode('utf-8'))
stdin, stdout, stderr=ssh.exec_cmd('ls')
print(stdout.read().decode('utf-8'))
ssh.close()
相关阅读:
1、pypi:paramiko
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有