在好例子网,分享、交流、成长!
您当前所在位置:首页Python 开发实例Python语言基础 → 通过查找自定义文件中的大量服务器远程登录

通过查找自定义文件中的大量服务器远程登录

Python语言基础

下载此实例
  • 开发语言:Python
  • 实例大小:0.02M
  • 下载次数:3
  • 浏览次数:73
  • 发布时间:2022-03-22
  • 实例类别:Python语言基础
  • 发 布 人:琉璃康康
  • 文件格式:.zip
  • 所需积分:3
 相关标签: python SSH linux bash

实例介绍

【实例简介】在大量服务器的环境中,讲服务器登录信息按照规则写入配置文件,然后使用此命令直接匹配某一个服务器名字直接登录,无需在大脑记忆登录信息,可以跟linux bash complete完美配置,提供了基于python2和python3的两个版本,和bash_complete的配置介绍。

【实例截图】

【核心代码】

#!/usr/bin/env python3
#_*_ coding:utf-8 _*_
#Version: 3.0
#Author: Minpu Kang
#Create Date:2016-09-03
#Version 3.0 build at 2019-09-01
#Options:This is a common version in Linux/Unix Server with Python 3.0 or above.
#        Update the size Adaptive
#        Version 2 is to fix the error of exiting ssh for some special action like Ctrl C
#        Version 2.1 is to fix if any node cannot be login after reboot, reinstall or upgrading.
#        Version 2.2 is to fix with new cli of ssh-keygen if any node cannot be login after reboot, reinstall or upgrading.
#        Version 2.3 is to fix login failed once the public key has transferred to remote server
#        Version 2.4 is to support to mark the obsoleted nodes and sort the all node list
#        Version 3.0 is to support perform clis followed in the remote node directly.

import sys
import time
import os
import pexpect
import struct
import fcntl
import termios
import signal
import socket
import getopt
import datetime

usr_home = os.path.expanduser('~')
node_file="%s/nodes" % usr_home
known_hosts_file="%s/.ssh/known_hosts" % usr_home

#print all nodes
def print_nodes():
    f = open(node_file, "rb")
    f_line=f.readlines()
    node_list=[]
    print ("Currently node list:",end=' ')
    for line in f_line:
        node_info = line.decode().strip("\r\n").split(",")
        if node_info[0].startswith("#") == False:
            node_list.append(node_info[0])
    node_list.sort()
    for i in node_list:
        print (i,end=' ')
    print ("\n")
    f.close()

#set the size
def sigwinch_passthrough (sig, data):
    winsize = getwinsize()
    global ssh 
    ssh.setwinsize(winsize[0],winsize[1])

def getwinsize():
    """This returns the window size of the child tty.
    The return value is a tuple of (rows, cols).
    """
    if 'TIOCGWINSZ' in dir(termios):
        TIOCGWINSZ = termios.TIOCGWINSZ
    else:
        TIOCGWINSZ = 1074295912 # Assume
    s = struct.pack('HHHH', 0, 0, 0, 0)
    x = fcntl.ioctl(sys.stdout.fileno(), TIOCGWINSZ, s)
    return struct.unpack('HHHH', x)[0:2]

