paramiko 模块封装-阿里云开发者社区

开发者社区> 安全> 正文

paramiko 模块封装

简介: #!/usr/bin/env python#coding=utf-8 import paramiko, getpass,sys,traceback class ssh_utils(): def login_by_passwd(self, ip, port, username, passwd): self.

#!/usr/bin/env python
#coding=utf-8

import paramiko, getpass,sys,traceback

class ssh_utils():
def login_by_passwd(self, ip, port, username, passwd):
self.ip = ip
self.port = port
self.username = username
self.passwd = passwd
self.pkey = None

def login_by_key(self, username, key_path, passwd):
try:
self.pkey=paramiko.RSAKey.from_private_key_file(key_path)
except paramiko.PasswordRequiredException:
if not passwd:
passwd = getpass.getpass('RSA key password: ')
self.pkey = paramiko.RSAKey.from_private_key_file(key_path, passwd)

def ssh(self,shell):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if self.pkey:
ssh.connect(self.ip, self.port, self.username, compress = True, pkey= self.pkey)
else:
if not self.passwd:
self.passwd = getpass.getpass('input password: ')
ssh.connect(self.ip,self.port,self.username, self.passwd)
stdin, stdout, stderr = ssh.exec_command(shell)
res = stdout.readlines()
ssh.close()
return res
except:
type, value, tb = sys.exc_info()
return traceback.format_exception(type, value, tb)

def scp(self,localpath,remotepath):
try:
t = paramiko.Transport((self.ip,self.port))
if self.pkey:
t.connect(self.ip, self.port, self.username, pkey= self.pkey)
else:
if not self.passwd:
self.passwd = getpass.getpass('input password: ')
t.connect(username = self.username, password = self.passwd)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put(localpath,remotepath)
t.close()
return "SCP OK"
except:
type, value, tb = sys.exc_info()
return traceback.format_exception(type, value, tb)

if __name__ == '__main__':
#使用例子
myssh = ssh_utils()
myssh.login_by_passwd("192.168.11.181",22,"ahwater","Aa7.")
ret = myssh.scp('c:\\inetpub\\','d:\\sl\\')
#myssh.ssh("cd d:\ && pwd")

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

分享:
+ 订阅

云安全开发者的大本营

其他文章