paramiko自动化运维
实现文件上传下载(sftp),命令执行,命令交互执行,生成日志文件,由于使用ssh登录,tcp限制,最大并发数为200
服务器,网络设备均可使用
代码如下:
import paramiko
import time
import json
class SSHConnection(object):
def __init__(self, job,retry_num=3,cmd_wait=3,null_cmd = "\r",default_mod=0o755):
self.host = job['host']
self.port = job['port']
self.user = job['user']
self.pwd = job['pwd']
self.tasks = job["tasks"]
self.timeout = int(job.get("timeout",20))# 连接超时时间
self.logfile = job.get("logfile",None)
self.retry_num = retry_num # 命令执行出错重试次数,当前3
self.cmd_wait = cmd_wait # 交互命令执行等待时间,及终端开启等待时间
self.null_cmd = null_cmd # 空命令 当前为\r
self.default_mod=default_mod # 上传文件权限设置,当前755
def connect(self):
transport = paramiko.Transport(self.host, self.port)
transport.connect(username=self.user, password=self.pwd,)
self.__transport = transport
def close(self):
self.__transport.close()
def to_str(self,bytes_or_str):
if isinstance(bytes_or_str, bytes):
value = bytes_or_str.decode('utf-8')
else:
value = bytes_or_str
return value
def run_tasks(self):
log_list = []
self.connect()
ssh = paramiko.SSHClient()
ssh._transport = self.__transport
# 交互终端
task_type_keys = [ str(x["type"]) for x in self.tasks]
if "interaction" in task_type_keys:
terminal = ssh.invoke_shell()
# 等待打开终端
time.sleep(self.cmd_wait)
login_info = self.to_str(terminal.recv(99999999999999))
if self.logfile:
log_list.append({
'login_info':login_info})
def run(task:dict