python腳本--簡單實現堡壘機登陸的過程

以前寫的大多數python文章比較粗糙,之後儘可能寫的深刻一點。python


1.腳本內容服務器

[root@python ~]# cat blj_login.py ssh

#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Date:2017-03-11
Author:Bob
'''

import os
ip_dict = {}
n = 0
with open('blj_ip.txt', 'r') as f:
    while 1:
        n += 1
        #遍歷文本的每一行內容,長度爲0時退出
        line = f.readline()
        if len(line) == 0:
            break
        #必須把n轉換成str類型,不然在if那段輸入的時候會出現死循環
        ip_dict[str(n)] = line
#print ip_dict

while 1:
    try:
        #對字典的key進行排列,初始化爲一個列表
        ip_list = sorted(ip_dict.iteritems(), key=lambda x:x[0])
        for k, v in ip_list:
            #打印列表的key和value
            print '{}: {}'.format(k,v),
            #print '%s: %s' % (k,v),
        option = raw_input("Please select server:")
        if option in ip_dict.keys():
            print ip_dict[option]
            user = raw_input("Please input username:").strip()
            cmd = 'ssh {}@{}'.format(user, ip_dict[option])
            #cmd = 'ssh %s@%s ' % (user, ip_dict[option])
            os.system(cmd)
        elif option == "exit":
            break
        else:
            print 'wrong number input!'
    except ValueError, e:
        print 'error' + str(e)


2.存放服務器ip的文本ide

[root@python ~]# cat blj_ip.txt orm

10.1.1.1
10.1.1.2
192.168.182.128


3.驗證登陸堡壘機的過程server

[root@python ~]# python blj_login.py ip

1: 10.1.1.1
2: 10.1.1.2
3: 192.168.182.128

Please select server:6
wrong number input!
1: 10.1.1.1
2: 10.1.1.2
3: 192.168.182.128

Please select server:3
192.168.182.128

Please input username:root
The authenticity of host '192.168.182.128 (192.168.182.128)' can't be established.
RSA key fingerprint is d3:b8:fa:f0:84:48:d9:1d:49:28:0b:d7:61:54:5b:a7.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.182.128' (RSA) to the list of known hosts.
root@192.168.182.128's password: 
Last login: Sat Mar 11 20:08:25 2017 from 192.168.182.1

[root@localhost ~]# exit
logout
Connection to 192.168.182.128 closed.
1: 10.1.1.1
2: 10.1.1.2
3: 192.168.182.128
Please select server:exit
相關文章
相關標籤/搜索