difflib paramiko模块

difflib模块

import difflib
# 1. 以字符串方式展示两个文本的不同, 效果如下:
text1 = '''  
    1. Beautiful is better than ugly.
    2. Explicit is better than implicit.
    3. Simple is better than complex.
    4. Complex is better than complicated.
'''.splitlines(keepends=True)
text2 = '''  
    1. Beautifu  is better than ugly.
    2. Explicit is better than implicit.
    3. Simple is better than complex.
    4. Complex is better than complicated.
'''.splitlines(keepends=True)
d = difflib.Differ()
result = list(d.compare(text1,text2))
result = " ".join(result)
print(result)
# 2. 以html方式展示两个文本的不同, 浏览器打开:
d = difflib.HtmlDiff()
with open('passwd.html','w') as f:
    f.write(d.make_file(text1,text2))

这里写图片描述
这里写图片描述
eg:比较两个文件的不同

import difflib
file1 = '/etc/passwd'
file2 = '/tmp/passwd'
with open(file1) as f1,open(file2) as f2:
    text1 = f1.readlines()
    text2 =f2.readlines()
d = difflib.HtmlDiff()
with open('passwd1.html','w') as f:
    f.write(d.make_file(text1,text2))

paramiko模块

paramiko远程密码连接

基于ssh用于连接远程服务器做操作:远程执行命令, 上传文件, 下载文件

import paramiko
# 创建一个ssh对象;
client = paramiko.SSHClient()
#  解决问题:如果之前没有;连接过的ip, 会出现
# Are you sure you want to continue connecting (yes/no)? yes
# 自动选择yes
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#  连接服务器
client.connect(hostname='172.25.254.178',
               port=22,
               username='root',
               password='westos'
               )
# 执行操作
stdin,stdout,stderr=client.exec_command('hostname')
#获取命令的执行结果;
result = stdout.read().decode('utf-8')
print(result)
print(stderr.read())
# 关闭连接
client.close()

这里写图片描述

基于公钥的远程连接
import paramiko
from paramiko.ssh_exception import NoValidConnectionsError,AuthenticationException
def connect(cmd,hostname,port=22,user='root'):
# 创建一个ssh对象;
    client = paramiko.SSHClient()
    # 返回一个私钥对象
    private_key = paramiko.RSAKey.from_private_key_file('id_rsa')
  # 2. 解决问题:如果之前没有;连接过的ip, 会出现
    # Are you sure you want to continue connecting (yes/no)? yes
    # 自动选择yesclient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
     # 3. 连接服务器
        client.connect(hostname=hostname,
                       port=port,
                       username=user,
                       pkey=private_key)
        # 4. 执行操作
        stdin, stdout, stderr = client.exec_command(cmd)
    except NoValidConnectionsError as e:
        print("连接失败")
    except AuthenticationException as e:
        print("密码错误")
    else:
        # 5. 获取命令的执行结果;
        result = stdout.read().decode('utf-8')
        print(result)
    finally:
        # 6. 关闭连接
        client.close()
if __name__=='__main__':
#批量连接,操作
    # for count in range(254):
    #     host = '172.25.254.%s' % (count + 1)
    #     print(host.center(50, '*'))
    #     connect('hostname', host)
    connect('hostname','172.25.254.246')

这里写图片描述

基于用户名密码的上传和下载

import paramiko
transport = paramiko.Transport(('172.25.254.246',22))
transport.connect(
    username='root',
    password='westos'
)
sftp = paramiko.SFTPClient.from_transport(transport)
# 上传文件, 包含文件名
sftp.put('/home/kiosk/Desktop/rhcsa-exam','/mnt/rhcsa-exam')
sftp.get('/mnt/rhcsa-exam','/home/kiosk/Desktop/rhcsa1-exam')

这里写图片描述

基于密钥上传下载

import  paramiko

# 返回一个私钥对象
private_key = paramiko.RSAKey.from_private_key_file('id_rsa')

transport = paramiko.Transport(('172.25.254.246', 22))
transport.connect(username='root',pkey=private_key)
sftp = paramiko.SFTPClient.from_transport(transport)
# 上传文件, 包含文件名
sftp.put('/home/kiosk/Desktop/rhcsa-exam', '/mnt/rhcsa2-exam')
sftp.get('/mnt/rhcsa2-exam', '/home/kiosk/Desktop/rhcsa2-exam')
transport.close()

这里写图片描述

paramiko的封装

import os
import paramiko
from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException, SSHException


