zoukankan      html  css  js  c++  java
  • paramiko(临时笔记)

    import sys
    import os
    import time
    import re
    import traceback
    import threading
    import paramiko
    
    
    class Ssh():
    
        def __init__(self, ip, username, password, port=22, recv_len=96, logfile="ssh.log", timeout=3600):
            self.info = {
                "ip": ip,
                "port": port,
                "username": username,
                "password": password
            }
            self.timeout = timeout
            self.recv_len = recv_len
            self.logfile = logfile
            self.logs = self._log()
            self.ssh_status = False
            self.channel = self.login()
            self._keep_alive()
    
        # def log(self, msg, encoding="utf-8"):
        #     msg = msg.replace("", "")
        #     msg = msg.replace("", "")
        #     msg = msg.replace("", "")
        #     msg = msg.replace("", "")
        #     msg = msg.replace("", "")
        #     msg = msg.replace("", "")
        #     msg = msg.replace("", "")
        #     msg = msg.replace("", "")
        #     msg = msg.replace("", "")
        #     if self.logfile == None:
        #         print(msg)
        #     else:
        #         # print(msg)
        #         with open(self.logfile, mode="a", encoding=encoding) as f:
        #             # print(msg)
        #             f.write(msg)
        #             f.flush()
        def _log(self):
            f = open(self.logfile,'ab')
            return f
        def log(self,msg):
            self.logs.write(msg)
            self.logs.flush()
    
    
        def _login(self):
            trans = paramiko.Transport((self.info["ip"], self.info["port"]))
            trans.start_client()
            trans.auth_password(
                username=self.info["username"], password=self.info["password"])
            channel = trans.open_session()
            channel.settimeout(self.timeout)
            channel.get_pty()
            channel.invoke_shell()
            self.ssh_status = True
            # channel.send("date
    ")
            time.sleep(1)
            self.log(channel.recv(self.recv_len))
            # self.log2(channel.recv(self.recv_len))
            return channel
        
        def login(self):
            for i in range(3):
                try:
                    channel = self._login()
                    return channel
                except:
                    if i == 2:
                        print("*****************************登录失败********************************")
                        traceback.print_exc()
                        sys.exit(0)
                    time.sleep(10)
                    
    
        def logout(self):
            self.excute_cmd("exit")
            self.channel.close()
            self.logs.close()
            sys.exit(0)
    
        def excute_cmd(self, cmd, timer=0.5, encoding="utf-8"):
            if self.channel.closed:
                for i in range(10):
                    if self.channel.closed:
                        try:
                            self.channel = self._login()
                            break
                        except:
                            if i == 9:
                                traceback.print_exc()
                                sys.exit(0)
                            time.sleep(1)
            cmd = cmd + "
    "
            self.channel.send(cmd)
            time.sleep(timer)
            res_bin = b""
            i = 0
            while True:
                if not self.channel.recv_ready():
                    i = i + 1
                    if i < 11:
                        time.sleep(0.05)
                        continue
                    else:
                        break
                res_bin_tmp = self.channel.recv(self.recv_len)
                self.log(res_bin_tmp)
                res_bin = b"".join([res_bin,res_bin_tmp])
            res = res_bin.decode(encoding)
            return res
    
        def _alive(self):
            while True:
                if self.channel.closed:
                    try:
                        self.channel = self._login()
                    except:
                        pass
        def _keep_alive(self):
            t = threading.Thread(target=self._alive)
            t.setDaemon(True)
            t.start()
    
    
    def ssh_login(ssher, hostip, username, password, port=22):
        res_list = [
            "(yes/no", "yes or no", "password", "Password", "@@@@"
        ]
        if checkhost(ssher,hostip):
            print("**********************当前就是目标环境{},不需要登陆***************************".format(hostip))
            return
        while True:
            if not checkhost(ssher,ssher.info["ip"]):
                ssher.excute_cmd("exit")
            else:
                break
    
        cmd = "ssh {}@{} -p {}".format(username, hostip, port)
        res = ssher.excute_cmd(cmd)
        time.sleep(1)
        i = 0
        while True:
            if res_list[0] in res or res_list[1] in res:
                res = ssher.excute_cmd("yes")
                time.sleep(0.5)
                res = ssher.excute_cmd(password)
            elif res_list[4] in res:
                ssher.excute_cmd("rm -f /root/.ssh/known_hosts")
                time.sleep(0.5)
                res = ssher.excute_cmd(cmd)
                time.sleep(0.5)
            elif res_list[2] in res or res_list[3] in res:
                res = ssher.excute_cmd(password)
                time.sleep(1)
                # return
                if checkhost(ssher, hostip):
                    return
                else:
                    res = ssher.excute_cmd(cmd)
            else:
                i += 1
                if i < 3:
                    time.sleep(0.05)
                    continue
                else:
                    return
    
    def ssh_exit(ssher):
        if checkhost(ssher,ssher.info["ip"]):
            return
        ssher.excute_cmd("exit")
    
    
    def checkhost(ssher, ip):
        cmd = "ip addr show | grep {}".format(ip)
        res = ssher.excute_cmd(cmd)
        if res.count(ip) > 1:
            print("*************************OK*****************************")
            return True
        else:
            print("*************************NO*****************************")
            return False
    
    def shutdown_vm(ssher, hostip,username,password,port=22):
        if hostip == ssher.info["ip"]:
            print("host机关机需要60s")
            ssher.excute_cmd("shutdown -h 1")
            return
        ssh_login(ssher,hostip,username,password,port)
        ssher.excute_cmd("shutdown now")
    
    if __name__ == "__main__":
        ip = "192.168.192.128"
        username = "root"
        password = "root"
        ssher = Ssh(ip, username, password, logfile="ssh.log")
        ssher.excute_cmd("top")
        ssher.excute_cmd("x03")        #ctrl + c
        ssher.logout()
    
  • 相关阅读:
    mysql之安装和配置(一)
    linux之cron定时任务介绍
    redis基础之开机自启动和监听(二)
    linux内网穿透自启动配置
    mysql 之修改初始密码
    Oracle-Linux安装配置python3.6环境
    redis基础之python连接redis(五)
    /etc/profile、/etc/bashrc、~/.bash_profile、~/.bashrc 文件的作用
    CentOS yum的详细使用方法
    9.2、面向对象:继承、多态
  • 原文地址:https://www.cnblogs.com/jingxindeyi/p/14141886.html
Copyright © 2011-2022 走看看