• ssh paramiko && subprocess


    subprocess:

    #!/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
            try:
                client=paramiko.SSHClient()
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                client.connect(self.ip,self.port,self.user,self.pwd)
                self.client=client
            except ConnectionError as e:
                log.error(e)
        def exe_cmd(self,shell):
                stdin, stdout, stderr = self.client.exec_command(shell)
                res,err = stdout.read(),stderr.read()
                result = res if res else err
                return result
                # print(result.decode("utf-8"))
        def close_client(self):
            self.client.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&&ifconfig')
        log.info(res)
    
    def run_sshpass():
        shell=" ps -ef|grep java&&df -m"
        sub=subprocess.Popen(shell,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
        sub.wait(timeout=20)
        res=sub.stdout.readlines()
        log.info(deal_res(res))
    
    def deal_res(res):
        std=''
        for i  in res:
    
            output=i.decode("utf-8")
    
            std +=output
        return std
    
    if __name__ == '__main__':
        run_sshpass()
        #run()
    [root@hostuser src]# 
    

      

    [root@hostuser src]# python3 sshutils.py 
    [INFO]2019-05-14 00:31:27 Tue --root-- sshutils.py:
    root      28680  28677  0 00:31 pts/0    00:00:00 /bin/sh -c  ps -ef|grep java&&df -m
    root      28683  28680  0 00:31 pts/0    00:00:00 grep java
    Filesystem              1M-blocks  Used Available Use% Mounted on
    /dev/mapper/centos-root     27627  8616     19012  32% /
    devtmpfs                      894     0       894   0% /dev
    tmpfs                         910     1       910   1% /dev/shm
    tmpfs                         910    10       901   2% /run
    tmpfs                         910     0       910   0% /sys/fs/cgroup
    /dev/sda1                    1014   232       783  23% /boot
    

      paramiko:

    #!/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
            try:
                client=paramiko.SSHClient()
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                client.connect(self.ip,self.port,self.user,self.pwd)
                self.client=client
            except ConnectionError as e:
                log.error(e)
        def exe_cmd(self,shell):
                stdin, stdout, stderr = self.client.exec_command(shell)
                res,err = stdout.read(),stderr.read()
                result = res if res else err
                return result
                # print(result.decode("utf-8"))
        def close_client(self):
            self.client.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&&ifconfig')
        log.info(res)
    
    def run_sshpass():
        shell=" ps -ef|grep java&&df -m"
        sub=subprocess.Popen(shell,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
        sub.wait(timeout=20)
        res=sub.stdout.readlines()
        log.info(deal_res(res))
    
    def deal_res(res):
       res1= res.decode("utf-8")
       
       return res1
    
    if __name__ == '__main__':
        #run_sshpass()
        run()
    [root@hostuser src]# vi sshutils.py 
    [root@hostuser src]# python3 sshutils.py 
    [INFO]2019-05-14 00:28:19 Tue --paramiko.transport-- transport.py:
    Connected (version 2.0, client OpenSSH_7.4)
    /usr/local/lib/python3.7/site-packages/paramiko/kex_ecdh_nist.py:39: CryptographyDeprecationWarning: encode_point has been deprecated on EllipticCurvePublicNumbers and will be removed in a future version. Please use EllipticCurvePublicKey.public_bytes to obtain both compressed and uncompressed point encoding.
      m.add_string(self.Q_C.public_numbers().encode_point())
    /usr/local/lib/python3.7/site-packages/paramiko/kex_ecdh_nist.py:96: CryptographyDeprecationWarning: Support for unsafe construction of public numbers from encoded data will be removed in a future version. Please use EllipticCurvePublicKey.from_encoded_point
      self.curve, Q_S_bytes
    /usr/local/lib/python3.7/site-packages/paramiko/kex_ecdh_nist.py:111: CryptographyDeprecationWarning: encode_point has been deprecated on EllipticCurvePublicNumbers and will be removed in a future version. Please use EllipticCurvePublicKey.public_bytes to obtain both compressed and uncompressed point encoding.
      hm.add_string(self.Q_C.public_numbers().encode_point())
    [INFO]2019-05-14 00:28:19 Tue --paramiko.transport-- transport.py:
    Authentication (publickey) failed.
    [INFO]2019-05-14 00:28:19 Tue --paramiko.transport-- transport.py:
    Authentication (password) successful!
    [INFO]2019-05-14 00:28:45 Tue --root-- sshutils.py:
    b'root      28245  16287  2 00:28 pts/0    00:00:00 python3 sshutils.py
    root      28310  28248  0 00:28 ?        00:00:00 bash -c ps -ef|grep python&&ifconfig
    root      28326  28310  0 00:28 ?        00:00:00 grep python
    ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
            inet 192.168.81.129  netmask 255.255.255.0  broadcast 192.168.81.255
            inet6 fe80::f08c:a9:42b2:6ec4  prefixlen 64  scopeid 0x20<link>
            ether 00:0c:29:11:d6:35  txqueuelen 1000  (Ethernet)
            RX packets 7533  bytes 640098 (625.0 KiB)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 6119  bytes 755348 (737.6 KiB)
            TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
    
    lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
            inet 127.0.0.1  netmask 255.0.0.0
            inet6 ::1  prefixlen 128  scopeid 0x10<host>
            loop  txqueuelen 1000  (Local Loopback)
            RX packets 52950  bytes 43181732 (41.1 MiB)
            RX errors 0  dropped 0  overruns 0  frame 0
            TX packets 52950  bytes 43181732 (41.1 MiB)
            TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
    
    '
    

      

  • 相关阅读:
    VMware的安装
    草根创业专题开篇
    转:分布式和集中式版本控制工具svn,git,mercurial
    sql db to sqlite
    简单办公自动化系统开发与思考1
    sql ef datacontext muti thread problem
    谈云计算,服务器运算的惊天骗局
    ios5.1二货,手贱,解决方案
    阿曹的创业点子1人人快递
    创业点子wifi anywhere
  • 原文地址:https://www.cnblogs.com/SunshineKimi/p/10859935.html
Copyright © 2020-2023  润新知