linux登录脚本(需密码方式)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os,sys

#计数器,记录错误数来强制结束程序。
err_num=0

TNS={
'172.16.132.3':{'username':'root','password':'xxxx','medo':'主Master'},
'172.16.132.14':{'username':'root','password':'xxxx','medo':'主Master'},
'172.16.132.15':{'username''root','password':'xxxx','medo':'主Master'},
'172.16.132.16':{'username':'root','password':'xxxx','medo':'主Master'},
'172.16.132.17':{'username':'root','password':'xxxxx','medo':'主Master'},
'172.16.132.18':{'username':'root','password':'xxxxx','medo':'主Master'},
'172.16.132.119':{'username':'root','password':'xxxxx','medo':'主Master'},
'172.16.132.2000':{'username':'root','password':'xxxxx','medo':'主Master'},
'172.16.132.4545454':{'username':'root','password':'xxxxx','medo':'主Master'}
}

def conn_linux(ip,username,password):
    #os.system('ssh %s/%s@%s' %(username,password,ip))
    os.system('sshpass -p %s ssh %s@%s' %(password,username,ip))

def print_choose(dicts):
    global err_num
    #获取字典中keys值存入列表
    menu= [ key for key in dicts.keys()]
    menu.sort()
    print()
    print ('%s%s%s' %('*'*12,'Linux登录工具','*'*12))
    for index,i in enumerate(menu):
        print ("* 序号: {:<4} 选择对象: {:<20}".format(index,i))
    choose_num=input('请输入序号(Q|q退出)\n')
    if choose_num == 'q' or choose_num == 'Q':
        sys.exit("QUIT!")
    #判断是否是数字
    elif choose_num.isdigit() == False: 
        print ("输入不是数字,错误次数:%s" %err_num)
        choose_menu=''
    elif int(choose_num) >= len(menu):
        err_num += 1
        print ("输入超出范围,错误次数:%s" %err_num)
        choose_menu=''
    elif choose_num == '':
        print ("输入为空,错误次数:%s" %err_num)
        choose_menu=''
    else:
        choose_menu = menu[int(choose_num)]
    return choose_menu

if __name__ == '__main__':
    while True:
        if err_num > 3:  
            sys.exit('err_num later than 3, QUIT! ')   
        else:
            choose_menu=print_choose(TNS)
            if len(choose_menu) != 0:
                print ('choose_menu:%s' %choose_menu)
                username=TNS[choose_menu]['username']
                print ('username:%s' %username)
                password=TNS[choose_menu]['password']
                ip=choose_menu
                print ('ip:%s' %choose_menu)
                conn_linux(ip,username,password)
            else:
                print ('获取值错误!')

posted @ 2019-05-04 15:51  辉bird  阅读(1051)  评论(0编辑  收藏  举报