Python通过ssh登录实现报文监听

Python自动化ssh登录目标主机,实现报文长度length 0监听,并根据反馈信息弹窗报警;

代码比较简陋,后续记得优化改进。

#_*_coding:utf-8 _*_
#!/usr/bin/python

import paramiko 
import re 
import sys
import win32api,win32con
import multiprocessing
import time 
import logging

 



#获取登录信息
def user_info_get():
    global host_name
    global user_name
    global ssh_loadkey
    global execmd
    
    host_name = 'xxx.xxx.xxx.xxx' #input("主机地址:")
    user_name = 'xxxxx' #input("用户名:")
    ssh_loadkey = 'xxxxx'#input("登录密码:")
    execmd = 'sudo tcpdump -v '



'''
使用正则表达式,过滤出length为0,并报警
'''
def length_judge(original_tcp_length1):
    original_tcp_length2=str(original_tcp_length1)
    
    #构造正则表达式
    filter_way=re.compile("length\W*(\d*)")
    #利用正则表达式过滤匹配length后的数字
    filter_tcp_length=filter_way.findall(original_tcp_length2)
    
    
    #将列表中的字符转化为数字
    filter_tcp_length = [ float(x) for x in filter_tcp_length ]
    #遍历数据,查找length是否为0
    #print(filter_tcp_length)
    for i in filter_tcp_length:
        #print(i)
        if i == 0:
            localtime = time.asctime( time.localtime(time.time()) )
            #调用Windows系统告警
            win32api.MessageBox(0,"发现length为0!!!", "告警!!!"+ localtime ,win32con.MB_ICONWARNING)
            break
        
def ssh_load():
    global back_normal_info
    global back_erro_info
      
    #创建SSH连接日志文件(只保留前一次连接的详细日志,以前的日志会自动被覆盖)
    paramiko.util.log_to_file("paramiko.log") 
    # 创建SSH对象
    s = paramiko.SSHClient() 
    # 允许连接不在know_hosts文件中的主机
    s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
    # 连接服务器
    s.connect(hostname=host_name, port=22, username=user_name, password=ssh_loadkey)
    # 执行命令 
    stdin, stdout, stderr = s.exec_command (execmd) #execmd传的参数free也是命令
    #如果执行sudo命令,要考虑到该命令是否需要密码验证的问题,如果需要就要进行服务器端免密设置
   # stdin, stdout, stderr = s.exec_command ('ls')
    stdin.write("Y") # Generally speaking, the first connection, need a simple interaction.
                     #一般来说,第一个连接,需要简单的交互。  
    
    stderr.channel.set_combine_stderr(stdout)
        #打开log文件,如果没有便新创建,模式a+为追加模式
    #log_file = open("message.log", "a+")
    print('登录了吗')
    
    
    while True:
        back_normal_info = stdout.readline()
        if len(back_normal_info) == 0:
            break
        print(str(back_normal_info.strip()))
        write_log_info()
        length_judge(back_normal_info)
    #关闭文件
       
    client.close()
    return stdout.channel.recv_exit_status()





 
        #返回错误信息
    back_erro= stderr.readline()
    
  
    print(back_erro)
    
    
    # 关闭连接
    s.close() 
    print('结束了吗')
      
#def monitor_action():
    #time.sleep(0.02)
    #length_judge(back_normal_info) 


def write_log_info():
    #打开log文件,如果没有便新创建,模式a+为追加模式
    log_file = open("message.log", "a+")   
    #写入信息
    log_file.writelines(back_normal_info)
    #关闭文件
    log_file.close()
 
      
 
if __name__ == '__main__':
    user_info_get()
    ssh_load()   

  

posted @ 2022-01-24 17:06  No九五二七9527  阅读(209)  评论(0)    收藏  举报