title: How to get output of port scanner program in python to a text file
body: <p>I am writing a program in python to scan the ports of the host and tell how many of them are open, show the time taken &amp; have also added error handling...</p>
  <p>This code is working fine but the problem is it is taking too long to scan all the ports (im talking about the time its taking to generate the full output) like it did not even complete in 1hr, is this normal? or what's wrong here.</p>
  <p>secondly, I want the output of this program in a text file... I have tried several methods but none of them did work, one of the methods I tried is written at the end of the code in comment. Any help would be greatly appreciated. Thanks, in advance!</p>
  <p>Here's the source code:</p>
  <pre><code>#!/usr/bin/env python
  import socket
  import subprocess
  import sys
  from datetime import datetime
  
  # Clear the screen
  subprocess.call('clear', shell=True)
  
  # Ask for input
  remoteServer = input(&quot;Enter a remote host to scan: &quot;)
  
  # Using the range function to specify ports (here it will scans all ports between 1 and 1024)
  
  # We also put in some error handling for catching errors
  
  try:
      remoteServerIP  = socket.gethostbyname(remoteServer)
  
      # Prints a banner with info on which host we are about to scan
      print (&quot;-&quot; * 60)
      print (&quot;Please wait, scanning remote host&quot;, remoteServerIP)
      print (&quot;-&quot; * 60)
  
      # Check what time the scan started
      t1 = datetime.now()
      
      for port in range(1,1025):  
          sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
          result = sock.connect_ex((remoteServerIP, port))
          if result == 0:
              print (&quot;Port {}:      Open&quot;.format(port))
          sock.close()
  
  except KeyboardInterrupt:
      print (&quot;You pressed Ctrl+C&quot;)
      sys.exit()
  
  except socket.gaierror:
      print ('Hostname could not be resolved. Exiting')
      sys.exit()
  
  except socket.error:
      print (&quot;Host is not available&quot;)
      sys.exit()
  
  # Checking the time again
  t2 = datetime.now()
  
  # Calculates the difference of time, to see how long it took to run the script
  total =  t2 - t1
  
  # Printing the information to screen
  print ('Scanning Completed in: ', total)
  
  '''#Text file
  f = open('Hostreport.txt', 'a')
  print(port,file=f)
  f.close()'''
  </code></pre>