#!/usr/bin/env python
# -*- coding:utf8 -*-
# written by liYang
import paramiko
import sys
import tty
import termios
import select
import socket
import MySQLdb
class MyJump(object):
def __init__(self, port=22):
self.port = port
def __get_login_from_mysql(self):
"""
mysql> select user_name,group_name,host_name
from users,user_group,user_host
where users.group_id = user_group.group_id
and users.host_id = user_host.host_id;
+-----------+------------+----------------+
| user_name | group_name | host_name |
+-----------+------------+----------------+
| alex | staff | 192.168.122.24 |
| eric | staff | 192.168.122.23 |
| liyang | admin | 192.168.122.20 |
| seven | staff | 192.168.122.22 |
| xiyu | ops | 192.168.122.21 |
+-----------+------------+----------------+
"""
conn = MySQLdb.connect(host="127.0.0.1",
user="root",
passwd="123456",
db="hostmanager")
cur = conn.cursor()
reCount = cur.execute("select user_name,host_name,group_name \
from users,user_group,user_host \
where users.group_id = user_group.group_id \
and users.host_id = user_host.host_id;")
res = cur.fetchall()
self.__result = res
cur.close()
conn.close()
# print reCount
# print res
# print "host list: "
# for i in res:
# print "\t%s\t%s\t%s" % (i[0], i[1], i[2])
def operation(self):
print "host list: "
for i in self.__result:
print "\t%s\t%s\t%s" % (i[0], i[1], i[2])
hostname = str(raw_input("your host: "))
user = str(raw_input("your name: "))
password = str(raw_input("your password: "))
# login to remote server
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((hostname, self.port))
tran = paramiko.Transport(sock)
tran.start_client()
tran.auth_password(user, password)
chan = tran.open_session()
# 获取一个终端
chan.get_pty()
# 激活终端
chan.invoke_shell()
oldtty = termios.tcgetattr(sys.stdin)
try:
tty.setraw(sys.stdin.fileno())
chan.settimeout(0.0)
f = open("record", "a")
while True:
r, w, e = select.select([chan, sys.stdin], [], [], 1)
if chan in r:
try:
x = chan.recv(1024)
if len(x) == 0:
print '\r\n*** EOF\r\n',
f.close()
break
sys.stdout.write(x)
sys.stdout.flush()
except socket.timeout:
pass
if sys.stdin in r:
x = sys.stdin.read(1)
if len(x) == 0:
break
f.write(x)
chan.send(x)
finally:
# 重新设置终端属性
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
chan.close()
tran.close()
def run(self):
self.__get_login_from_mysql()
self.operation()
mj = MyJump()
mj.run()