zoukankan      html  css  js  c++  java
  • Python 自动化paramiko操作linux使用shell命令,以及文件上传下载linux与windows之间的实现

    #!/usr/bin/python3
    import paramiko
    import os
    import sys
    import subprocess
    curPath = os.path.abspath(os.path.dirname(__file__))
    rootPath = os.path.split(curPath)[0]
    sys.path.append(rootPath)
    from src.logutils import logger
    log=logger("root",rootstdout=True,handlerList=['I','E'])
    class SshConnect(object):
    
        def __init__(self,ip,user,pwd,port):
            self.port=port
            self.pwd=pwd
            self.user=user
            self.ip=ip
        def get_connected_client(self):
            client=paramiko.SSHClient()
            try:
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                client.connect(self.ip,self.port,self.user,self.pwd)
                if client:
                    return client
            except ConnectionError as e:
                log.error(e)
        def exe_cmd(self,shell):
            client=self.get_connected_client()
            try:
                input, out, err =client.exec_command(shell)
                res,err = out.read(),err.read()
                result = res if res else err
                if type(result).__name__ == 'bytes':
                    return result.decode('utf-8')
                elif type(result).__name__ == 'str':
                    return result
    
            except Exception as e:
                log.error(e)
            finally:
                if client:
                    client.close()
                else:
                    log.info("ssh client is null not need close")
    
    def run():
        ip='192.168.81.129'
        port=22
        pwd='admin'
        user='root'
        client=SshConnect(ip,user,pwd,port)
        res=client.exe_cmd('ps -ef|grep python&&df -m') #type should be str 
        log.info(res)
    
    # def deal_res(res):
    #     std=''
    #     for i  in res:
    #         output=i.decode("utf-8")
    #         std +=output
    #     return std
    
    if __name__ == '__main__':
        run()
    

      

    """ 
         注意点:remote_path 和 local_path , 
        路径必须为带文件名全路径只到目录路径会报:
         [Errno 13] Permission denied,若路径怕出错可以在最前面加r   """
            
    def downlodfile_from_linux(self,remote_path,local_path):
        try:
            transport = paramiko.Transport(self.host ,self.port)
            transport.connect(username=self.user,password=self.pwd)
            sftp=paramiko.SFTPClient.from_transport(transport)
            sftp.get(remotepath=remote_path,localpath=local_path)
            transport.close()
        except Exception as e:
           log.error(e)
        else:
            log.info(" download ok")
    def upload_file_to_linux(self,local_path,remote_path):
        try:
            transport = paramiko.Transport(self.host ,self.port)
            transport.connect(username=self.user,password=self.pwd)
            sftp=paramiko.SFTPClient.from_transport(transport)
            sftp.put(localpath=local_path,remotepath=remote_path)
            transport.close()
        except Exception as e:
            log.error(e)
        else:
            log.info("upload ok")
    

      

    C:\Python37\python.exe C:/Users/Administrator/PycharmProjects/checkTest/src/sshutils.py
    [INFO]2019-05-19 22:41:35 Sun --paramiko.transport-- transport.py>>_log function ::at line 1746 :
    Connected (version 2.0, client OpenSSH_7.4)
    [INFO]2019-05-19 22:41:35 Sun --paramiko.transport-- transport.py>>_log function ::at line 1746 :
    Authentication (publickey) failed.
    [INFO]2019-05-19 22:41:35 Sun --paramiko.transport-- transport.py>>_log function ::at line 1746 :
    Authentication (password) successful!
    [INFO]2019-05-19 22:41:36 Sun --root-- sshutils.py>>run function ::at line 53 :
    root 6650 1 0 16:33 ? 00:00:56 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid
    root 7294 1 0 16:33 ? 00:00:11 /usr/bin/python2 -Es /usr/sbin/tuned -l -P
    root 64041 64030 0 22:41 ? 00:00:00 bash -c ps -ef|grep python&&df -m
    root 64057 64041 0 22:41 ? 00:00:00 grep python
    Filesystem 1M-blocks Used Available Use% Mounted on
    /dev/mapper/centos-root 27627 8654 18974 32% /
    devtmpfs 894 0 894 0% /dev
    tmpfs 910 1 910 1% /dev/shm
    tmpfs 910 11 900 2% /run
    tmpfs 910 0 910 0% /sys/fs/cgroup
    /dev/sda1 1014 232 783 23% /boot
    tmpfs 182 1 182 1% /run/user/42
    tmpfs 182 0 182 0% /run/user/0

     
  • 相关阅读:
    httpclient的maven依赖
    阿里云maven仓库镜像
    log4j2在webapp项目中的配置
    web.xml中的filter标签
    mybatis在xml文件中处理大于号小于号的方法
    javaweb(三十八)——mysql事务和锁InnoDB(扩展)
    javaweb(三十八)——事务
    javaweb(三十七)——获得MySQL数据库自动生成的主键
    javaweb学习总结(三十六)——使用JDBC进行批处理
    JavaWeb(三十五)——使用JDBC处理Oracle大数据
  • 原文地址:https://www.cnblogs.com/SunshineKimi/p/10540201.html
Copyright © 2011-2022 走看看