python登录linux服务器脚本

写一个python登录脚本   需要一个配置文件  里面需要写一个字典  字典里面包含有需要登录机器的账号密码以及IP地址还有端口

#coding: utf-8
import MySQLdb
import sys
import os 
import re
import time
import paramiko
import struct
import fcntl
import select 
import textwrap
import pexpect
import subprocess
import socket
import signal

LOGIN_NAME = 'panzi'
from serverinfo import *

class ServerError(Exception):
    pass

try:
    import termios
    import tty
except ImportError:
    print '\033[1;31mOnly UnixLike supported.\033[0m'
    time.sleep(3)
    sys.exit()

def get_win_size():
    """This function use to get the size of the windows!"""
    if 'TIOCGWINSZ' in dir(termios):
        TIOCGWINSZ = termios.TIOCGWINSZ
    else:
        TIOCGWINSZ = 1074295912L  # Assume
    s = struct.pack('HHHH', 0, 0, 0, 0)
    x = fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ, s)
    return struct.unpack('HHHH', x)[0:2]

def posix_shell(chan, username, host):
    """
    Use paramiko channel connect server interactive.
    """
    old_tty = termios.tcgetattr(sys.stdin)
    try:
        tty.setraw(sys.stdin.fileno())
        tty.setcbreak(sys.stdin.fileno())
        chan.settimeout(0.0)
        
        while True:
            try:
                r, w, e = select.select([chan, sys.stdin], [], [])
            except:
                pass

            if chan in r:
                try:
                    x = chan.recv(1024)
                    if len(x) == 0:
                        break
                    sys.stdout.write(x)
                    sys.stdout.flush()
                except socket.timeout:
                    pass

            if sys.stdin in r:
                x = os.read(sys.stdin.fileno(), 1)
                if len(x) == 0:
                    break
                chan.send(x)

    finally:
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)



def set_win_size(sig, data):
    """This function use to set the window size of the terminal!"""
    try:
        win_size = get_win_size()
        channel.resize_pty(height=win_size[0], width=win_size[1])
    except:
        pass

def sigwinch_passthrough(sig, data):
    winsize=get_win_size()
    global foo
    foo.setwinsize(winsize[0],winsize[1])

def print_prompt():
    msg="""
    1) 查看非开放平台机器的服务器 \033[32mE/e\033[0m
    2) 进入页游请输入 \033[32mY/y\033[0m
    3) 进入手游请输入 \033[32mS/s\033[0m
    4) 进入其他机器请输入 \033[32mH/h\033[0m
    5)退出请输入 \033[32mQ/q\033[0m 
    """
    print textwrap.dedent(msg)

def connect(username,password,host,port,login_name):
    ps1 = "PS1='[\u@%s \W]\$ '\n" % host
    login_msg = "clear;echo -e '\\033[32mLogin %s done. Enjoy it.\\033[0m'\n" % host
    
    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)
#        ssh.connect(host, port=port, username=username, password=password)
    except paramiko.ssh_exception.AuthenticationException, paramiko.ssh_exception.SSHException:
        raise ServerError('Authentication Error.')
    except socket.error:
        raise ServerError('Connect SSH Socket Port Error, Please Correct it.')
    
    global channel
    win_size = get_win_size()
    channel = ssh.invoke_shell(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)

    # Make ssh interactive tunnel
    posix_shell(channel, login_name, host)

    # Shutdown channel socket
    channel.close()
    ssh.close()


def verify_connect(username, part_ip):
    ip_matched = []
    try:
        hosts_attr = get_user_host(username)
        hosts = hosts_attr.values()
    except ServerError, e:
        color_print(e, 'red')
        return False

    for ip_info in hosts:
        for info in ip_info[1:]:
            if part_ip in info:
                ip_matched.append(ip_info[1])

    ip_matched = list(set(ip_matched))
    if len(ip_matched) > 1:
        for ip in ip_matched:
            print '%-15s -- %s' % (ip, hosts_attr[ip][2])
    elif len(ip_matched) < 1:
        color_print('No Permission or No host.', 'red')
    else:
        username, password, host, port = get_connect_item(username, ip_matched[0])
        connect(username, password, host, port, LOGIN_NAME)

