您的位置:首页 > 编程语言 > Python开发

Python paramiko 实现堡垒机功能

2016-11-14 10:58 369 查看

1、安装 paramiko

yum install -y python-paramiko


2、修改文件 interactive.py

# 增加两个传递参数 username和hostname
def interactive_shell(chan , username , hostname):
if has_termios:
posix_shell(chan , username , hostname)
else:
windows_shell(chan)
# 增加两个参数 username和hostname
def posix_shell(chan , username , hostname ):
# 记录操作的文件,登录 用户名和登录的机器,这里的用户名是 登录堡垒机的用户名,已追加的方式打开
f=file('/tmp/%s-%s-audit.log' % (username , hostname) , 'a+') ;
import select
#导入python time包
import time
oldtty = termios.tcgetattr(sys.stdin)
try:
tty.setraw(sys.stdin.fileno())
tty.setcbreak(sys.stdin.fileno())
chan.settimeout(0.0)
#当前操作员敲入的字符
currentX=''
#当前完整的命令
full_cmd=''
while True:
inp=sys.stdin
r, w, e = select.select([chan, inp], [], [])
if chan in r:
try:
x = chan.recv(1024)
if len(x) == 0:
print '\r\n*** EOF\r\n',
break
# 判断操作员输入的不是回车键,就将屏幕上打印的字符记录下来,保存到full_cmd变量中
if currentX != '\r':
cmdArray=x.split('\n')
cmd = cmdArray[0]
cmdArray = cmd.split(' ')
new_cmd = cmdArray[len(cmdArray) - 1]
if '' != new_cmd:
cmd = new_cmd
full_cmd=full_cmd+cmd
#f.write('%s\n' % cmd);
#f.flush()
#当用户输入回车键时,full_cmd不为空 就保存到日志文件中
elif '' != full_cmd:
f.write('%s |  %s | %s\n' % ( hostname , time.strftime('%Y-%m-%d %H:%M:%S') ,full_cmd));
f.flush()
full_cmd=''
sys.stdout.write(x)
sys.stdout.flush()
except socket.timeout:
pass
if sys.stdin in r:
x = sys.stdin.read(1)
#保存用户当前输入的字符
currentX=x
#如果操作员输入空格,这里在命令中加入一个空格
if x == ' ':
full_cmd=full_cmd+' ';
if len(x) == 0:
break
chan.send(x)
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)


3、新建menu.py

#!/usr/bin/evn python
# -*- coding:utf8 -*-
import os
msg = """
\033[42;1m      欢迎登录Gary认证系统   \033[0m
"""
print msg

host_dic = {
"root@192.168.1.10":'123456' ,
"root@192.168.1.123":"123456"
}
while True:
for host , pwd in host_dic.items():
print host
try:
host = raw_input("请选择登录的服务器:").strip();
print host
if host=='quit':
print "Goodbye!"
os.system("logout")
break;
except KeyboardInterrupt:continue
except EOFError:continue
if len(host) == 0:continue
if not host_dic.has_key(host):
print "找不到您要登录的机器,请再试一次。"
continue
print "\033[32;1m 正在链接 \033[0m" ,host
os.system("python demo.py %s %s" % (host , host_dic[host]) )


修改demo.py ,在大约154行的位置,如果参数有密码,就直接用密码登录客户机

154     if not t.is_authenticated():
155         if len(sys.argv) > 2:
156           t.auth_password(username, sys.argv[2])
157         else:
158           manual_auth(username, hostname)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: