zoukankan      html  css  js  c++  java
  • paramiko_su_root

    #coding=utf8
    import paramiko
    import time
    import logging
    
    '''
    if user root,can not login,must use user xx and then switch to root
    
    not root ,then run
    
    '''
    
    def  _conn_root(ip,port,username,passwd,cmd):
        s = paramiko.SSHClient()
        s.load_system_host_keys()
        s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
        #此处写入一个用于登录的用户
            s.connect(hostname=ip, port=int(port), username='xx', password='xx')
        except:
            logging.info('err: can not conn %s ,pls check %s and password of xx',(ip,ip))
    
        if username == 'root' or  'xx':
            ssh = s.invoke_shell()
            time.sleep(1)
            if username=='xx':
               ssh.send('su - xx
    ')
            else:
                ssh.send('su -
    ')
            buff = ''
            while not buff.endswith('Password: '):
                resp = ssh.recv(2048)
                buff += resp
            ssh.send(passwd)
            ssh.send('
    ')
            buff = ''
            while not buff.endswith('# '):
                resp = ssh.recv(2048)
                buff += resp
            ssh.send(cmd)
            ssh.send('
    ')
            buff = ''
            time.sleep(1)
            resp = ssh.recv(2048)
            resp = ''
            while not buff.endswith('# '):
                resp = ssh.recv(2048)
                print resp
                buff += resp
            s.close()
            result = buff
        else:
            stdin, stdout, stderr = s.exec_command(cmd)
            result = stdout.read()
            s.close()
    
        return result
    
    def _conn_nomal(ip,port,username,passwd,cmd):
        s = paramiko.SSHClient()
        s.load_system_host_keys()
        s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
           s.connect(hostname=host, port=int(port), username=username, password=password)
        except:
            logging.info('err: can not connect %s ,pls check %s and user && password',(ip,ip))
        #'get result'
        stdin, stdout, stderr = s.exec_command(cmd)
        result = stdout.read()
        s.close()
        return result
    
    
    def Connect(ip,port=22,username='xx',passwd='xx',cmd='echo '):
    
            if username=='root' or 'xx':
                return _conn_root(ip,port,username,passwd,cmd)
            else:
                return _conn_nomal(ip,port,username,passwd,cmd)
    

      

  • 相关阅读:
    洛谷P2522 [HAOI2011]Problem b(莫比乌斯反演)
    洛谷P3327 [SDOI2015]约数个数和(莫比乌斯反演)
    Informatica PowerCenter 常用转换组件一览表
    Informatica_(3)组件
    Informatica_(2)第一个例子
    Informatica_(1)安装
    InformaticaPowerCenter调用存储过程
    Informatica 9.5.1 安装配置
    Linux字符集的查看及修改
    Redis-3.2.9集群配置(redis cluster)
  • 原文地址:https://www.cnblogs.com/EWWE/p/8018850.html
Copyright © 2011-2022 走看看