def connectto(username,password,host):
    username=username
    password=password
    ip=host
    global foo
    try:
        foo = pexpect.spawn('/usr/bin/ssh -q -o StrictHostKeyChecking=no %s@%s -p36001' % (username,ip))
        foo.expect('.*ssword:')
        foo.sendline(password)
        signal.signal(signal.SIGWINCH, sigwinch_passthrough)
        size = get_win_size()
        foo.setwinsize(size[0], size[1])
        foo.interact() 
    except socket.error:
        raise ServerError('Connect SSH Socket Port Error, Please Correct it.')
    except Exception,e:
        print e

def connectly(username,password,host,port):
    username=username
    password=password
    ip=host
    port=port
    global foo
    try:
        foo = pexpect.spawn('/usr/bin/ssh -q -o StrictHostKeyChecking=no %s@%s -p%s' % (username,ip,port))
#        foo = pexpect.spawn('/usr/bin/ssh  %s@%s -p%s' % (username,ip,port))
        foo.expect('.*ssword:')
        foo.sendline(password)
        signal.signal(signal.SIGWINCH, sigwinch_passthrough)
        size = get_win_size()
        foo.setwinsize(size[0], size[1])
        foo.interact() 
#    except Exception,e:
#        print e
    except pexpect.EOF:
        raise ServerError('Connect SSH Socket Port Error, Please Correct it.')
    except pexpect.TIMEOUT:
        raise ServerError('Connect SSH TIMEOUT, Please Correct it.')

def connectaa(host):
    ip=host
    try:
        foo = pexpect.spawn('/usr/bin/ssh -q -o %s' % (ip))
        signal.signal(signal.SIGWINCH, sigwinch_passthrough)
        size = get_win_size()
        foo.setwinsize(size[0], size[1])
        foo.interact() 
    except Exception,e:
        print e

zhuan=serverinfo.keys()
aaa=[]
#output= subprocess.call("cat /etc/hosts",shell=True)
output= subprocess.check_output(["cat","/etc/hosts"])
p=re.findall(r'[^#]\w\w\w\w*', output)
for i in p:
    aaa.append(i.strip())

if __name__ == '__main__':
    print_prompt() 
    try:
        while True:
            try:
                option = raw_input("输入E/e查看非开放平台服务器或者输入(Y/y|S/s|H/h)进入开放平台服务器: ")
            except EOFError:
                print
                continue
            if option in ['E','e']:
                try:
                    print_prompt()
                    output= subprocess.call("cat /etc/hosts",shell=True)
                    print output
                    while True:
                        try:
                            zone = raw_input("请输入你需要进入的服务器简称或者输入E/e查看列表:")
                        except EOFError:
                            print 
                            continue
                        if zone in aaa:
                            if zone in zhuan:
                                port=serverinfo[zone]['port']
                            else:
                                port=serverinfo['ly']['port']
                            host=zone
                            username=serverinfo['ly']['username']
                            if zone == "xkxbs":
                                password=serverinfo['xkxbs']['password']
                            else:
                                password=serverinfo['ly']['password']
                            connectly(username, password, host, port)
                        elif zone in ['e','E']:
                            print  output
                        elif zone in ['q','Q', 'exit']:
                            sys.exit()

                except Exception,e:
                    print e
            elif option in ['Y','y']:
                try:
                    username=serverinfo['ytyy']['username']
                    print username
                    password=serverinfo['ytyy']['password']
                    host=serverinfo['ytyy']['host']
                    connectto(username,password,host)
                except Exception,e:
                    print e
            elif option in ['S','s']:
                try:
                    username=serverinfo['ytsy']['username']
                    password=serverinfo['ytsy']['password']
                    host=serverinfo['ytsy']['host']                    
                    connectto(username,password,host)
                except Exception,e:
                    print e
            elif option in ['H','h']:
                try:
                    username=serverinfo['txsh']['username']
                    password=serverinfo['txsh']['password']
                    host=serverinfo['txsh']['host']
                    connectto(username,password,host)
                except Exception,e:
                    print e
            elif option in ['Q', 'q', 'exit']:
                sys.exit()
    except IndexError:
        pass


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值