#nodes information and ssh to nodes
def login_node(node,user,host,port,password):
    print ("Start Date and Time: " time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    print ("Node: %s"%node)
    print ("Host: %s"%host)
    print ("User: %s"%user)
    if os.path.exists(known_hosts_file):
        #cmd_del_hosts = "sed -i \"/" host "/d\" " known_hosts_file
        cmd_del_hosts = "ssh-keygen -f \"" known_hosts_file "\" -R " host " > /dev/null 2>&1"
        os.system(cmd_del_hosts)
    ssh = pexpect.spawn('ssh  %s@%s -p %s' % (user, host, port))
    #signal.signal(signal.SIGWINCH, sigwinch_passthrough)
    winsize = getwinsize();
    ssh.setwinsize(winsize[0], winsize[1])
    try: 
        i = ssh.expect(['.*Are you sure you want to continue connecting (yes/no)?','.*assword.*','.*Last login: *'],timeout=60)
        if i == 0: 
            ssh.sendline('yes') 
            i = ssh.expect(['.*Are you sure you want to continue connecting (yes/no)?','.*assword.*','.*Last login: *'],timeout=60)
        if i == 1: 
            ssh.sendline(password) 
        title = "echo -n \"\033]0;%s\007\";" %node 
        os.system(title) 
    except pexpect.EOF: 
        print ("EOF:Connection timed out. Please kindly check if node info is correct or not!")
        ssh.close()
    except pexpect.TIMEOUT: 
        print ("TIMEOUT:Connection timed out. Please kindly check if node info is correct or not!") 
        ssh.close()
    return ssh

def cli_perform(node,user,host,port,password,cmd):
    if os.path.exists(known_hosts_file):
        #cmd_del_hosts = "sed -i \"/" host "/d\" " known_hosts_file
        cmd_del_hosts = "ssh-keygen -f \"" known_hosts_file "\" -R " host " > /dev/null 2>&1"
        os.system(cmd_del_hosts)
    ssh = pexpect.spawn('ssh  %s@%s -p %s' % (user, host, port))
    try: 
        i = ssh.expect(['.*Are you sure you want to continue connecting (yes/no)?','.*assword.*','.*Last login: *'],timeout=60)
        if i == 0: 
            ssh.sendline('yes') 
            i = ssh.expect(['.*Are you sure you want to continue connecting (yes/no)?','.*assword.*','.*Last login: *'],timeout=60)
        if i == 1: 
            ssh.sendline(password) 
    except pexpect.EOF: 
        #print ("EOF:Connection timed out. Please kindly check if node info is correct or not!")
        ssh.close()
    except pexpect.TIMEOUT: 
        #print ("TIMEOUT:Connection timed out. Please kindly check if node info is correct or not!") 
        ssh.close()
    prompt="\$"
    ssh.expect(prompt)
    ssh.buffer = "".encode()
    ssh.sendline(cmd)
    try:
        ssh.expect(prompt)
    except pexpect.EOF: 
        print ("\n\n" cmd ": command not found\n\n")
        ssh.close()
        return
    except pexpect.TIMEOUT: 
        print ("\n\n" cmd ": command not found\n\n")
        ssh.close()
        return
    result = ssh.before.strip().decode().split('\r\n')
    print (result[-1] prompt.split("\\")[-1] " " cmd)
    for i in result[1:-1]:
        print (i)
    #print (ssh.before.strip().decode().replace('\r\n','\n'))
    ssh.close()
    
    #prompt=""
    #prompt_num=ssh.expect(['\$','\#','\>'])
    #ssh.buffer = "".encode()
    #if prompt_num == 0:
    #    ssh.sendline(cmd)
    #    prompt="$"
    #elif prompt_num == 1:
    #    ssh.sendline(cmd)
    #    prompt="#"
    #elif prompt_num == 2:
    #    ssh.sendline(cmd)
    #    prompt=">"
    #try:
    #    ssh.expect(['\$','\#','\>'])
    #except pexpect.EOF: 
    #    print ("\n\n" cmd ": command not found\n\n")
    #    ssh.close()
    #    return
    #except pexpect.TIMEOUT: 
    #    print ("\n\n" cmd ": command not found\n\n")
    #    ssh.close()
    #    return
    #result = ssh.before.strip().decode().split('\r\n')
    #print (result[-1] prompt " " cmd)
    #for i in result[1:-1]:
    #    print (i)
    ##print (ssh.before.strip().decode().replace('\r\n','\n'))
    #ssh.close()
    


def usage(s2name):
    print ("This is used for quickly login nodes based on special node name in the file:\"%s\""%node_file)
    print ("Usage: %s node [-h] [-c \"clis\"]"%s2name)
    print ("Options:")
    print ("  node    Node     Set node name to login")
    print ("  -h      Help     Show the help")
    print ("  -c      CLI      Set the CLIs performed in remote server, more CLIs can added in double quotes and seperated with semicolon")
    print ("                   For example: -c \"ls -l;date;hostname\"\n")
    print ("Example:")
    print ("-----------------------------------\n")
    print ("  Login the node hk:")
    print ("  user@host> %s hk\n"%s2name)
    print ("  Login the node hk and perform clis:")
    print ("  user@host> %s hk -c \"ls -l;date;hostname\"\n"%s2name)
    print ("-----------------------------------\n")
    print ("Nodes info can be updated into file:%s"%node_file)
    print ("Format in the file:node_name,ip,user,password,port")
    print ("Options:")
    print ("1.Node name must be unique in the file!")
    print ("2.If no special port,set default 22!")
    print ("3.Password can be empty!")
    print ("An example without password:")
    print ("hk,192.168.10.5,admin,,22\n")
    if os.path.exists(node_file):
        print_nodes()

if __name__ == '__main__':
    s2name=(str(sys.argv[0][sys.argv[0].rfind(os.sep) 1:]).split("/")[-1])
    if len(sys.argv) < 2:
        print ("ERROR: missing node name")
        usage(s2name)
    else:
        args = sys.argv[1:]
        node = ""
        user = ""
        host = ""
        port = ""
        password = ""
        cli = ""
        if "-h" in args:
            usage(s2name)
        else:
            if os.path.exists(node_file):
                f = open(node_file, "rb")
                f_line=f.readlines()
                for i in args:
                    for line in f_line:
                        node_info = line.decode().strip("\r\n").split(",")
                        if i == node_info[0]:
                            node = node_info[0]
                            user = node_info[2]
                            host = node_info[1]
                            port = node_info[4]
                            password = node_info[3]
                            break
                f.close
            else:
                print ("Node file \"%s\" doesnot exist!"%node_file)
                usage(s2name)
                sys.exit(1)
            ### check if cli set or not
            for j in range(0,(len(args)-1)):
                if args[j] == "-c" and j < len(args)-1:
                    cli = args[j 1] ";"
                    
            if node == "":
                print ("No nodes matched")
                print_nodes()
                sys.exit(1)
            elif len(cli) == 0:
               isssh = login_node(node,user,host,port,password)
               if isssh != None:
                   isssh.interact()
                   hostName = socket.gethostname()
                   title = "echo -n \"\033]0;%s\007\";" %hostName
                   os.system(title)
                   print ("End Date and Time: " time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
            elif node != "" and cli != "":
                cli_args = cli.split(";")
                print ("====Start Date and Time: " time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) "====\n")
                print ("Node: " node ", Host: " host "\n")
                for cmd in cli_args:
                    if cmd != "":
                        cli_perform(node,user,host,port,password,cmd)
                        #cli_perform(node, host, port, user, password, cmd)
                        #print (cli_printout)
                print ("\n====End Date and Time: " time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) "====")
    sys.exit(1)
#finished

标签: python SSH linux bash

实例下载地址

通过查找自定义文件中的大量服务器远程登录

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警