class SshRemoteHost(object):
    def __init__(self, hostname, port, user, passwd, cmd):
        # 指的不是shell命令
        #   cmd shell命令
        #   put
        #   get
        self.hostname  = hostname
        self.port = port
        self.user = user
        self.passwd = passwd
        self.cmd = cmd
    def run(self):
        """默认调用的内容"""
        # cmd hostname
        # put
        # get
        cmd_str =  self.cmd.split()[0] # cmd
        # 类的反射, 判断类里面是否可以支持该操作?
        if hasattr(self, 'do_'+ cmd_str):  # do_cmd
            getattr(self, 'do_'+cmd_str)()
        else:
            print("目前不支持该功能")
    def do_cmd(self):
        # 创建一个ssh对象;
        client = paramiko.SSHClient()

        # 2. 解决问题:如果之前没有;连接过的ip, 会出现
        # Are you sure you want to continue connecting (yes/no)? yes
        # 自动选择yes
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        try:
            # 3. 连接服务器
            client.connect(hostname=self.hostname,
                           port=self.port,
                           username=self.user,
                           password=self.passwd)

            print("正在连接主机%s......." % (self.hostname))
        except NoValidConnectionsError as e:
            print("连接失败")
        except AuthenticationException as e:
            print("密码错误")
        else:
            # 4. 执行操作
            # cmd uname
            # cmd ls /etc/
            # *******注意:
            cmd = ' '.join(self.cmd.split()[1:])
            stdin, stdout, stderr = client.exec_command(cmd)

            # 5. 获取命令的执行结果;
            result = stdout.read().decode('utf-8')
            print(result)

            # 6. 关闭连接
            client.close()
    def do_put(self):
        # put /tmp/passwd /tmp/passwd
        # put /tmp/passwd /tmp/pwd
        # put /tmp/passwd   # 将本机的/tmp/passwd文件上传到远程主机的/tmp/passwd;
        print("正在上传.....")
        try:
            transport = paramiko.Transport((self.hostname, int(self.port)))
            transport.connect(username=self.user, password=self.passwd)
        except SSHException as e:
            print("连接失败")
        else:
            sftp = paramiko.SFTPClient.from_transport(transport)
            newCmd  = self.cmd.split()[1:]
            if len(newCmd) == 2:
                # 上传文件, 包含文件名
                sftp.put(newCmd[0], newCmd[1])
                print("%s文件上传到%s主机的%s文件成功" %(newCmd[0],
                                             self.hostname,  newCmd[1]))
            else:
                print("上传文件信息错误")

            transport.close()

    def do_get(self):
        # 2. 根据选择的主机组, 显示包含的主机IP/主机名;
        # 3. 让用户确认信息, 选择需要批量执行的命令;
        #       - cmd shell命令
        #       - put 本地文件 远程文件
        #       - get 远程文件  本地文件
        print("正在下载.....")
        try:
            transport = paramiko.Transport((self.hostname, int(self.port)))
            transport.connect(username=self.user, password=self.passwd)
        except SSHException as e:
            print("连接失败")
        else:
            sftp = paramiko.SFTPClient.from_transport(transport)
            newCmd  = self.cmd.split()[1:]
            if len(newCmd) == 2:
                # 上传文件, 包含文件名
                sftp.get(newCmd[0], newCmd[1])
                print("下载文件成功" )
            else:
                print("下载文件信息错误")
            transport.close()

def main():
    # 1. 选择操作的主机组:eg: mysql, web, ftp
    groups = [file.rstrip('.conf') for file in os.listdir('conf')]
    print("主机组显示:".center(50, '*'))
    for group in groups: print('\t', group)
    choiceGroup = input("清选择批量操作的主机组(eg:web):")

    # 2. 根据选择的主机组, 显示包含的主机IP/主机名;
    #   1). 打开文件conf/choiceGroup.conf
    #   2). 依次读取文件每一行,
    #   3). 只拿出ip

    print("主机组包含主机:".center(50, '*'))
    with open('conf/%s.conf' %(choiceGroup)) as f:
        for line in f:
            print(line.split(':')[0])
        f.seek(0,0)  # 把指针移动到文件最开始
        hostinfos = [line.strip() for line in f.readlines()]
    # 3. 让用户确认信息, 选择需要批量执行的命令;
    print("批量执行脚本".center(50, '*'))
    while True:
        cmd = input(">>:").strip()  # cmd uname
        if cmd:
            if cmd == 'exit' or cmd =='quit':
                print("执行结束, 退出中......")
                break
            # 依次让该主机组的所有主机执行
            for info in hostinfos:
                # 'ip:port:user:passwd'
                host, port, user, passwd = info.split(":")
                print(host.center(50, '-'))
                clientObj = SshRemoteHost(host, port, user, passwd, cmd)
                clientObj.run()
if __name__ == '__main__':
    main()

这里写图片描述
这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42635252/article/details/82631888