• Python paramiko模块


    paramiko模块

      paramiko 模块是基于 Python 实现的 SSH 远程安全连接,用于 SSH 远程执行命令、文件传输等功 能。 默认 Python 没有,需要手动安装:

    安装pip:yum install python-pip -y

    安装paramiko:pip install paramiko 如安装失败,可以尝试 yum 安装:yum install python-paramiko

    SSHClient类和SFTPClient类

    SSHClient类常用的几个方法:

      1)connect:connect方法实现远程服务器连接与认证,对于方法,只有hostname是必传参数。

      2)set_missing_host_key_policy():设置远程服务器没有在know_hosts文件中记录时的应对策略。目前支持三种策略:分别是AutoAddPolicy,RejectPolicy(默认策略)与WarningPolicy,分别表示自动添加服务器到know_hosts文件、拒绝本次连接、警告并将服务器添加到know_hosts文件中。

      3)exec_command:在远程服务器执行Linux命令的方法

      4)open_sftp:在当前的ssh会话的基础上创建一个sftp会话。该方法会返回一个SFTPClient对象。

    SFTPClient类常用的方法:

    • put:上次本地文件到远程服务器
    • get:从远程服务器下载文件到本地
    • mkdir:在远程服务器上创建目录
    • remove:删除远程服务器中的文件
    • rmdir:删除远程服务器中的目录
    • rename:重命名远程服务器中文件或目录
    • stat:获取远程服务器中文件的详情信息
    • listdir:列出远程服务器中指定目录下的内容

    1)ssh密码远程执行命令

    #!/usr/bin/env python
    # coding:utf-8
    
    import paramiko
    class SSHClient(): def __init__(self,host,port,user,password): self.ssh_host = host self.ssh_port = port self.ssh_user = user self.ssh_password = password self._connect() def _connect(self): self.ssh = paramiko.SSHClient() self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: self.ssh.connect(hostname=self.ssh_host, port=self.ssh_port, username=self.ssh_user, password=self.ssh_password,timeout=10) except Exception as e: print(e) print('ssh连接失败') def execute_command(self,command): stdin,stdout,stderr = self.ssh.exec_command(command) return stdout, stderr @property def close_ssh(self): self.ssh.close() if __name__ == "__main__": ssh_obj = SSHClient('172.16.84.222',22,'root','123456') stdout,stderr = ssh_obj.execute_command('df -h') if stderr.read()=="": print(stdout.read()) #stdout.read()返回结果为一个大的字符串,而stdout.readlines()是把返回结果放到一个列表中 else: print(stderr.read()) ssh_obj.close_ssh

    2)私钥认证远程执行命令

    #!/usr/bin/env python
    # coding:utf-8
    import paramiko
    
    
    class SSHClient():
        def __init__(self,host,port,user,pkey):
            self.ssh_host = host
            self.ssh_port = port
            self.ssh_user = user
            self.private_key = paramiko.RSAKey.from_private_key_file(pkey)
            self._connect()
    
        def _connect(self):
            self.ssh = paramiko.SSHClient()
            self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            try:
                self.ssh.connect(hostname=self.ssh_host,
                                 port=self.ssh_port,
                                 username=self.ssh_user,
                                 pkey=self.private_key,timeout=10)
        except Exception as e:
               print(e)
               print('ssh连接失败')
    
        def execute_command(self,command):
            stdin,stdout,stderr = self.ssh.exec_command(command)
            return stdout, stderr
    
        @property
        def close_ssh(self):
            self.ssh.close()
    
        
    if __name__ == "__main__":
        ssh_obj = SSHClient('172.16.84.222',22,'root','/root/.ssh/id_rsa')
        stdout,stderr = ssh_obj.execute_command('df -h')
        if stderr.read()=="":
             print(stdout.read())
        else:
             print(stderr.read())
        ssh_obj.close_ssh

    3)上传文件到远程服务器

      基于以上代码我们可以直接打开一个sftp会话或这直接创建SFTPClient类来使用,可参考一下示例代码:

    #!/usr/bin/env python
    # coding:utf-8
    
    import paramiko
    
    def deploy_monitor(ip):
    
        with paramiko.SSHClient() as client:
            client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            client.connect(hostname=ssh_host,
                             port=ssh_port,
                             username=ssh_user,
                             password=ssh_password,timeout=10)
            stdin,stdout,stderr=client.exec_command('ls -l')
            print(stdout.readlines())
    
            with client.open_sftp() as sftp:
                sftp.put('monitor.py','monitor.py')
                sftp.chmod('monitor.py',0075)
    
    def main():
        with open('hosts') as f:
            for line in f:
                 deploy_monitor(line.strip())
    
     
    if __name__ == "__main__":
        main()

      以上除了使用Python的上下文管理器进行及时关闭连接,还是调用对象的close方法进行关闭连接。

  • 相关阅读:
    python的mysql-connector和pymysql
    java知识整理
    Spring——使用自定义标签
    Eclipse maven 错误修正方法:An error occurred while filtering resources
    设计模式--模板模式
    编译Spring源码
    Lunix 命令
    (转)设计模式——策略模式
    JVM(一)
    SenjuFamily项目总结 之 Activiti 学习总结(一)
  • 原文地址:https://www.cnblogs.com/wushaoyu/p/15231466.html
Copyright © 2020-2023  润新知