如何将所有输出数据另存为Python中的文件?

问题描述 投票:0回答:1

这是一个简单的端口扫描程序。在这里一切正常。仅缺少两件事。

  1. 如何创建和保存也将每个输出覆盖到文件。

  2. 在扫描之前,程序应向主机发送ping命令以意识到主机可以访问,否则应向主机无法访问提供错误。

#! /usr/bin/python3

import socket
import subprocess
import sys
import argparse
 import pyfiglet     # Install if you get any error, pip install pyfiglet==0.7.5
  from datetime import datetime

   def scan_ports(host, startPort='1', endPort='1025'):
        # Clear the screen
        subprocess.call('cls', shell=True)

        ascii_banner = pyfiglet.figlet_format("PORT SCANNER")
        print(ascii_banner)

        # Ask for input
        host = input("Enter a host to scan: ")
        startPort = int(input("Enter beginning port number: "))
        endPort = int(input("Enter end port number: "))

        # Check what time the scan started
        t1 = datetime.now()

        # Print a banner with information on which host we are about to scan
        print("-" * 60)
        print("Please wait, scanning ---->", host)
        print("Started at ", t1.strftime("%Y-%m-%d %H:%M:%S"))
        print("Ports range ", startPort, "to", endPort)
        print("-" * 60)
        print('\n')

        # Take the user input of 'startPort' and 'endPort' numbers and place them in a range
        # These are the port numbers to be scanned
        try:
            hostIP = socket.gethostbyname(host)
            for port in range(startPort, endPort):
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.settimeout(0.5)
                result = sock.connect_ex((hostIP, port))
                # print(result) - Can be used to test reply codes, 0=ok, 61=TCP RST, etc...
                if result == 0:
                    print("Port {}: \t Open".format(port))
                elif result == 61:
                    print("Port {}: \t Rejected by Host".format(port))
                else:
                    print("Port {}: \t Close".format(port))
                sock.close()

        except KeyboardInterrupt:
            print("You pressed Ctrl+C")
            sys.exit()

        except socket.gaierror:
            print('Hostname could not be resolved. Exiting')
            sys.exit()

        except socket.error:
            print('Socket creation failed. Error code: ' +
                  str(err_msg[0]) + ' Error message: ' + err_msg[1])
            sys.exit()

        # Check the time once scan is complete, and compare the start - end times.
        t2 = datetime.now()
        total = t2 - t1

        # Print the scan time information
        print('\n')
        print('-' * 60)
        print('Scanning Completed in: ', total)
        print("Completed at ", t2.strftime("%Y-%m-%d %H:%M:%S"))
        print('Host IP ----> ', hostIP)
        print('-' * 60)

    if __name__ == "__main__":
        # Command line arguments
        parser = argparse.ArgumentParser(description='Remote Port Scanner')
        parser.add_argument('--host', action="store",
                            dest="hostIP", default='localhost')
        parser.add_argument('--start-port', action="store",
                            dest="startPort", default=1, type=int)
        parser.add_argument('--end-port', action="store",
                            dest="endPort", default=100, type=int)
        # Parse arguments
        given_args = parser.parse_args()
        hostIP, startPort, endPort = given_args.hostIP, given_args.startPort, given_args.endPort
        scan_ports(hostIP, startPort, endPort)

python python-3.x pycharm
1个回答
0
投票
  1. 您是指写入文件吗?尝试查看有关“打开时”的信息,即:

    with open(file_name, 'w+') as the_file:
        the_file.write(test_string)
    
  2. ping是指对服务器内部的已知路由发出HTTP请求吗?尝试在python中使用请求库,您将需要知道可能的状态码响应并采取行动]

    import requests
    
    x = requests.get('https://w3schools.com')
    if x.status_code == 200:
       print("ok")
    
© www.soinside.com 2019 - 2024. All rights reserved.