window平台上基于python搭建一个堡垒级系统

#coding=utf-8
import getpass,select,socket,sys  
import paramiko,logging

logging.basicConfig(level=logging.DEBUG, filename='bastion.log',
          format='%(asctime)s - %(levelname)s: %(message)s')
# 定义一个Handler打印INFO及以上级别的日志到sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
# 设置日志打印格式
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
# 将定义好的console日志handler添加到root logger
logging.getLogger('').addHandler(console) 


user =raw_input('username:')
pwd =getpass.getpass('password')
dic ={'pi': ['192.168.1.105','c10.puppet.com','c11.puppet.com',],'eric': ['c100.puppet.com',]}
if user =='pi'and pwd =='123':
    logging.info('登陆成功')
    if dic.get(user,''):
        print(dic.get(user,''))
        NO=raw_input('选择ip对应NO:')
    else:
        print('你还没有访问资源,联系管理员添加')
        sys.exit()    
else:
    logging.info('登陆失败')
    sys.exit()

#主机ip 端口
hostname ='192.168.1.105'
port =22

tran =paramiko.Transport((hostname, port,))
tran.start_client()
#windows上的私钥
default_path='C:\Users\zhouzw\Downloads\id_rsa'
key =paramiko.RSAKey.from_private_key_file(default_path)
tran.auth_publickey('pi', key)
# 打开一个通道
chan =tran.open_session()
# 获取一个终端
chan.get_pty()
# 激活器
chan.invoke_shell()

##########
def windows_shell(chan):
    import threading

    sys.stdout.write("Line-buffered terminal emulation. Press F6 or ^Z to send EOF.\r\n\r\n")

    def writeall(sock):
        while True:
            data = sock.recv(256)
            if not data:
                logging.info(data)
                sys.stdout.write('\r\n*** EOF ***\r\n\r\n')
                sys.stdout.flush()
                break
            sys.stdout.write(data)
            sys.stdout.flush()

    writer = threading.Thread(target=writeall, args=(chan,))
    writer.start()

    try:
        while True:
            d = sys.stdin.read(1)
            if not d:
                break
            print d    
            logging.info(d)    
            chan.send(d)
    except EOFError:
        # user hit ^Z or F6
        pass

windows_shell(chan)
#########
chan.close()
tran.close()

你可能感兴趣的:(堡垒机,python实践,paramiko,调度系统,python)