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\n')
        else:
            ssh.send('su -\n')
        buff = ''
        while not buff.endswith('Password: '):
            resp = ssh.recv(2048)
            buff += resp
        ssh.send(passwd)
        ssh.send('\n')
        buff = ''
        while not buff.endswith('# '):
            resp = ssh.recv(2048)
            buff += resp
        ssh.send(cmd)
        ssh.send('\n')
        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)

  

posted on 2017-12-10 23:44 EWWE 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/EWWE/p/8018850.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值