在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
2、paramiko文档
*** walker ***