paramiko 远程远程部署软件脚本案例
# -*- coding: utf-8 -*- import paramiko import sys, os import datetime import subprocess import time import re import hashlib reload(sys) sys.setdefaultencoding("utf-8") os.environ["PATH"] = "/usr/local/jdk18/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin" os.environ["LANG"] = "en_US.UTF-8" ip_list = ["10.110.189.217","10.110.193.106"] class pub_filebeat(): def __init__(self): self.username = "redis" self.passwd = "123456" self.client_ssh = None self.sftpcliet = None self.port = 22 self.chan = None self.result = None # 创建一个ssh 链接 def create_ssh(self,ip): self.client_ssh = paramiko.SSHClient() self.client_ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.client_ssh.connect(ip, self.port, self.username, self.passwd, timeout=5) self.chan = self.client_ssh.invoke_shell() self.flag=None ''' 在现有的ssh链接的基础上获取一个ftp链接 方式一 : transport = self.client_ssh.get_transport() self.sftpcliet = paramiko.SFTPClient.from_transport(transport) 方式二 : self.sftpcliet = self.client_ssh.open_sftp() ''' # # transport = self.client_ssh.get_transport() # self.sftpcliet = paramiko.SFTPClient.from_transport(transport) self.sftpcliet = self.client_ssh.open_sftp() def execute(self,ip): try: self.sendcmd(" sudo su - ") if self.flag == 1: self.sendcmd("redis@yto369") self.sendcmd(" cd /home/redis ") self.sendcmd(" tar -zxvf filebeat623.tar.gz ") self.sendcmd(" sed -i 's/hostip: 10.1.241.99/hostip: %s/g' filebeat623/filebeat.yml ; " % (ip)) self.sendcmd(" nohup filebeat623/filebeat -e -c filebeat623/filebeat.yml > info.log 2>&1 & ") print "%s filebeat 部署完成" % (ip) except Exception,e: print e.message def tranfile(self): try: self.sftpcliet.put("F:\dwchaoyue\ELK\/filebeat623.tar.gz", '/home/redis/filebeat623.tar.gz') except Exception,e: print e.message self.sftpcliet.close() def sendcmd(self,cmd): cmd = cmd + '\r' p = re.compile(r'\[root@.+\s.*\]') self.result = "" self.chan.send(cmd) while True: time.sleep(0.5) ret = self.chan.recv(65535).decode("utf-8") self.result = self.result + ret if 'password' in self.result.split(" "): self.flag = 1 break if p.search(ret): break # 遍历ip 列表 def bianli(self,ip_list): for ip in ip_list: self.create_ssh(ip) if self.check_result() >= 1 : print "%s filebeat 已部署,无需重新部署" % (ip) continue pass self.tranfile() self.execute(ip) if self.check_result() < 1: print "%s filebeat 部署失败 ,请重试" % (ip) self.client_ssh.close() self.sftpcliet.close() def check_result(self): std_in,std_out,std_err = self.client_ssh.exec_command("ps -ef | grep -i filebeat | grep -v 'grep' | wc -l") return int(std_out.read()) if __name__ == "__main__": try: pb = pub_filebeat() pb.bianli(ip_list) except Exception, e: print e
paramiko 远程执行命令和上传下载代码案例
Phttps://www.cnblogs.com/haigege/p/5513759.html
phttps://blog.csdn.net/a382486075/article/details/78658165
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。