Commit 803dc9c5 authored by ibuler's avatar ibuler

准备完工

parent 5426116e
#coding: utf-8 #coding: utf-8
import socket import socket
import sys import sys
import os import os
import select import select
import time import time
import paramiko import paramiko
import struct import struct
import fcntl import fcntl
import signal import signal
import textwrap
try: import django
import termios from django.core.exceptions import ObjectDoesNotExist
import tty from Crypto.Cipher import AES
except ImportError: from binascii import b2a_hex, a2b_hex
print '\033[1;31mOnly postfix supported.\033[0m'
sys.exit() os.environ['DJANGO_SETTINGS_MODULE'] = 'AutoSa.settings'
django.setup()
CURRENT_DIR = os.path.abspath('.') from juser.models import User, Group
LOG_DIR = os.path.join(CURRENT_DIR, 'logs') from jasset.models import Asset, IDC
from jpermission.models import Permission
def green_print(string): try:
print '\033[1;32m%s\033[0m' % string import termios
import tty
except ImportError:
def red_print(string): print '\033[1;31mOnly postfix supported.\033[0m'
print '\033[1;31m%s\033[0m' % string sys.exit()
def alert_print(string): CURRENT_DIR = os.path.abspath('.')
red_print('AlertError: %s' % string) LOG_DIR = os.path.join(CURRENT_DIR, 'logs')
time.sleep(2)
sys.exit()
def green_print(string):
print '\033[1;32m%s\033[0m' % string
def get_win_size():
"""This function use to get the size of the windows!"""
if 'TIOCGWINSZ' in dir(termios): def red_print(string):
TIOCGWINSZ = termios.TIOCGWINSZ print '\033[1;31m%s\033[0m' % string
else:
TIOCGWINSZ = 1074295912L # Assume
s = struct.pack('HHHH', 0, 0, 0, 0) def alert_print(string):
x = fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ, s) red_print('AlertError: %s' % string)
return struct.unpack('HHHH', x)[0:2] time.sleep(2)
sys.exit()
def set_win_size(sig, data):
"""This function use to set the window size of the terminal!""" class PyCrypt(object):
try: """It's used to encrypt and decrypt password."""
win_size = get_win_size() def __init__(self, key):
channel.resize_pty(height=win_size[0], width=win_size[1]) self.key = key
except: self.mode = AES.MODE_CBC
pass
def encrypt(self, text):
cryptor = AES.new(self.key, self.mode, b'0000000000000000')
def posix_shell(chan, user, host): length = 16
""" count = len(text)
Use paramiko channel connect server and logging. if count < length:
""" add = (length - count)
connect_log_dir = os.path.join(LOG_DIR, 'connect') text += ('\0' * add)
today = time.strftime('%Y%m%d') elif count > length:
date_now = time.strftime('%Y%m%d%H%M%S') add = (length - (count % length))
today_connect_log_dir = os.path.join(connect_log_dir, today) text += ('\0' * add)
log_filename = '%s_%s_%s.log' % (user, host, date_now) ciphertext = cryptor.encrypt(text)
log_file_path = os.path.join(today_connect_log_dir, log_filename) return b2a_hex(ciphertext)
if not os.path.isdir(today_connect_log_dir): def decrypt(self, text):
try: cryptor = AES.new(self.key, self.mode, b'0000000000000000')
os.makedirs(today_connect_log_dir) plain_text = cryptor.decrypt(a2b_hex(text))
except OSError: return plain_text.rstrip('\0')
alert_print('Create %s failed, Please modify %s permission.' % (today_connect_log_dir, connect_log_dir))
try: def get_win_size():
log = open(log_file_path, 'a') """This function use to get the size of the windows!"""
except IOError: if 'TIOCGWINSZ' in dir(termios):
alert_print('Create logfile failed, Please modify %s permission.' % today_connect_log_dir) TIOCGWINSZ = termios.TIOCGWINSZ
else:
old_tty = termios.tcgetattr(sys.stdin) TIOCGWINSZ = 1074295912L # Assume
try: s = struct.pack('HHHH', 0, 0, 0, 0)
tty.setraw(sys.stdin.fileno()) x = fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ, s)
tty.setcbreak(sys.stdin.fileno()) return struct.unpack('HHHH', x)[0:2]
chan.settimeout(0.0)
while True: def set_win_size(sig, data):
try: """This function use to set the window size of the terminal!"""
r, w, e = select.select([chan, sys.stdin], [], []) try:
except: win_size = get_win_size()
pass channel.resize_pty(height=win_size[0], width=win_size[1])
except:
if chan in r: pass
try:
x = chan.recv(1024)
if len(x) == 0: def posix_shell(chan, user, host):
break """
sys.stdout.write(x) Use paramiko channel connect server and logging.
sys.stdout.flush() """
log.write(x) connect_log_dir = os.path.join(LOG_DIR, 'connect')
log.flush() today = time.strftime('%Y%m%d')
except socket.timeout: date_now = time.strftime('%Y%m%d%H%M%S')
pass today_connect_log_dir = os.path.join(connect_log_dir, today)
log_filename = '%s_%s_%s.log' % (user, host, date_now)
if sys.stdin in r: log_file_path = os.path.join(today_connect_log_dir, log_filename)
x = os.read(sys.stdin.fileno(), 1)
if len(x) == 0: if not os.path.isdir(today_connect_log_dir):
break try:
chan.send(x) os.makedirs(today_connect_log_dir)
except OSError:
finally: alert_print('Create %s failed, Please modify %s permission.' % (today_connect_log_dir, connect_log_dir))
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
log.close() try:
log = open(log_file_path, 'a')
except IOError:
def connect(username, password, host, port): alert_print('Create logfile failed, Please modify %s permission.' % today_connect_log_dir)
"""
Connect server. old_tty = termios.tcgetattr(sys.stdin)
""" try:
ps1 = "PS1='[\u@%s \W]\$ '\n" % host tty.setraw(sys.stdin.fileno())
login_msg = "clear;echo -e '\\033[32mLogin %s done. Enjoy it.\\033[0m'\n" % host tty.setcbreak(sys.stdin.fileno())
chan.settimeout(0.0)
# Make a ssh connection
ssh = paramiko.SSHClient() while True:
ssh.load_system_host_keys() try:
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) r, w, e = select.select([chan, sys.stdin], [], [])
try: except:
ssh.connect(host, port=port, username=username, password=password, compress=True) pass
except paramiko.ssh_exception.AuthenticationException:
alert_print('Host Password Error, Please Correct it.') if chan in r:
except socket.error: try:
alert_print('Connect SSH Socket Port Error, Please Correct it.') x = chan.recv(1024)
if len(x) == 0:
# Make a channel and set windows size break
global channel sys.stdout.write(x)
channel = ssh.invoke_shell() sys.stdout.flush()
win_size = get_win_size() log.write(x)
channel.resize_pty(height=win_size[0], width=win_size[1]) log.flush()
try: except socket.timeout:
signal.signal(signal.SIGWINCH, set_win_size) pass
except:
pass if sys.stdin in r:
x = os.read(sys.stdin.fileno(), 1)
# Set PS1 and msg it if len(x) == 0:
channel.send(ps1) break
channel.send(login_msg) chan.send(x)
print channel.get_name()
finally:
# Make ssh interactive tunnel termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)
posix_shell(channel, username, host) log.close()
# Shutdown channel socket
channel.close() def get_host_all(username):
ssh.close() host_all = {}
try:
user = User.objects.get(username=username)
if __name__ == '__main__': except AttributeError:
connect('guanghongwei', 'Lov@j1ax1n', '172.16.1.122', 2001) red_print("Don't Use Root To Do That or User isn't Exist.")
else:
perm_all = user.permission_set.all()
for perm in perm_all:
host_all[perm.asset.ip] = perm.asset.comment
return host_all
def print_prompt():
msg = """
\033[1;32m### Welcome Use JumpServer To Login. ### \033[0m
1) Type \033[32mIP ADDRESS\033[0m To Login.
2) Type \033[32mP/p\033[0m To Print The Servers You Available.
3) Type \033[32mE/e\033[0m To Execute Command On Several Servers.
4) Type \033[32mQ/q\033[0m To Quit.
"""
print textwrap.dedent(msg)
def print_user_host(username):
host_all = get_host_all(username)
for ip, comment in host_all.items():
print '%s -- %s' % (ip, comment)
def connect(username, password, host, port):
"""
Connect server.
"""
ps1 = "PS1='[\u@%s \W]\$ '\n" % host
login_msg = "clear;echo -e '\\033[32mLogin %s done. Enjoy it.\\033[0m'\n" % host
# Make a ssh connection
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(host, port=port, username=username, password=password, compress=True)
except paramiko.ssh_exception.AuthenticationException:
alert_print('Host Password Error, Please Correct it.')
except socket.error:
alert_print('Connect SSH Socket Port Error, Please Correct it.')
# Make a channel and set windows size
global channel
channel = ssh.invoke_shell()
win_size = get_win_size()
channel.resize_pty(height=win_size[0], width=win_size[1])
try:
signal.signal(signal.SIGWINCH, set_win_size)
except:
pass
# Set PS1 and msg it
channel.send(ps1)
channel.send(login_msg)
print channel.get_name()
# Make ssh interactive tunnel
posix_shell(channel, username, host)
# Shutdown channel socket
channel.close()
ssh.close()
if __name__ == '__main__':
username = os.getlogin()
print_prompt()
try:
while True:
try:
option = raw_input("\033[1;32mOpt or IP>:\033[0m ")
except EOFError:
continue
if option in ['P', 'p']:
print_user_host()
continue
elif option in ['E', 'e']:
pass
elif option in ['Q', 'q']:
sys.exit()
else:
pass
except IndexError:
pass
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment